使用Spring MVC 3.1+ WebApplicationInitializer以编程方式配置session-config和error-page

时间:2012-05-30 09:56:49

标签: java spring-mvc servlet-3.0

WebApplicationInitializer提供了一种以编程方式表示标准web.xml文件的一部分的方法 - servlet,过滤器,监听器。

但是,我无法找到使用WebApplicationInitializer表示这些元素(会话超时,错误页面)的好方法,是否仍需要维护这些元素的web.xml?

<session-config>
    <session-timeout>30</session-timeout>
</session-config>

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/uncaughtException</location>
</error-page>

<error-page>
    <error-code>404</error-code>
    <location>/resourceNotFound</location>
</error-page>

5 个答案:

答案 0 :(得分:13)

我对这个主题做了一些研究,发现对于某些配置,比如sessionTimeOut和错误页面,你仍然需要有web.xml。

请查看此Link

希望这会对你有所帮助。 欢呼声。

答案 1 :(得分:5)

使用spring-boot非常容易。

我确信无需弹簧启动也可以通过扩展SpringServletContainerInitializer来完成。它似乎就是专门为它设计的。

  

Servlet 3.0 ServletContainerInitializer旨在支持基于代码的   使用Spring的servlet容器的配置   WebApplicationInitializer SPI与(或可能在   与传统的基于web.xml的方法相结合。

示例代码(使用SpringBootServletInitializer)

public class MyServletInitializer extends SpringBootServletInitializer {

    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory containerFactory = new TomcatEmbeddedServletContainerFactory(8080);

        // configure error pages
        containerFactory.getErrorPages().add(new ErrorPage(HttpStatus.UNAUTHORIZED, "/errors/401"));

        // configure session timeout
        containerFactory.setSessionTimeout(20);

        return containerFactory;
    }
}

答案 2 :(得分:3)

实际上WebApplicationInitializer并未直接提供。但是有一种方法可以使用java配置设置sessointimeout。

您必须先创建HttpSessionListner

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

public class SessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        //here session will be invalidated by container within 30 mins 
        //if there isn't any activity by user
        se.getSession().setMaxInactiveInterval(1800);
    }

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

在此之后,只需使用您的servlet上下文注册此侦听器,该上下文将在方法WebApplicationInitializer下的onStartup中提供

servletContext.addListener(SessionListener.class);

答案 3 :(得分:1)

扩展BwithLove注释,您可以使用异常和控制器方法定义404错误页面,即@ExceptionHandler:

  1. 在DispatcherServlet中启用抛出 NoHandlerFoundException
  2. 在控制器中使用 @ControllerAdvice @ExceptionHandler
  3. WebAppInitializer类:

    public class WebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext container) {
        DispatcherServlet dispatcherServlet = new DispatcherServlet(getContext());
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        ServletRegistration.Dynamic registration = container.addServlet("dispatcher", dispatcherServlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/");
    }
    
    private AnnotationConfigWebApplicationContext getContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation("com.my.config");
        context.scan("com.my.controllers");
        return context;
    }
    }
    

    控制器类:

    @Controller
    @ControllerAdvice
    public class MainController {
    
        @RequestMapping(value = "/")
        public String whenStart() {
            return "index";
        }
    
    
        @ExceptionHandler(NoHandlerFoundException.class)
        @ResponseStatus(value = HttpStatus.NOT_FOUND)
        public String requestHandlingNoHandlerFound(HttpServletRequest req, NoHandlerFoundException ex) {
            return "error404";
        }
    }
    

    “error404”是一个JSP文件。

答案 4 :(得分:1)

在web.xml中

<session-config>
    <session-timeout>3</session-timeout>
</session-config>-->
<listener>
    <listenerclass>

  </listener-class>
</listener>

听众类

public class ProductBidRollBackListener implements HttpSessionListener {

 @Override
 public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    //To change body of implemented methods use File | Settings | File Templates.

 }

 @Override
 public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    HttpSession session=httpSessionEvent.getSession();
    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
    ProductService productService=(ProductService) context.getBean("productServiceImpl");
    Cart cart=(Cart)session.getAttribute("cart");
    if (cart!=null && cart.getCartItems()!=null && cart.getCartItems().size()>0){
        for (int i=0; i<cart.getCartItems().size();i++){
            CartItem cartItem=cart.getCartItems().get(i);
            if (cartItem.getProduct()!=null){
                Product product = productService.getProductById(cartItem.getProduct().getId(),"");
                int stock=product.getStock();
                product.setStock(stock+cartItem.getQuantity());
                product = productService.updateProduct(product);
            }
        }
    }
 }
}