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

问题描述 投票:18回答:5

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>
java spring-mvc servlet-3.0
5个回答
13
投票

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

看看这个Link

希望这对你有所帮助。干杯。


5
投票

使用弹簧靴很容易。

我相信它可以通过扩展SpringServletContainerInitializer而无需弹簧启动。它似乎是专门为它设计的。

Servlet 3.0 ServletContainerInitializer旨在使用Spring的WebApplicationInitializer SPI支持基于代码的servlet容器配置,而不是(或可能与传统的基于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;
    }
}

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

1
投票

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

  1. 在DispatcherServlet中启用抛出NoHandlerFoundException。
  2. 在控制器中使用@ControllerAdvice和@ExceptionHandler。

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文件。


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);
            }
        }
    }
 }
}
© www.soinside.com 2019 - 2024. All rights reserved.