将数据从java servlet发送到jsp

时间:2014-06-01 14:06:53

标签: java jsp servlets

我正在尝试从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

My Directory structure

2 个答案:

答案 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 LibraryExpression 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" ) %>