Custom 404 error page not working with Struts 2

前端 未结 2 1170
旧巷少年郎
旧巷少年郎 2021-01-27 00:21

I am converting a JSP/Servlet dynamic web project to Struts 2 and the custom error pages (that previously worked with the JSP/Servlet version) have stopped working.

When

相关标签:
2条回答
  • 2021-01-27 01:15

    Instead of custom error page create a custom error action that returns a result to a custom error page.

    struts.xml:

    <action name "error" class="ErrorAction">
      <result name="404">/404.jsp</result>
      <result name="500">/500.jsp</result>
    </action> 
    

    ErrorAction:

    public class ErrorAction extends ActionSupport {
    
      private Integer statusCode;
      //getter and setter
    
      @Override
      public String execute() {
        if (stausCode != null)
        switch (statusCode){
          case 404:
            return "404";
          case 500:
            return "500";
        }
      }
    }
    

    web.xml:

    <error-page>
        <error-code>404</error-code>
        <location>/error_code.jsp</location>
    </error-page>
    
    <error-page>
        <error-code>500</error-code>
        <location>/error_code.jsp</location>
    </error-page>
    

    error_code.jsp:

    <% 
     Integer statusCode = (Integer) request
                           .getAttribute("javax.servlet.error.status_code");
    
     response.sendRedirect(pageContext.getServletContext().getContextPath()
                           +"/error?statusCode="+statusCode ); 
    %>
    
    0 讨论(0)
  • 2021-01-27 01:16

    You are calling a JSP directly, and trying to use a Struts tag inside it:

    6: <s:include value="css/style2.css" />
    

    Turn this to plain html and it will work.

    Otherwise, you need to call an action.

    0 讨论(0)
提交回复
热议问题