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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10813993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:41:56  来源:igfitidea点击:

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

javaspring-mvcservlet-3.0

提问by Biju Kunjummen

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

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

However I have not been able to figure out a good way to represent these elements(session-timeout, error-page) using WebApplicationInitializer, is it necessary to still maintain a web.xml for these elements?

但是,我还没有找到一种使用 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>

采纳答案by Japan Trivedi

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.

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

Have look at this Link

看看这个链接

Hope this helps you. Cheers.

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

回答by Matt MacLean

Using spring-boot it's pretty easy.

使用 spring-boot 非常简单。

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.

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

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.

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

Sample code (using SpringBootServletInitializer)

示例代码(使用 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;
    }
}

回答by Satyajitsinh Raijada

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

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

You have to create a HttpSessionListnerfirst :

你必须先创建一个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");
    }
}

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

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

servletContext.addListener(SessionListener.class);

回答by nmeln

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

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

  1. Enable throwing NoHandlerFoundExceptionin DispatcherServlet.
  2. Use @ControllerAdviceand @ExceptionHandlerin controller.
  1. 在 DispatcherServlet 中启用抛出NoHandlerFoundException
  2. 在控制器中使用@ControllerAdvice@ExceptionHandler

WebAppInitializer class:

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 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.

“error404”是一个 JSP 文件。

回答by ycli

In web.xml

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