我想简单地将值传递给jsp页面。我想运行jsp文件,并且从获取servlet
显示onload数据但我得到了空:"Servlet communicated message to JSP: null "
下面是我的代码。
java代码
package api;
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);
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("javaPapers.jsp");
reqDispatcher.forward(request,response);
}
}
jsp文件
<%@ page import="api.ServletToJSP" language="java" %>
<html>
<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>
</html>
的web.xml
<servlet>
<servlet-name>ServletToJSP</servlet-name>
<servlet-class>api.ServletToJSP</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletToJSP</servlet-name>
<url-pattern>/ServletToJSP/*</url-pattern>
</servlet-mapping>
答案 0 :(得分:2)
有一些事情需要改变:
在servlet中
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);
request.getRequestDispatcher("javaPapers.jsp").forward(request,response);
}
在jsp中
<html>
<body>
Servlet communicated message to JSP: ${message}
</body>
</html>
所做的更改:
答案 1 :(得分:0)
替换
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("javaPapers.jsp");
与
RequestDispatcher reqDispatcher = request.getRequestDispatcher("javaPapers.jsp");
答案 2 :(得分:0)
使用request.setAttribute("message", message);
传递参数应该可以使用以下代码:
RequestDispatcher rd = getServletContext().getRequestDispatcher("yourPage.jsp");
rd.forward(request,response);
您还可以使用调度程序中的URL传递属性:
RequestDispatcher rd = getServletContext().getRequestDispatcher("yourPage.jsp?message=some message");
rd.forward(request,response);
您也可以使用会话对象共享信息。
session.setAttribute("message","your message");
然后使用以下命令在jsp中检索它:
String message=(String)session.getAttribute("message");
答案 3 :(得分:-1)
您必须使用上下文路径从servlet获取消息到jsp。这绝对有效,我已经做到了。
String msg = "Message from servlet to jsp";
response.sendRedirect(response.encodeRedirectURL(contextPath+"/report/test.jsp?msg="+msg));