日期:2014-05-18  浏览次数:20596 次

新手问题:servlet中设定的值如何在JSP中显示
小弟正在学习JSP,想在java中设定一个值,在jsp画面中显示出来,代码如下,又明白的麻烦请指点一下。
--index.jsp
<%@   page   contentType= "text/html;   charset=UTF-8 "   %>
<!DOCTYPE   HTML   PUBLIC   "-//W3C//DTD   HTML   4.0   Transitional//EN ">
<html>
<head>
<title> CATOFTOM </title>
<meta   http-equiv= "Content-Type "   content= "text/html;   charset=Shift_JIS ">
</head>
<body>
<form   action= "index "   method= "get ">
<table>
<tr>
<td> number1: </td>
<td> <input   type= "text "   name= "num1 "   size= "20 ">
</td>
<tr>
<td> number2: </td>
<td> <input   type= "text "   name= "num2 "   size= "20 ">
</td>
<tr>
<td> total: </td>
<td> <%=request.getAttribute( "total ")   %>
</td>
<td>

</td>
</tr>
<tr>
<td   colspan= "2 ">
<input   type= "submit "   name= "action "   value= "add ">
<input   type= "submit "   name= "action "   value= "sub ">
</td>
</tr>
</table>
</form>
</body>
</html>

--index.java
package   test;

import   java.io.IOException;

import   javax.servlet.RequestDispatcher;
import   javax.servlet.ServletException;
import   javax.servlet.http.HttpServlet;
import   javax.servlet.http.HttpServletRequest;
import   javax.servlet.http.HttpServletResponse;


public   class   Index   extends   HttpServlet   {

private   static   final   long   serialVersionUID   =   1L;
protected   void   doGet(HttpServletRequest   request,   HttpServletResponse   response)   throws   ServletException,   IOException   {

request.setAttribute( "total ",   "test ");
        RequestDispatcher   rd=request.getRequestDispatcher( "/index.jsp ");      
        rd.forward(request,response);      
}
}


------解决方案--------------------
请求的地址应该是Servlet的URL,并且要用GET方法(直接在地址栏中输地址),而不是index.jsp的URL,如果直接请求index.jsp的话,是没有值的。

至于直接在画面上显示 ${total},应该是不支持EL表达式吧。需要servelet2.4,jsp2.0

------解决方案--------------------
http://cache.baidu.com/c?word=requestdispatcher%2C%B2%CE%CA%FD&url=http%3A//topic%2Ecsdn%2Enet/t/20050713/08/4140590%2Ehtml&p=8a67c54add9d1dfc57ee9e2f5354&user=baidu