我记得我以前看书的时候,书上说<jsp:setProperty>在调用javabean的setxxx函数的时候,表单提交的参数名一定要跟javabean中的属性名一致(包括大小写),这样才会自动调用setxxx 方法将表单中的参数值传入;但是我今天看到下面这样两个文件,在javabean中没有声明同表单中的参数名一致的属性,可是却也调用了set方法,是书上写错了,还是我理解有误:
guess.jsp:
<jsp:useBean id="numguess" class="hh.guess" 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="guess.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 action="guess.jsp" 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 action="guess.jsp" method="get">
What's your guess?<INPUT type="text" name=guess>
<INPUT type="submit" value="Submit">
</form>
<%
}
%>
</font>
</BODY>
</html>
guess.java(javabean):
package hh;
import java.util.*;
public class guess {
int answer; //并没声明guess属性,可是程序运行正常,setGuess方法被调用了,这是怎么回事?
boolean success;
String hint;
int numGuesses;
public guess()
{
reset();
}
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 boolean getSuccess()
{
return success;
}
public String getHint()
{
return ""+hint;
}
public int getNumGuesses()
{
return numGuesses;
}
public void reset()
{
answer=Math.abs(new Random().nextInt()%100)+1;
success=false;
numGuesses=0;
}
}
谢谢!!
----------------解决方案--------------------------------------------------------
jsp的东西不用研究这么深,会在jsp页面里面写java代码就好了!
----------------解决方案--------------------------------------------------------