在我的servlet url-pattern上,应用程序使用" / path"但不是" / path / to"

时间:2016-08-10 18:19:13

标签: java jsp servlets web

我有以下Java servlet:

package com.controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Teste extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setAttribute("teste", "Test");
        request.getSession().setAttribute("teste", "Test Session");
        RequestDispatcher rd = request.getRequestDispatcher("teste.jsp");
        rd.forward(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }

}

以下web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>Teste</servlet-name>
        <servlet-class>com.controller.Teste</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Teste</servlet-name>
        <url-pattern>/teste</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

我可以通过网址http://localhost:8084/myapp/teste

访问servlet

我想要的是将url-pattern更改为/teste/edit,但是当我这样做,并尝试通过url http://localhost:8084/myapp/teste/edit访问servlet时,我收到以下404错误:

  

HTTP状态404 - /TrabalhoPSW/teste/teste.jsp

     

输入状态报告

     

message /TrabalhoPSW/teste/teste.jsp

     

说明请求的资源不可用。阿帕奇   的Tomcat / 8.0.27

为什么会这样?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

问题是servlet试图找到的JSP文件。当我从

改变
request.getRequestDispatcher("teste.jsp"); 

request.getRequestDispatcher("/teste.jsp");

它正常工作。

答案 1 :(得分:0)

如果您的servlet需要使用 / path / path / to ,请将web.xml中的servlet映射更改为:

datab : { "test": "bob"}
testa is null.