我正在尝试从Java servlet向JSP发送一个字符串,但我总是在字符串中得到一个null
Test.java
servlet:protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String s = "HelloWolrd";
System.out.println(s);
response.setContentType("text/jsp");
request.setAttribute("s", s);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/test.jsp");
dispatcher.forward(request,response);
}
test.jsp
<body><%= request.getAttribute("s")%> </body>
web.xml
将servlet类映射到apis。测试和网址格式为/test
。
答案 0 :(得分:0)
根据您的项目结构,test.jsp
文件位于WEB-INF
之外。再次验证它。
的Servlet
public class Test extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String s = "HelloWolrd";
System.out.println(s);
response.setContentType("text/jsp");
request.setAttribute("s", s);
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher("/test.jsp"); // CHANGE IT HERE
dispatcher.forward(request, response);
}
}
的web.xml:
<servlet>
<servlet-name>XYZ/servlet-name>
<servlet-class>apis.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>XYZ</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
查看我的另一篇文章How does a servlets filter identify next destination is another filter or a servlet/jsp?,详细了解用于url-pattern
的 Servlet匹配程序。
注意:始终尝试避免使用 Scriplet ,而是使用JavaServer Pages Standard Tag Library和Expression Language。
答案 1 :(得分:-1)
另外,根据您的eclipse目录结构,您可以在WebContent文件夹下使用JSP。所以你需要做
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/traders/test.jsp");
你可以尝试其他一些事情
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/traders/test.jsp?s=s");
然后在你的JSP中你可以做
<%= request.getAttribute("s")%>
OR
你可以使用Session
HttpSession session = request.getSession(true);
session.setAttribute("s", "s");
并做
<%= session.getAttribute( "s" ) %>