浅谈JavaWeb(一)—— Servlet

什么是Servlet?

Servlet其实就是Java提供的一个接口,同时也是处理网络请求的规范,是Java Web程序的基础。

浅谈JavaWeb(一)—— Servlet_第1张图片

Servlet能做什么?

Servlet由Servlet容器来统一管理,当浏览器向Web服务器发送一个请求后,Web服务器交给Servlet容器来处理,Servlet容器解析后决定哪个具体的Servlet去执行业务逻辑。Servlet执行后,回传请求结果,最后请求结果在浏览器呈现。

浅谈JavaWeb(一)—— Servlet_第2张图片

SpringBoot中怎么注册Servlet

1.使用注解

1.1 继承HttpServlet重写doGet与doPost,添加@WebServlet注解

@WebServlet(urlPatterns = "/self/info")
public class ServletTestDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter printWriter=resp.getWriter();
        printWriter.println("");
        printWriter.println("Servlet Demo");
        printWriter.println("");
        printWriter.println("

Servlet Display Demo

"); printWriter.println("
Hello servlet
"); printWriter.println(""); printWriter.println(""); printWriter.println(""); printWriter.flush(); printWriter.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }

1.2 启动类添加注解 @ServletComponentScan,指定扫描的ServLet所在的包

@ServletComponentScan(basePackages = "com.forest.servelt")
@SpringBootApplication
public class ServletDemoApplication {

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

}

2.配置类方式

2.1继承HttpServlet重写doGet与doPost

public class ServletTestDemo2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter printWriter=resp.getWriter();
        printWriter.println("");
        printWriter.println("Servlet Demo");
        printWriter.println("");
        printWriter.println("

Servlet Display Demo

"); printWriter.println("
Hello servlet By Config
"); printWriter.println(""); printWriter.println(""); printWriter.println(""); printWriter.flush(); printWriter.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

2.2 定义配置类,实例化Servlet

@Configuration
public class ServletConfiguration {

    @Bean
    public ServletRegistrationBean myServletBean(){
        return new ServletRegistrationBean(new ServletTestDemo2(),"/getMyServlet");
    }

}

你可能感兴趣的:(java,web,spring,boot,servlet)