spring boot2.1.1自定义servlet的两种方式

环境

idea 2019
jdk1.8
maven3.6
spring boot2.1.1(目前springboot最高版本为2.1.8情况下,2.0以上测试过几个版本都可正常运行)
项目类型:jar

导入spring boot web启动器依赖

<dependency>
 		<groupId>org.springframework.bootgroupId>
  	    <artifactId>spring-boot-starter-webartifactId>
dependency>

注意:spring boot自动配置的前提是>>所有组件都在核心启动类所在包及其子包下,所以本篇所有java类都是在核心类所在包及其子包下创建。

方式一(自动扫描):

创建一个类继承于HttpServlet类,在类上加@WebServlet注解
package com.wn.demo.springboot.server;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/servlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("hello world");
    }
}
在配置类上添加@ServletComponentScan注解,这里方便起见就加在核心启动类上
package com.wn.demo.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@ServletComponentScan // 自动扫描自定义的servlet组件
@SpringBootApplication
public class SpringBootWeb2Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootWeb2Application.class, args);
    }

}

方式二(手动注册):

创建一个类继承于HttpServlet类
package com.wn.demo.springbootrestfulcrud.server;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("hello MyServlet");
    }
}
在配置类中注册servlet
package com.wn.demo.springbootrestfulcrud.config;

import com.wn.demo.springbootrestfulcrud.server.MyServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * server相关配置
 */
@Configuration
public class MyServerConfig {

    /**
     * 注册servlet
     * @return servlet注册对象
     */
    @Bean
    public ServletRegistrationBean<MyServlet> myServlet() {
        // 两个参数(自定义servlet, 拦截路径 可变参) 这里也可以使用匿名内部类的方式
        return new ServletRegistrationBean<>(new MyServlet(), "/myServlet");
    }
    
}

你可能感兴趣的:(spring boot2.1.1自定义servlet的两种方式)