2017-01-02 77 views
0

我有一個簡單的Web應用程序。 這是我的servlet錯誤的請求url處理程序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)不起作用。

回答

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位於項目的根文件夾中(根據您的路徑)