Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

annotations - Custom 404 using Spring DispatcherServlet

I've set up web.xml as below. I also have an annotation-based controller, which takes in any URL pattern and then goes to the corresponding jsp (I've set that up in the -servlet.xml). However, If I go to a page that ends in .html (and whose jsp doesn't exist), I don't see the custom 404 page (and see the below error in the log). Any page that doesn't end in .html, I can see the custom 404 page.

How can I configure to have a custom 404 page for any page that goes through the DispatcherServlet?

Also want to add that if I set my error page to a static page (ie. error.htm) it works, but if I change it to a jsp (ie. error.jsp), I get the IllegalStateException. Any help would be appreciated.

log error

Caused by: java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:606)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:195)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:124)

controller

@RequestMapping(value = {"/**"})

public ModelAndView test() {

    ModelAndView modelAndView = new ModelAndView();

    return modelAndView;
}

web.xml

<servlet>
 <servlet-name>my_servlet</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

...

<servlet-mapping>
    <servlet-name>my_servlet</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>

...

<error-page>
    <error-code>404</error-code>
    <location>/error.html</location>
</error-page>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One option is to map all your error pages through your dispatcher servlet.

Create a new HTTP error controller:


@Controller
public class HTTPErrorController {

    @RequestMapping(value="/errors/404.html")
    public String handle404() {
        return "errorPageTemplate";
    }

    @RequestMapping(value="/errors/403.html")
    ...

}

Map the error pages in web.xml

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...