在web项目开发中,大部分情况下,都是通过Spring默认的DispatcherServlet,转发请求到Controller,我们在Controller里处理请求。但有时候,可能有些请求我们不希望通过Spring,而是通过其他Servlet处理。如果是普通的项目,那可以在web.xml文件中进行配置,但是springBoot中是没有web.xml的。
在springBoot中有2中方法实现。
其一:使用注解注册@WebServlet(urlPatterns = "/test/*",initParams = {@WebInitParam(name = "param1", value = "value1"),})
其二:代码注册ServletRegistrationBean
创建一个@Bean,使用:return new ServletRegistrationBean(new TestServlet(), "/test1/");
public class TestServlet extends HttpServlet{ @Override public void init(ServletConfig config) throws ServletException { super.init(config); String value=config.getInitParameter("param1"); log.info("param1:{}",value); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out = resp.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Hello World</title>"); out.println("</head>"); out.println("<body>"); out.println("Hello"); out.println("</body>"); out.println("</html>"); }
1 @Bean 2 public ServletRegistrationBean testServletBean() { 3 ServletRegistrationBean testServletRegistration = new ServletRegistrationBean(new TestServlet(), "/test1/"); 4 Map<String,String> params = new HashMap<>(); 5 params.put("param1","value2"); 6 testServletRegistration.setInitParameters(params); 7 return testServletRegistration; 8 9 }