小弟正在学习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);   
}
}

解决方案 »

  1.   

    刚才的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 { String action = request.getParameter("action").toString();
    if ("add".equals(action)) {
    request.setAttribute("total", "test");
        RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");   
        rd.forward(request,response);
    }
    }
    }
      

  2.   

    谢谢解答试过了不好用
    直接在画面上显示  ${total}
      

  3.   

    记得好像要jsp2.0才能用 ${total}?
    <%=request.getAttribute("total") %>
    lz这段不能显示test的数值么?
      

  4.   

    显示不了,不知道为什么,是不是我的jsp的header部分写的不对
      

  5.   

    请求的地址应该是Servlet的URL,并且要用GET方法(直接在地址栏中输地址),而不是index.jsp的URL,如果直接请求index.jsp的话,是没有值的。至于直接在画面上显示  ${total},应该是不支持EL表达式吧。需要servelet2.4,jsp2.0
      

  6.   

    to:bl_long1 
    我好像听说过这个说法,那我应该在程序里怎么改呢
      

  7.   

    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
      

  8.   

    谢谢大家热心指点,用下面两位高手的方法,问题解决了
    bl_long1() 
    aimer311(等3个裤衩了,我就散200分)
      

  9.   

    谢谢大家热心指点,用下面两位高手的方法,问题解决了  
    bl_long1()    
    aimer311(等3个裤衩了,我就散200分)