I've been trying to make it work for hours, but I just can't.
I have a java web application using spring mvc.
I modified my web.xml to handle html code errors:
...
<error-page>
<error-code>404</error-code>
<location>my/path/to/404.jsp</location>
</error-page>
...
I know it works well, because in my code I was using HttpServletResponse to send an error, which would be catch by the server and than return that page.
I was doing it this way:
response.sendError(404);
Note that it's not written that way, I'm just simplifying because I know that part works
But I didn't like that way, for my unit test to work out, I had to get the status, so I added in my code modelAndView.setStatus(HttpStatus.BAD_REQUEST);
.
At first I thought it would throw the error the same as response.sendError
, but it looks like not. So I had to set the status and than throw error with HttpServletResponse
.
So I asked myself if I could remove the HttpServletResponse
and just return the HttpStatus
so it would get my error page in my web.xml.
I handed up changing the signature of my method from public ModelAndView
to public ResponseEntity<ModelAndView>
and I tried return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
And other stuff found here:
But it returns a white and empty page. From the navigator, if I inspect element, I don't see anything.
It won't even return the page normally if I return ResponseEntity.ok(modelAndView);
I saw it was possible to do something such as this, but I think it would just be better to use HttpServletResponse and throw error even if I'm setting the status.
Plus, it's not really a big deal for the moment, because the error pages are in english, but when the page is loaded after being "trigger" by HttpServletResponse, it won't load the charset I'm setting in the page, which I do that way;
Before <html>
tag
<%@page contentType="text/html" pageEncoding="UTF-8"%>
After <head>
tag
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
So that's why I want to avoid the HttpServletResponse.sendError
. If I try to access a page that doesn't exist, the server knows it, so it will call 404 page itself, that way to charset is correct.
But that is not my problem.
Thanks for any help about that spring mvc error handling.