wrong request url handler servlet

324 Views Asked by At

I have a simple web application. This is my 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");
    }
}

This is my 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>

I am using a simple maven web project. How can I handle wrong urls - for example if I check localhost:8080/home/12? In my case error page (error.jsp) and error handler (another servlet) didn't work.

1

There are 1 best solutions below

0
On

Provided solution should work for servlet 3.0. You can try to specify error code like

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

Also check

1) your web.xml is in WEB-INF folder so the application sees it correctly.

2) error.jsp is in project's root folder (according to your path)