我想将值servlet传递给jsp。在servlet中设置值并在jsp页面中使用
我在下面得到NullPointerException是我的代码
JSP
<body>
<%
String message = (String) request.getAttribute("message");
out.println("Servlet communicated message to JSP: "+ message);
Vector vecObj = (Vector) request.getAttribute("vecBean");
out.println("Servlet to JSP communication of an object: "+vecObj.get(0));
%>
</body>
的java
public class ServletToJSP extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//communicating a simple String message.
String message = "Example source code of Servlet to JSP communication.";
request.setAttribute("message", message);
//communicating a Vector object
Vector vecObj = new Vector();
vecObj.add("Servlet to JSP communicating an object");
request.setAttribute("vecBean",vecObj);
//Servlet JSP communication
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("javaPapers.jsp");
reqDispatcher.forward(request,response);
}
}
错误日志我没有在web.xml中执行任何操作我没有在web.xml中执行任何操作
org.apache.jasper.JasperException: An exception occurred processing JSP page /javaPapers.jsp at line 21
18: out.println("Servlet communicated message to JSP: "+ message);
19:
20: Vector vecObj = (Vector) request.getAttribute("vecBean");
21: out.println("Servlet to JSP communication of an object: "+vecObj.get(0));
22: %>
23: </body>
24: </html>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:553)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:457)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.NullPointerException
org.apache.jsp.javaPapers_jsp._jspService(javaPapers_jsp.java:83)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.12 logs.
答案 0 :(得分:0)
您可能会收到NullPointerException,因为“reqDispatcher.forward(request,response);”完全创建一个新请求,vecObj变为null,因为它在请求对象中不存在。而不是使用reqDispatcher.forward使用response.redirect。