zoukankan      html  css  js  c++  java
  • springBoot之Servlet

    在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     }
  • 相关阅读:
    jax + php 写入数据库最简单实例
    JavaScript--水平幻灯片
    深入理解CSS3 gradient斜向线性渐变
    js基础-1
    html5 Canvas 如何自适应屏幕大小
    清除浮动塌陷
    spring MVC配置
    dom4j使用
    Visio绘制时序图
    Eclipse中引来的jar包乱码
  • 原文地址:https://www.cnblogs.com/swfzzz/p/11760149.html
Copyright © 2011-2022 走看看