How to prevent raw exception information appearing on JSP in Spring MVC 3.0 app?
While testing my Spring app, I uploaded a file that exceeded the maximum allowed size configured in the app.
Consequently, the following messa开发者_StackOverflow社区ge appeared on the JSP, visible to the user:
Error
Exception: org.springframework.web.multipart.MultipartException:
something went wrong here; nested exception is
org.apache.commons.fileupload.FileUploadBase$FileUploadIOException
What would I need to change to present a more user-friendly message on the JSP for the user?
For example:
Uploaded file exceeds maximum allowed size of 25MB.
I have not done Spring MVC before but I think Spring can do it.
Use Message Resources (ResourceBundle). You will have to catch the exception and create a error page where the message of the error can be displayed.
Spring uses ResourceBundleMessageSource for message resources. This example (however too simple) shows you how to configure one and use it.
Use HandlerExceptionResolver.
public class MyExceptionResolver implements HandlerExceptionResolver{
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
return new ModelAndView("jsp_to_show_error_message.jsp").
addObject("message", ex.getMessage());
}
}
Create a new jsp jsp_to_show_error_message.jsp
and put ${message}
somewhere within it. Configure MyExceptionResolver
in your xml. If you are using annotations based controller, read here.
Leaving Spring outside consideration, the Servlet API offers the possibility to attach custom error pages to certain exceptions. In this particular example, it's a matter of adding the following entry to web.xml
.
<error-page>
<exception-type>org.springframework.web.multipart.MultipartException</exception-type>
<location>errors/upload.jsp</location>
</error-page>
This way you can supply a fully custom error page in default webpage layout in flavor of errors/upload.jsp
.
精彩评论