Servlet值未在JSP中显示

时间:2013-08-15 10:19:40

标签: jsp servlets

我在servlet上测试了一个简单的测试。我想将我在servlet中所做的值显示给JSP,但它似乎没有出现。这是我的代码。

Test.java(servlet的):

public class Test extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Test() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String message = "hello";
        request.setAttribute("message", message);
        request.getRequestDispatcher("/servlet-test.jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }
}

servlet的test.jsp的(页):

<p>Message: ${message}</p>

的web.xml

<servlet>
    <description></description>
    <display-name>Test</display-name>
    <servlet-name>Test</servlet-name>
    <servlet-class>com.fluxion.mrcos.actions.Test</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Test</servlet-name>
    <url-pattern>/Test</url-pattern>
</servlet-mapping>

然后,当我要在页面中查看它时,值不会出现。总有一天可以告诉我什么是错的?

2 个答案:

答案 0 :(得分:0)

您正试图直接访问/servlet-test.jsp,这意味着servlet永远不会被调用!

您应该访问servlet的URL /Test,而不是直接转到JSP,'/ servlet-test.jsp`。

这就是通常的做法是通过将JSP放在WEB-INF目录下的目录下来隐藏JSP直接访问的原因。

然后您的请求调度程序行将更改为

request.getRequestDispatcher("/WEB-INF/jsp/servlet-test.jsp").forward(request, response);

所以您点击的网址应为

www.example.com/context/Test

答案 1 :(得分:-1)

解决了!只需将扩展名添加到 url-pattern

即可

<强>的web.xml:

<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/Test.do</url-pattern>

我也删除了 request.getRequestDispatcher 中的WEB-INF(这是我不理解的部分,但它有效。)

request.getRequestDispatcher("/servlet-test.jsp").forward(request, response);