Custom page not found and other error webpages in Spring 3.0 - spring

I want to display a custom 404 page not found error page (among others). I'm using Spring 3.0 and don't know how to do this.. I know I can specify a jsp page in web.xml to handle 404 errors. But I want Spring's environment for my error pages. So I tried simply returning a ModelAndView that's basically an error page. But the problem there is once I do this:
response.sendError(HttpServletResponse.SC_NOT_FOUND);
Then the whole request just gets forwarded back to the container's default 404 page. How are we supposed to handle error pages in Spring 3.0?

In Servlet 2.4, response.sendError() and response.setStatus() are treated differently. The former is handled by container, but the latter gives option to provide the response yourself. That means, you have to use response.setStatus(HttpServletResponse.SC_NOT_FOUND). Please also see How do I return a 403 Forbidden in Spring MVC?

Related

Spring MVC: how to handle incoming request to wrong context path

How do we handle incoming request to a wrong contextpath in spring mvc?
I have deployed a spring mvc application having contextpath as
http://exampledomain.com/mycontext
But when I try accessing url http://exampledomain.com/wrongcontext I get error as HTTP Status 404 - /wrongcontext/
I have implemented error handling which works fine for all wrong url when correct context path is used but it does not work for wrong context path.
I am trying to understand how do we redirect all incoming request to specific page in production environment..
thanks in advance
Your application can only see requests to its context /mycontext There is nothing your application can do about requests to other contexts.
You can however deploy an application at the root context / and implement an error handler there.
Check out this answer: How to customize JBoss AS7 404 page
That answer relates to JBoss, but the same idea will apply on other servers.
It is not possible to handle wrong context path requests in Spring since it only will handle the requests which goes to your context root. You have to take a look at server configuration parameters to redirect those kind of requests. If you are working on Tomcat, check path parameter of context.xml:
https://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Defining_a_context
We can use #ExceptionHandler inside a #Controller or #ControllerAdvice to handle such kind of exceptions and decide on the view page to be rendered.
#ExceptionHandler({ HttpRequestMethodNotSupportedException.class,
HttpMediaTypeNotSupportedException.class, HttpMediaTypeNotAcceptableException.class,
MissingPathVariableException.class, MissingServletRequestParameterException.class,
ServletRequestBindingException.class,MethodArgumentNotValidException.class, MissingServletRequestPartException.class,
NoHandlerFoundException.class})
public ModelAndView handleException(){
return new ModelAndView("errorpage");
}

Force Spring to always report exceptions as JSON

How do I force Spring to always convert uncaught exception to JSON instead of HTML page?
This is what I get when request is made from Chrome's REST client plugin:
{
timestamp: 1425041457798
status: 404
error: "Not Found"
exception: "com.some.my.Exception"
message: "/rrr does not exist"
path: "/test/rrr"
}
But this is what I get when I access it from browser or from Jersey API (you see parsed HTML):
Whitelabel Error PageThis application has no explicit mapping for /error, so you are seeing this as a fallback.Fri Feb 27 13:37:27 CET 2015There was an unexpected error (type=Not Found, status=404).No message available
I know this can be done somehow by setting the request headers but I want JSON response to be the only variant.
First we need add some exception resolver for exception that trows inside controllers. I prefer extend ResponseEntityExceptionHandler and add own method, but there is a great article on spring.io: http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
After that if you still get following page you can override org.springframework.boot.autoconfigure.web.ErrorController. There are an example: BasicErrorController. But this works only if you use spring boot application with embedded container. For example, if you will create war file form spring boot project and will deploy under tomcat, you will get standard tomcat error page.
So this mean that ErrorController is not common solution.
In my case i throws exceptions inside filters, that why /error page shown. So solution will be write own filter that converts exceptions to JSON representation. This solution should work for every container/server, and you can get more information about exception.

How to send the send status code as response for 404 instead of 404.jsp as a html reponse in spring?

I created web application in spring and handled exception mappings for 404 and 500.If system doesn't find any resources for requested URL it redirects into custom 404.jsp instead of regular 404 page.Everything works fine till have decided to add a webservice in my app.I have included one more controller as a webservice there is no view for this controller and this needs to be invoke through curl command.
User may get into change the curl script.If they changed the URL it should show 404 status code.But it returns the custom 404.jsp as a html response instead of status code.Because dispatcher servlet will takes all urls with /*.
How I can solve this issue?
Please share your suggestions.
Spring 3.2 introduced the #ControllerAdvice, and as mentioned in the documentation:
It is typically used to define #ExceptionHandler
That means you can use the #ControllerAdvice to assist your #Controller like the following:
#ControllerAdvice
class GlobalControllerExceptionHandler {
#ResponseStatus(HttpStatus.NOT_FOUND) // 404
#ExceptionHandler(Exception.class)
public void handleNoTFound() {
// Nothing to do
}
}
For further details please refer to this tutorial and this answer.

Spring mapping a .jsp with parameters to a .jsp (404) error

I have a 3rd party .jsp that I am trying to use in my SpringMVC 3.2 application.
the URL call looks like this:
http://localhost:8080/dms/pcc.jsp/Page/q/0/AttributescumentID=eJQAyAEYASgBJAFMAMgAlADIARgBsAG8AZwBvAC4AdABpAGYA0
I am getting a 404 error. How do I map this in my web.xml?
when I call
http://localhost:8080/dms/pcc.jsp
it works (well, no 404 errors) but I need to send it the parameters.
Changing the 3rd party jsp might be problematic, so how does one map this call straight to the jsp?
Thanks in advance.
Really a broad question. I would start with checking mapping in #Controller, then move into application-config.xml and then web.xml.
It would be nice if you would look at sample Spring Application.
If call to http://localhost:8080/dms/pcc.jsp works, you should try following thing.
http://localhost:8080/dms/pcc.jsp?AttributescumentID=eJQAyAEYASgBJAFMAMgAlADIARgBsAG8AZwBvAC4AdABpAGYA0&otherParams=something
The Page/q/0/ part in URL seems to be messing things up for you. If these also are parameters to be sent, send it the way explained above.

Change header at Included JSP with Spring MVC

It is very interesting for me but I have simple Spring MVC application and JSP page. At Jsp pages which are included I would like to add a cookie to my application. However despite of setting it, It could not resolved at runtime.
this is the code at my included jsp page.
<% response.addCookie(new Cookie("test3","test3")); %>
I prefer writing some of the parts of the our application at jsp level over writing at controller.
What I can just say is that I am using Tuckey UrlRewrite and at instead of my jsp pages when I call my method, it is working fine. And at my called method I can see that the inital response object at my MVC controller is wrapped by another HttpServletResponse object. It seems that headers and cookies could not be changed after forwarded to jsp?
Any help?
PS: I have updated my question to make it clear regarding it is jsp included page.
JSP is part of the response. You need to ensure that that line is exeucted before the response is been committed. Otherwise you end up with IllegalStateException: response already committed in the server logs. So put it in the very top of the JSP page, before any HTML is been sent to the response. Or, better, just put it in a Spring controller or a servlet or filter, far before the forward to JSP takes place.
You also need to ensure that you aren't altering the response inside a JSP file which is included by <jsp:include>. It will be plain ignored. See also the RequestDispatcher#include() javadoc:
The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.

Resources