Rectangle 27 250

Since I spent a lot of time on this issue, I thought I'd share my solution. Since spring 3.0.4, there is a configuration parameter that is called <mvc:resources/> (more about that on the reference documentation website) which can be used to serve static resources while still using the DispatchServlet on your site's root.

In order to use this, use a directory structure that looks like the following:

src/
 springmvc/
  web/
   MyController.java
WebContent/
  resources/
   img/
    image.jpg
  WEB-INF/
    jsp/
      index.jsp
    web.xml
    springmvc-servlet.xml

The contents of the files should look like:

package springmvc.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloWorldController {

 @RequestMapping(value="/")
 public String index() {
  return "index";
 }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- not strictly necessary for this example, but still useful, see http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-controller for more information -->
 <context:component-scan base-package="springmvc.web" />

    <!-- the mvc resources tag does the magic -->
 <mvc:resources mapping="/resources/**" location="/resources/" />

    <!-- also add the following beans to get rid of some exceptions -->
 <bean      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
 <bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
 </bean>

    <!-- JSTL resolver -->
 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>

</beans>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h1>Page with image</h1>
<!-- use c:url to get the correct absolute path -->
<img src="<c:url value="/resources/img/image.jpg" />" />

This example should be in the Spring user guide - it's the best I've seen on this topic. Thanks Joris!

This definitely did the trick for me -- merely rozky's advice is what I started out doing but for some reason any page, other than my home-page, was rendering the resource-URL's relative to the page -- following this advice renders them relative to my app's context-root instead -- and works perfectly! Thanks!

thanks! I was pulling my hair out until I changed the line: <mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/web-resources/" /> to <mvc:resources mapping="/resources/**" location="/resources/" />

As @Bane pointed out, the <c:url value=... /> is a key part of this solution. Would you (or anyone) mind telling me why? Thanks!

You can also use <mvc:resources mapping="/**" location="/resources/" /> and it will be mapped to the root. (i.e: The root will contain both resources AND the jsps). This can save you using c:url everywhere

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc
Rectangle 27 250

Since I spent a lot of time on this issue, I thought I'd share my solution. Since spring 3.0.4, there is a configuration parameter that is called <mvc:resources/> (more about that on the reference documentation website) which can be used to serve static resources while still using the DispatchServlet on your site's root.

In order to use this, use a directory structure that looks like the following:

src/
 springmvc/
  web/
   MyController.java
WebContent/
  resources/
   img/
    image.jpg
  WEB-INF/
    jsp/
      index.jsp
    web.xml
    springmvc-servlet.xml

The contents of the files should look like:

package springmvc.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloWorldController {

 @RequestMapping(value="/")
 public String index() {
  return "index";
 }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- not strictly necessary for this example, but still useful, see http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-controller for more information -->
 <context:component-scan base-package="springmvc.web" />

    <!-- the mvc resources tag does the magic -->
 <mvc:resources mapping="/resources/**" location="/resources/" />

    <!-- also add the following beans to get rid of some exceptions -->
 <bean      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
 <bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
 </bean>

    <!-- JSTL resolver -->
 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>

</beans>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h1>Page with image</h1>
<!-- use c:url to get the correct absolute path -->
<img src="<c:url value="/resources/img/image.jpg" />" />

This example should be in the Spring user guide - it's the best I've seen on this topic. Thanks Joris!

This definitely did the trick for me -- merely rozky's advice is what I started out doing but for some reason any page, other than my home-page, was rendering the resource-URL's relative to the page -- following this advice renders them relative to my app's context-root instead -- and works perfectly! Thanks!

thanks! I was pulling my hair out until I changed the line: <mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/web-resources/" /> to <mvc:resources mapping="/resources/**" location="/resources/" />

As @Bane pointed out, the <c:url value=... /> is a key part of this solution. Would you (or anyone) mind telling me why? Thanks!

You can also use <mvc:resources mapping="/**" location="/resources/" /> and it will be mapped to the root. (i.e: The root will contain both resources AND the jsps). This can save you using c:url everywhere

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc
Rectangle 27 250

Since I spent a lot of time on this issue, I thought I'd share my solution. Since spring 3.0.4, there is a configuration parameter that is called <mvc:resources/> (more about that on the reference documentation website) which can be used to serve static resources while still using the DispatchServlet on your site's root.

In order to use this, use a directory structure that looks like the following:

src/
 springmvc/
  web/
   MyController.java
WebContent/
  resources/
   img/
    image.jpg
  WEB-INF/
    jsp/
      index.jsp
    web.xml
    springmvc-servlet.xml

The contents of the files should look like:

package springmvc.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloWorldController {

 @RequestMapping(value="/")
 public String index() {
  return "index";
 }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- not strictly necessary for this example, but still useful, see http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-controller for more information -->
 <context:component-scan base-package="springmvc.web" />

    <!-- the mvc resources tag does the magic -->
 <mvc:resources mapping="/resources/**" location="/resources/" />

    <!-- also add the following beans to get rid of some exceptions -->
 <bean      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
 <bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
 </bean>

    <!-- JSTL resolver -->
 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>

</beans>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h1>Page with image</h1>
<!-- use c:url to get the correct absolute path -->
<img src="<c:url value="/resources/img/image.jpg" />" />

This example should be in the Spring user guide - it's the best I've seen on this topic. Thanks Joris!

This definitely did the trick for me -- merely rozky's advice is what I started out doing but for some reason any page, other than my home-page, was rendering the resource-URL's relative to the page -- following this advice renders them relative to my app's context-root instead -- and works perfectly! Thanks!

thanks! I was pulling my hair out until I changed the line: <mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/web-resources/" /> to <mvc:resources mapping="/resources/**" location="/resources/" />

As @Bane pointed out, the <c:url value=... /> is a key part of this solution. Would you (or anyone) mind telling me why? Thanks!

You can also use <mvc:resources mapping="/**" location="/resources/" /> and it will be mapped to the root. (i.e: The root will contain both resources AND the jsps). This can save you using c:url everywhere

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc
Rectangle 27 15

There's another stack overflow post that has an excellent solution.

It doesn't seem to be Tomcat specific, is simple, and works great. I've tried a couple of the solutions in this post with spring mvc 3.1 but then had problems getting my dynamic content served.

In brief, it says add a servlet mapping like this:

<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/images/*</url-pattern>
</servlet-mapping>

Great! Out of all the solutions I've been searching, this worked perfectly :)

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc
Rectangle 27 15

There's another stack overflow post that has an excellent solution.

It doesn't seem to be Tomcat specific, is simple, and works great. I've tried a couple of the solutions in this post with spring mvc 3.1 but then had problems getting my dynamic content served.

In brief, it says add a servlet mapping like this:

<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/images/*</url-pattern>
</servlet-mapping>

Great! Out of all the solutions I've been searching, this worked perfectly :)

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc
Rectangle 27 15

There's another stack overflow post that has an excellent solution.

It doesn't seem to be Tomcat specific, is simple, and works great. I've tried a couple of the solutions in this post with spring mvc 3.1 but then had problems getting my dynamic content served.

In brief, it says add a servlet mapping like this:

<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/images/*</url-pattern>
</servlet-mapping>

Great! Out of all the solutions I've been searching, this worked perfectly :)

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc
Rectangle 27 46

This problem is solved in spring 3.0.4.RELEASE where you can use <mvc:resources mapping="..." location="..."/> configuration element in your spring dispatcher configuration file.

Though not actually "wrong", this answer is too brief because Spring's own documentation (which you referenced as your answer) appears to be missing something. Check Joris's answer for a more complete answer... not the fact that it's lengthy but the fact that he mentions the use of <c:url ...> which neither your answer nor Spring's dox make mention of -- and which proved to be a critical part of the solution.

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc
Rectangle 27 46

This problem is solved in spring 3.0.4.RELEASE where you can use <mvc:resources mapping="..." location="..."/> configuration element in your spring dispatcher configuration file.

Though not actually "wrong", this answer is too brief because Spring's own documentation (which you referenced as your answer) appears to be missing something. Check Joris's answer for a more complete answer... not the fact that it's lengthy but the fact that he mentions the use of <c:url ...> which neither your answer nor Spring's dox make mention of -- and which proved to be a critical part of the solution.

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc
Rectangle 27 46

This problem is solved in spring 3.0.4.RELEASE where you can use <mvc:resources mapping="..." location="..."/> configuration element in your spring dispatcher configuration file.

Though not actually "wrong", this answer is too brief because Spring's own documentation (which you referenced as your answer) appears to be missing something. Check Joris's answer for a more complete answer... not the fact that it's lengthy but the fact that he mentions the use of <c:url ...> which neither your answer nor Spring's dox make mention of -- and which proved to be a critical part of the solution.

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc
Rectangle 27 38

In Spring 3.0.x add the following to your servlet-config.xml (the file that is configured in web.xml as the contextConfigLocation. You need to add the mvc namespace as well but just google for that if you don't know how! ;)

<mvc:default-servlet-handler/>

when I add this line I get: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 31 in XML document from class path resource [META-INF/spring/application-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 31; columnNumber: 35; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mvc:default-servlet-handler'.

Be sure to tackle with the order of the handler when you have some other view resolvers also.

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc
Rectangle 27 38

In Spring 3.0.x add the following to your servlet-config.xml (the file that is configured in web.xml as the contextConfigLocation. You need to add the mvc namespace as well but just google for that if you don't know how! ;)

<mvc:default-servlet-handler/>

when I add this line I get: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 31 in XML document from class path resource [META-INF/spring/application-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 31; columnNumber: 35; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mvc:default-servlet-handler'.

Be sure to tackle with the order of the handler when you have some other view resolvers also.

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc
Rectangle 27 38

In Spring 3.0.x add the following to your servlet-config.xml (the file that is configured in web.xml as the contextConfigLocation. You need to add the mvc namespace as well but just google for that if you don't know how! ;)

<mvc:default-servlet-handler/>

when I add this line I get: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 31 in XML document from class path resource [META-INF/spring/application-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 31; columnNumber: 35; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mvc:default-servlet-handler'.

Be sure to tackle with the order of the handler when you have some other view resolvers also.

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc
Rectangle 27 16

Starting with Spring Boot 1.3.0 this behavior can be configured using following property:

spring.mvc.dispatch-options-request=true

DispatcherServlet in Spring Boot is defined by DispatcherServletAutoConfiguration. You can create your own DispatcherServlet bean somewhere in your configuration classes, which will be used instead of the one in auto configuration:

@Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public DispatcherServlet dispatcherServlet() {
    DispatcherServlet dispatcherServlet = new DispatcherServlet();
    dispatcherServlet.setDispatchOptionsRequest(true);
    return dispatcherServlet;
}

But be aware that defining your DispatcherServlet bean will disable the auto configuration, so you should manually define other beans declared in the autoconfiguration class, namely the ServletRegistrationBean for DispatcherServlet.

You can create BeanPostProcessor implementation which will set the dispatchOptionsRequest attribute to true before the bean is initialized. Yoy can put this somewhere in your configuration classes:

@Bean
public DispatcherServletBeanPostProcessor dispatcherServletBeanPostProcessor() {
    return new DispatcherServletBeanPostProcessor();
}

public static class DispatcherServletBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof DispatcherServlet) {
            ((DispatcherServlet) bean).setDispatchOptionsRequest(true);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

If you had SpringBootServletInitializer in your application you could do something like this to enable OPTIONS dispatch:

public class ServletInitializer extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.getServletRegistration(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
                .setInitParameter("dispatchOptionsRequest", "true");
    }
}

That would however only work if you deployed your app as a WAR into Servlet container, as the SpringBootServletInitializer code is not executed when running your Spring Boot app using main method.

Important update: OPTIONS requests will be supported by default as of Spring Framework 4.3 (used by default for upcoming Spring Boot 1.4 release), see jira.spring.io/browse/SPR-13130 for more details.

How to handle HTTP OPTIONS requests in Spring Boot? - Stack Overflow

spring spring-mvc spring-boot http-options-method
Rectangle 27 15

Use String instead of AuthenticationResponse. If you get an empty response, the String value will be empty.

ResponseEntity<String> authenticateResponse = restTemplate.getForEntity(authenticateUrl, String.class);
ResponseEntity<Void> response = restTemplate.getForEntity(authenticateUrl,Void.class);
Void body = response.getBody();

Thanks, Hareesh. I was rather hoping restTemplate would have an elegant way of handling 204 No Content or for that matter any other http code where rest services can communicate with their client just via http codes and not having to have any payload

btw, this fails, i'd need to have the rest service have a return type(String) instead of void

String worked for me as well

rest - How to handle empty response in Spring RestTemplate - Stack Ove...

spring rest jackson resttemplate
Rectangle 27 15

I'll talk about Spring and @Transactional but the advise applies for many other frameworks also.

This is an inherent problem with proxy based aspects. It is discussed in the spring documentation here:

There are a number of possible solutions.

Refactor your classes to avoid the self-invocation calls that bypass the proxy.

Advantages of this approach are its simplicity and that there are no ties to any framework. However, it may not be appropriate for a very transactional heavy code base as you'd end up with many trivially small classes.

Internally in the class get a reference to the proxy.

This can be done by injecting the proxy or with hard coded " AopContext.currentProxy()" call (see Spring docs above.).

This method allows you to avoid splitting the classes but in many ways negates the advantages of using the transactional annotation. My personal opinion is that this is one of those things that is a little ugly but the ugliness is self contained and might be the pragmatic approach if lots of transactions are used.

As AspectJ does not use proxies then self-invocation is not a problem

This is a very clean method though - it is at the expense of introducing another framework. I've worked on a large project where AspectJ was introduced for this very reason.

Refactor your code to use manual transaction demarcation - possibly using the decorator pattern.

An option - but one that requires moderate refactoring, introducing additional framework ties and increased complexity - so probably not a preferred option

Usually splitting up the code is the best answer and can also be good thing for seperation of concerns also. However, if I had a framework/application that heavily relied on nested transactions I would consider using AspectJ to allow self-invocation.

thanks best answer so far. So i think i'll use AopContext.currentProxy() only on some very specific cases since i'm not on a heavy transactionnal app

java - How to handle internal calls on Spring/EJB/Mockito... proxies? ...

java hibernate spring java-ee ejb
Rectangle 27 14

You should consider to use HTTP status codes to indicate whether or not the delete operation succeeds rather than redirects. For example HTTP 200 OK (or HTTP 204 No Content) to indicate that the operation was successful, and HTTP 404 Not Found if the resource you are trying to access does not exist, HTTP 405 Method Not Allowed if the delete operation is not allowed, etc. Based on the response status, the client can decide whether or not to keep the referenced resource (in your case the object that is referenced by item/{id} ).

@ResponseStatus(value = HttpStatus.NO_CONTENT)
HandlerExceptionResolver

Okay let's say I want to use HTTP405 since resource cannot be deleted. How do I tell user which entity couldn't be deleted? Can I simply put it in the Model and than on JSP page try if there is such property in model?

It is the other way around. The client sends the id of the resource ,items/{id}, that it intends to delete, see my update.

java - How to handle RESTful delete in Spring MVC - Stack Overflow

java spring rest spring-mvc
Rectangle 27 21

A word upfront: if you just need a "static" error page without much logic and model preparation, it should suffice to put a <error-page>-Tag in your web.xml (see below for an example).

Otherwise, there might be better ways to do this, but this works for us:

We use a servlet <filter> in the web.xml that catches all Exceptions and calls our custom ErrorHandler, the same we use inside the Spring HandlerExceptionResolver.

<filter>
   <filter-name>errorHandlerFilter</filter-name>
   <filter-class>org.example.filter.ErrorHandlerFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>errorHandlerFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>
public class ErrorHandlerFilter implements Filter {

  ErrorHandler errorHandler;

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    try {
      filterChain.doFilter(request, response);
    } catch (Exception ex) {
      // call ErrorHandler and dispatch to error jsp
      String errorMessage = errorHandler.handle(request, response, ex);
      request.setAttribute("errorMessage", errorMessage);
      request.getRequestDispatcher("/WEB-INF/jsp/error/dispatch-error.jsp").forward(request, response);
    }

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    errorHandler = (ErrorHandler) WebApplicationContextUtils
      .getRequiredWebApplicationContext(filterConfig.getServletContext())
      .getBean("defaultErrorHandler");
  }

  // ...
}

I believe this should work pretty much the same for FreeMarker templates. Of course if your error view throws an error, you're more or less out of options.

To also catch errors like 404 and prepare the model for it, we use a filter that is mapped to the ERROR dispatcher:

<filter>
   <filter-name>errorDispatcherFilter</filter-name>
   <filter-class>org.example.filter.ErrorDispatcherFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>errorDispatcherFilter</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>ERROR</dispatcher>
</filter-mapping>

<error-page>
  <error-code>404</error-code>
  <location>/WEB-INF/jsp/error/dispatch-error.jsp</location>
</error-page>
<error-page>
  <exception-type>java.lang.Exception</exception-type>
  <location>/WEB-INF/jsp/error/dispatch-error.jsp</location>
</error-page>
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

  final HttpServletRequest request = (HttpServletRequest) servletRequest;

  // handle code(s)
  final int code = (Integer) request.getAttribute("javax.servlet.error.status_code");
  if (code == 404) {
    final String uri = (String) request.getAttribute("javax.servlet.error.request_uri");
    request.setAttribute("errorMessage", "The requested page '" + uri + "' could not be found.");
  }

  // notify chain
  filterChain.doFilter(servletRequest, servletResponse);
}

I have not used the custom error handler. All I want to do is - if template processing fails, then redirect user to a static errorpage. Browser shows the error page content but it also shows the stack trace. Any clues? I am using Spring. Just plain servlets with freemarker for views.

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'defaultErrorHandler' is defined
request.getRequestDispatcher("/WEB-INF/jsp/error/dispatch-error.jsp").forward(request, response);

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - How to handle exceptions thrown while rendering a view in Sprin...

java spring spring-mvc freemarker
Rectangle 27 17

If I understand your issue correctly, I think I have found a solution to your problem:

I had the same issue where raw output was shown with no css styles, javascripts or jquery files found.

I just added mappings to the "default" servlet. The following was added to the web.xml file:

<servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.css</url-pattern>
 </servlet-mapping>

 <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
 </servlet-mapping>

This should filter out the javascript and css file requests from the DispatcherRequest object.

Again, not sure if this is what you are after, but it worked for me. I think "default" is the name of the default servlet within JBoss. Not too sure what it is for other servers.

I actually don't want to use the default servlet- that couples me to jboss/tomcat

@hamo why is that a problem? (this is a genuine question, not a argumentative retort). You will need be running the server (jboss/tomcat/jetty) anyways for spring to run, right?

<url-pattern>
<servlet-mapping>

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc
Rectangle 27 17

If I understand your issue correctly, I think I have found a solution to your problem:

I had the same issue where raw output was shown with no css styles, javascripts or jquery files found.

I just added mappings to the "default" servlet. The following was added to the web.xml file:

<servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.css</url-pattern>
 </servlet-mapping>

 <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
 </servlet-mapping>

This should filter out the javascript and css file requests from the DispatcherRequest object.

Again, not sure if this is what you are after, but it worked for me. I think "default" is the name of the default servlet within JBoss. Not too sure what it is for other servers.

I actually don't want to use the default servlet- that couples me to jboss/tomcat

@hamo why is that a problem? (this is a genuine question, not a argumentative retort). You will need be running the server (jboss/tomcat/jetty) anyways for spring to run, right?

<url-pattern>
<servlet-mapping>

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc
Rectangle 27 17

If I understand your issue correctly, I think I have found a solution to your problem:

I had the same issue where raw output was shown with no css styles, javascripts or jquery files found.

I just added mappings to the "default" servlet. The following was added to the web.xml file:

<servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.css</url-pattern>
 </servlet-mapping>

 <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
 </servlet-mapping>

This should filter out the javascript and css file requests from the DispatcherRequest object.

Again, not sure if this is what you are after, but it worked for me. I think "default" is the name of the default servlet within JBoss. Not too sure what it is for other servers.

I actually don't want to use the default servlet- that couples me to jboss/tomcat

@hamo why is that a problem? (this is a genuine question, not a argumentative retort). You will need be running the server (jboss/tomcat/jetty) anyways for spring to run, right?

<url-pattern>
<servlet-mapping>

How to handle static content in Spring MVC? - Stack Overflow

spring-mvc