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

Java 使用Spring MVC 3.1+;WebApplicationInitializer以编程方式配置会话配置和错误页面,java,spring-mvc,servlet-3.0,Java,Spring Mvc,Servlet 3.0,提供了一种以编程方式表示标准web.xml文件的良好部分的方法—servlet、筛选器和侦听器 但是,我还没有找到一种使用WebApplicationInitializer表示这些元素(会话超时、错误页面)的好方法,是否仍需要为这些元素维护web.xml 30 java.lang.Exception /未捕获异常 404 /未找到资源 我对这个主题做了一些研究,发现对于一些配置,如sessionTimeOut和错误页面,您仍然需要web.xml 看看这个 希望这对你有帮助。 干杯。使用弹簧靴非

提供了一种以编程方式表示标准web.xml文件的良好部分的方法—servlet、筛选器和侦听器

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


30
java.lang.Exception
/未捕获异常
404
/未找到资源

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

看看这个

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

使用弹簧靴非常简单

我相信,通过扩展,它也可以在没有spring boot的情况下完成。似乎这就是它的特殊设计

Servlet 3.0 ServletContainerInitializer设计用于支持基于代码的 使用Spring的 WebApplicationInitializer SPI与(或可能与)相反 与传统的基于web.xml的方法相结合

示例代码(使用SpringBootServletilizer)


实际上,
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:

  • 在DispatcherServlet中启用抛出NoHandlerFoundException
  • 在控制器中使用@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文件。

    在web.xml中

    <session-config>
        <session-timeout>3</session-timeout>
    </session-config>-->
    <listener>
        <listenerclass>
    
      </listener-class>
    </listener>
    
    
    3.
    -->
    
    侦听器类

    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);
                }
            }
        }
     }
    }
    
    公共类ProductBidRollBackListener实现HttpSessionListener{
    @凌驾
    已创建公共无效会话(HttpSessionEvent HttpSessionEvent){
    //要更改已实现方法的主体,请使用文件|设置|文件模板。
    }
    @凌驾
    公共无效sessionDestroyed(HttpSessionEvent HttpSessionEvent){
    HttpSession session=httpSessionEvent.getSession();
    WebApplicationContext context=WebApplicationContextIls.getWebApplicationContext(session.getServletContext());
    ProductService=(ProductService)context.getBean(“productServiceImpl”);
    购物车=(购物车)会话.getAttribute(“购物车”);
    如果(购物车!=null&&cart.getCartItems()!=null&&cart.getCartItems().size()>0){
    
    对于(int i=0;iThank@Japs,是的,听起来这些需要通过web.xml文件来完成。情况是否发生了变化,或者我们仍然需要一个
    web.xml
    ?我不确定。最近还没有在最新的spring版本中尝试过。对于错误页面,您可以使用
    @ExceptionHandler
    注释方法或
    @ControllerAdvice
    类e配置。对于会话配置,为会话添加侦听器,并使用setMaxInactiveInterval()指定超时。
    @ExceptionHandler
    仅适用于您在控制器中抛出的错误。它不适用于SpringSecurity 401/403或普通404。我认为servletContainer()中缺少@Bean注释方法。这仅适用于嵌入式tomcat。在
    application.properties中设置
    server.session timeout=20
    更容易。值得注意的是,JavaDoc for SpringServletContainerInitializer明确指出“这个类既不是为扩展而设计的,也不是为扩展而设计的。它应该被视为一个内部类型”。所以我认为说“它似乎是专门为它设计的”是不正确的。“您从JavaDoc中引用的话是正确的-该类确实支持基于代码的配置,但它是通过委托给WebApplicationInitializer来实现的,而不是通过提供扩展点本身。
    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);
                }
            }
        }
     }
    }