SpringBoot: 2.SpringBoot整合servlet(转)

 

整合方式1:通过注解扫描完成 Servlet 组件的注册

1、编写servlet

复制代码
package com.bjsxt.servlet;

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;

/**
 * Created by Administrator on 2019/2/4.
 */
@WebServlet(name = "FirstServlet",urlPatterns = "/first")   //该servlet的名字,访问路径
public class FirstServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("firstServlet.............");
    }
}
复制代码

2、编写启动类

复制代码
package com.bjsxt;

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

/**
 * Created by Administrator on 2019/2/4.
 */
@SpringBootApplication
@ServletComponentScan   //在springboot启动时,会扫描@WebServlet,并将该类实例化
public class App {

    public static void main(String[] args){
        SpringApplication.run(App.class,args);
    }
}
复制代码

 

 整合方式二:通过方法完成 Servlet 组件的注册

1、编写servlet

复制代码
package com.bjsxt.servlet;

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;

/**
 * Created by Administrator on 2019/2/4.
 */
public class SecondServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("secondServlet.............");
    }
}
复制代码

2、编写启动类

复制代码
package com.bjsxt;

import com.bjsxt.servlet.SecondServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

/**
 * Created by Administrator on 2019/2/4.
 */
@SpringBootApplication
public class App2 {

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

    @Bean
    public ServletRegistrationBean getServletRegistrationBean(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
        bean.addUrlMappings("/second");
        return bean;
    }
}
复制代码
posted @ 2019-02-24 18:15  咫尺天涯是路人丶  阅读(1360)  评论(0编辑  收藏  举报