使用 Spring MVC 3.1+ WebApplicationInitializer 以编程方式配置会话配置和错误页



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>

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

看看这个链接

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

使用弹簧引导非常简单。

我相信它也可以在没有 spring 启动的情况下完成,也可以通过扩展 SpringServletContainerInitializer 来完成。这似乎是它专门设计的。

Servlet

3.0 ServletContainerInitializer 旨在支持基于代码 使用 Spring 的 Servlet 容器的配置 WebApplicationInitializer SPI 与(或可能在 结合)传统的基于网络.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;
    }
}

实际上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 上下文中,该上下文将在方法 onStartup 下以WebApplicationInitializer提供

servletContext.addListener(SessionListener.class);

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

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

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

最新更新