node.js实现tomcat经典例子猜数字

学jsp都时候知道tomcat有一个seesion的经典例子,猜数字。

tomcat 中有源码,JavaBean源码NumberGuessBean.java代码如下:

package num;

import java.io.Serializable;
import java.util.Random;

public class NumberGuessBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private int answer;
    private String hint;
    private int numGuesses;
    private boolean success;
    private Random random = new Random();

    public NumberGuessBean() {
        reset();
    }

    public int getAnswer() {
        return answer;
    }

    public void setAnswer(int answer) {
        this.answer = answer;
    }

    public String getHint() {
        return "" + hint;
    }

    public void setHint(String hint) {
        this.hint = hint;
    }

    public void setNumGuesses(int numGuesses) {
        this.numGuesses = numGuesses;
    }

    public int getNumGuesses() {
        return numGuesses;
    }

    public boolean getSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public void setGuess(String guess) {
        numGuesses++;

        int g;
        try {
            g = Integer.parseInt(guess);
        } catch (NumberFormatException e) {
            g = -1;
        }

        if (g == answer) {
            success = true;
        } else if (g == -1) {
            hint = "a number next time";
        } else if (g < answer) {
            hint = "higher";
        } else if (g > answer) {
            hint = "lower";
        }
    }

    public void reset() {
        answer = Math.abs(random.nextInt() % 100) + 1;
        success = false;
        numGuesses = 0;
    }
}
JSP源码numguess.jsp代码如下:

<%@ page import = "num.NumberGuessBean" %>

<jsp:useBean id="numguess" class="num.NumberGuessBean" scope="session"/>
<jsp:setProperty name="numguess" property="*"/>

<html>
<head><title>Number Guess</title></head>
<body bgcolor="white">
<font size=4>

<% if (numguess.getSuccess()) { %>

  Congratulations!  You got it.
  And after just <%= numguess.getNumGuesses() %> tries.<p>

  <% numguess.reset(); %>

  Care to <a href="numguess.jsp">try again</a>?

<% } else if (numguess.getNumGuesses() == 0) { %>

  Welcome to the Number Guess game.<p>

  I'm thinking of a number between 1 and 100.<p>

  <form method=get>
  What's your guess? <input type=text name=guess>
  <input type=submit value="Submit">
  </form>

<% } else { %>

  Good guess, but nope.  Try <b><%= numguess.getHint() %></b>.

  You have made <%= numguess.getNumGuesses() %> guesses.<p>

  I'm thinking of a number between 1 and 100.<p>

  <form method=get>
  What's your guess? <input type=text name=guess>
  <input type=submit value="Submit">
  </form>

<% } %>

</font>
</body>
</html>
仿照tomcat 我写了一个node.jsp版本,也用到了node.js module的写法。

仿照bean的NumberGuess.js 代码如下

var NumberGuess = exports.NumberGuess = function(guessObj){
	if(! guessObj){
		this.answer=0;
		this.hint='';
		this.numGuesses=0;
		this.success=false;

		this.reset();
	}else{
		this.answer=guessObj.answer;
		this.hint=guessObj.hint;
		this.numGuesses=guessObj.numGuesses;
		this.success=guessObj.success;
	}
}

NumberGuess.prototype.setGuess=function(guess) {
	this.numGuesses++;

	var g;
	if(! isNaN(guess)){
		g=guess;
	} else {
		g=-1;
	}

	if (g == this.answer) {
		this.success = true;
	} else if (g == -1) {
		this.hint = 'a number next time';
	} else if (g < this.answer) {
		this.hint = 'higher';
	} else if (g > this.answer) {
		this.hint = 'lower';
	}
};

NumberGuess.prototype.reset=function() {
	this.answer = Math.floor(Math.random() * 100) + 1;
	this.success = false;
	this.numGuesses = 0;
};
仿照jsp的guess.js代码如下:

var connect = require('connect');
var NumberGuess = require('./NumberGuess.js').NumberGuess;

var server = connect.createServer();
server.use(connect.cookieParser());
server.use(connect.session({ secret: 'keyboard cat'}));
server.use(connect.query());
server.use(function(req, res){
	var sess = req.session;
	 
	 if (! sess.guessObj) {
		sess.guessObj = new NumberGuess();
	 } else {
		//self.sessions[sid] = JSON.stringify(sess);   
		//sess = self.sessions[sid]; sess = JSON.parse(sess)
		//只序列化数据,反序列化js无类型信息,不能和java一样
		sess.guessObj = new NumberGuess(sess.guessObj);
	 }

	var guess = req.query.guess; 
	if(guess){
		sess.guessObj.setGuess(guess);
	}

	var result = '<html>'
			+'<head><title>Number Guess</title></head>'
			+'<body bgcolor="white">'
			+'<font size=4>';

	if (sess.guessObj.success) {
		result += 'Congratulations!  You got it.'
			+ 'And after just '+sess.guessObj.numGuesses +' tries.<p>'
			+' Care to <a href=".">try again</a>?';
		sess.guessObj.reset();
	} else if (sess.guessObj.numGuesses == 0) {
		result += 'Welcome to the Number Guess game.<p>'
			+'I\'m thinking of a number between 1 and 100.<p>'
			+ '<form method="get">'
			+'What\'s your guess? <input type="text" name="guess">'
			+'<input type="submit" value="Submit">'
			+'</form>';
	} else {
		result += 'Good guess, but nope.  Try <b>'+sess.guessObj.hint+'</b>.'
			+'You have made '+sess.guessObj.numGuesses+' guesses.<p>'
			+'I\'m thinking of a number between 1 and 100.<p>'
			+'<form method="get">'
			+'What\'s your guess? <input type=text name=guess>'
			+'<input type="submit" value="Submit">'
			+'</form>'; 
	}

	result += '</font></body></html>';

	res.setHeader('Content-Type', 'text/html');
	res.write(result);
	res.end();
});

server.listen(8080);

console.log('127.0.0.1:8080')

在命令行中输入node guess.js

在浏览器地址栏中输入 http://localhost:8080/,效果如下:

node.js实现tomcat经典例子猜数字_第1张图片

试试自己的运气吧,我的运气不好就不试了,这个大家应该都玩过,我就不继续截图了。

这个有点硬套,主要是试试connect对session的支持。

//self.sessions[sid] = JSON.stringify(sess);   
//sess = self.sessions[sid]; sess = JSON.parse(sess)
//只序列化数据,反序列化js无类型信息,不能和java一样

这段注释注意一下,这个知识点我搞了半天,我没想到。

你可能感兴趣的:(tomcat,jsp,function,Random,node.js,input)