2012-07-24 12 views
8

Estoy utilizando Spring MVC y he configurado satisfactoriamente un WebApplicationInitializer (utilizando Tomcat's ServletContainerInitializer), sin ningún archivo web.xml. Agregar filtros (como Spring Security) y servlets (como Dispatcher) no es un problema, y ​​funcionan bien. También puedo configurar init-params si necesito hacerlo.Cómo configurar tiempo de espera de sesión, páginas de error mediante programación sin web.xml

Lo que no puedo entender es cómo configurar algunas de las etiquetas especiales que normalmente existen en el web.xml. Por ejemplo, me gustaría configurar una página de error 403 personalizada. Por lo general, me gustaría hacer esto en web.xml con:

<error-page> 
    <error-code>403</error-code> 
    <location>/accessDenied.html</location> 
</error-page> 

Pero no puedo encontrar la manera de hacer esto dentro de la WebApplicationInitializer (que tiene acceso a la ServletContext).

Tengo el mismo problema con session-timeout y welcome-files. He estado buscando durante dos días, pero todavía no he visto esto hecho programáticamente. Una vez más, el objetivo es eliminar por completo el archivo web.xml y utilizar la clase de inicializador en su lugar.

¿Alguna idea?

Respuesta

7

No parece que esto es posible a través de WebApplicationInitializer, tendrá que atenerse a web.xml de concreto esta configuración junto con algunos otros que figuran con esta pregunta - Using Spring MVC 3.1+ WebApplicationInitializer to programmatically configure session-config and error-page

+0

Gracias. Ese parece ser el caso, basado en el enlace en su respuesta. Gorrón. – BobRob

+0

[Problema de especificación del servlet para esto] (https://java.net/jira/browse/SERVLET_SPEC-50) –

2
StandardEngine standardEngine = (StandardEngine)MBeanServerFactory.findMBeanServer(null).get(0).getAttribute(new ObjectName("Catalina", "type", "Engine"), "managedResource"); 

// This is totally irresponsible and will only work if this webapp is running on the default host 
StandardContext standardContext = (StandardContext)standardEngine.findChild(standardEngine.getDefaultHost()).findChild(servletContext.getContextPath()); 

ErrorPage errorPage404 = new ErrorPage(); 
errorPage404.setErrorCode(404); 
errorPage404.setLocation("/404"); 
standardContext.addErrorPage(errorPage404); 
+0

hombre funcionó muy bien – kakabali

1

Puede utilizar somethink así:

@WebFilter(filterName = "ErrorPageFilter", urlPatterns = "/*") 
public class ErrorPageFilter extends BaseHttpFilter { 

private GlobalErrorHandler globalErrorHandler; 

@Override 
public void init(FilterConfig filterConfig) throws ServletException { 
    globalErrorHandler = BeansUtil.getBean(filterConfig.getServletContext(), GlobalErrorHandler.class); 
} 

@Override 
protected void doHttpFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { 
    chain.doFilter(request, new ErrorPageHttpServletResponseWrapper(request, response)); 
} 

private class ErrorPageHttpServletResponseWrapper extends HttpServletResponseWrapper { 
    HttpServletRequest request; 

    public ErrorPageHttpServletResponseWrapper(HttpServletRequest request, HttpServletResponse response) { 
     super(response); 
     this.request = request; 
    } 

    @Override 
    public void sendError(int sc) throws IOException { 
     globalErrorHandler.handleError(sc, request, this); 
    } 

    @Override 
    public void sendError(int sc, String msg) throws IOException { 
     sendError(sc); 
    } 
} 
} 

public interface GlobalErrorHandler { 

void handleError(int responseCode, HttpServletRequest request, HttpServletResponse httpServletRequest) throws IOException; 

void addHandler(int responseCode, String handlerDescription); 
} 
+0

Esto parece una solución real a este problema. –

0

Usted debe tratar de crear su propia SessionListener y luego añadirlo a la ServletContext de su WebApplicationInitializer ..

Algo como esto:

import javax.servlet.http.HttpSessionEvent; 
import javax.servlet.http.HttpSessionListener; 

public class SessionListener implements HttpSessionListener { 

    public void sessionCreated(HttpSessionEvent evt) { 
     System.out.println("Session created"); 
     evt.getSession().setMaxInactiveInterval(30 * 60); // That means 30 minutes. 
    } 

    public void sessionDestroyed(HttpSessionEvent evt) { 
     System.out.println("Session destroyed"); 
    } 
} 

Y luego en su WebContentInitializ er agregue esta línea:

servletContext.addListener(new SessionListener()); 
Cuestiones relacionadas