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

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");
}

Related

Spring MVC: log all requests, even the resource not founds

How can I log all requests in Spring MVC, even the resource not founds ones?
I guess interceptors can not log resource not found requests. What do you suggest?
Have you tried using implementation of javax.servlet.Filter?
Filter in contrary to Spring's interceptor is part of a Java's standard and is executed by the servlet container for each incoming HTTP request..
Spring MVC use exactly one servlet and that is DispatcherServlet which, as the name suggest, disptach received request to correct controller which process the request futher.
Spring even provide few concrete implementations of Filter that can log incoming request for you such as: CommonsRequestLoggingFilter or ServletContextRequestLoggingFilter.
You can choose one of the above implementations or implement Filter interface by yourself - whatever you decide, by using Filter you should be able to log every single request received by your servlet container.

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.

regarding CSRF Filter in Tomcat 7 url encoding

I work on a web application that is vulnerable to CSRF(Cross Site Request Forgery) attack. Tomcat 7 has a CSRF prevention filter. I went through the description to configure this filter.
This filter expects that we call HttpServletResponse#encodeRedirectURL(String) or HttpServletResponse#encodeURL(String).
However, I see that in my application we are not using the above mentioned methods. We forward the response using mapping.findForward(target); without touching the request or response object. Can you please let me know how or where can I integrate encodeURL() or encodeRedirectURL() methods in my code?
Any help in this regard is appreciated.
Thanks,
You can Write a Servlet and map all urls (/*) to this servlet in your web.xml file. now you can use encodeUrl method through HttpServletResponse.

Custom page not found and other error webpages in Spring 3.0

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?

How to configure spring HandlerExceptionResolver to handle NullPointerException thrown in jsp?

From a jsp is thrown a NullPointerException for example using <% null.toString(); %>
This exception is not handled by the HandlerExceptionResolver, but thrown to the web container(tomcat) and converted into a code 500 error.
How can I configure spring to get that error in my HandlerExceptionResolver ?
Details:
Spring can be configured to handle exceptions thrown inside Controllers, but not exceptions thrown by view.
Of course i can resolve the NullPointerException, but i want to design a solution that will gracefully resolve any possible problem on the web application in order to display a user friendly message to the user.
See the HandlerInterceptor interface instead. You'll want the afterCompletion method. You can then intercept the response and then set the appropriate header information to redirect to a container-configured error web page. You're right that Spring doesn't have this functionality, this is going to have to be specified by the web.xml which determines which codes map to which pages.
I have not worked with this particular bit of the spring framework, but the docs say
"Interface to be implemented by objects than can resolve exceptions thrown during handler mapping or execution, in the typical case to error views. Implementors are typically registered as beans in the application context.
Error views are analogous to the error page JSPs, but can be used with any kind of exception including any checked exception, with potentially fine-granular mappings for specific handlers."
so I'd imagine that given that NullPointer extends RuntimeException the framework isn't designed to catch it. Is there a reason the exception(s) can't be handled in the controller directly?

Resources