错误的请求url处理程序servlet

时间:2017-01-02 15:23:15

标签: java servlet-3.0

我有一个简单的Web应用程序。 这是我的servlet

@WebServlet(urlPatterns = "/info_send", loadOnStartup = 1)

public class ApplicationController extends HttpServlet {

    @Override
    public void init() throws ServletException {
        UsersService.addUser("admin", "admin");
    }

    @Override
    protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        PrintWriter writer = httpServletResponse.getWriter();
        httpServletResponse.setContentType("text/html");

        String login = httpServletRequest.getParameter("login");
        String password = httpServletRequest.getParameter("pass");

        if (!login.isEmpty() && !password.isEmpty() && UsersService.isLoginPresent(login)) {
            if(UsersService.isUserExist(login, password)) {
                getServletContext().getRequestDispatcher("/result.jsp").forward(httpServletRequest, httpServletResponse);
            } else {
                writer.println("User with such login is already registered.");
                getServletContext().getRequestDispatcher("/").include(httpServletRequest, httpServletResponse);
            }
        } else {
            writer.println("No such user in the system");
            getServletContext().getRequestDispatcher("/").include(httpServletRequest, httpServletResponse);
        }
        writer.close();
    }

    @Override
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        httpServletResponse.getWriter().write("The request was wrong");
    }
}

这是我的web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <error-page>
        <location>/error.jsp</location>
    </error-page>

    <error-page>
        <location>/AppExceptionHandler</location>e
    </error-page>

</web-app>

我正在使用一个简单的maven web项目。如何处理错误的网址 - 例如,如果我检查localhost:8080/home/12?在我的情况下,错误页面(error.jsp)和错误处理程序(另一个servlet)不起作用。

1 个答案:

答案 0 :(得分:0)

提供的解决方案应该适用于servlet 3.0。 您可以尝试指定错误代码,如

<error-page>
    <error-code>404</error-code>
    <location>/error.html</location>
</error-page>

同时检查

1)您的web.xml位于WEB-INF文件夹中,因此应用程序可以正确查看它。

2)error.jsp在项目的根文件夹中(根据你的路径)