Using Spring MVC 3.1+ WebApplicationInitializer to programmatically configure session-config and error-page

后端 未结 5 2115
迷失自我
迷失自我 2020-12-14 18:19

WebApplicationInitializer provides a way to programmatically represent a good portion of a standard web.xml file - the servlets, filters, listeners.

However I have

相关标签:
5条回答
  • 2020-12-14 18:28

    I done a bit of research on this topic and found that for some of the configurations like sessionTimeOut and error pages you still need to have the web.xml.

    Have look at this Link

    Hope this helps you. Cheers.

    0 讨论(0)
  • 2020-12-14 18:30

    Actually WebApplicationInitializer doesn't provide it directly. But there is a way to set sessointimeout with java configuration.

    You have to create a HttpSessionListner first :

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

    After this just register this listener with your servlet context which will be available in WebApplicationInitializer under method onStartup

    servletContext.addListener(SessionListener.class);
    
    0 讨论(0)
  • 2020-12-14 18:35

    Using spring-boot it's pretty easy.

    I am sure it could be done without spring boot as well by extending SpringServletContainerInitializer. It seems that is what it is specifically designed for.

    Servlet 3.0 ServletContainerInitializer designed to support code-based configuration of the servlet container using Spring's WebApplicationInitializer SPI as opposed to (or possibly in combination with) the traditional web.xml-based approach.

    Sample code (using 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;
        }
    }
    
    0 讨论(0)
  • 2020-12-14 18:35

    Extending on BwithLove comment, you can define 404 error page using exception and controller method which is @ExceptionHandler:

    1. Enable throwing NoHandlerFoundException in DispatcherServlet.
    2. Use @ControllerAdvice and @ExceptionHandler in controller.

    WebAppInitializer class:

    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 class:

    @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" is a JSP file.

    0 讨论(0)
  • 2020-12-14 18:38

    In web.xml

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

    Listener Class

    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);
                }
            }
        }
     }
    }
    
    0 讨论(0)
提交回复
热议问题