方法1
1、新建一个类继承HttpServlet类,实现相关方法,并加上@WebServlet注解;urlPatterns为请求路径
@WebServlet(name = "FristServlet",urlPatterns = "/ ")
public class FristServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("FristServlet Runnint...");
PrintWriter writer = resp.getWriter();
writer.write("success...");
writer.flush();
writer.close();
}
}
2、在SpringBoot启动类上加上@ServletComponentScan注解扫描Servlet
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ServletComponentScan
public class BootDemoApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(BootDemoApplication.class);
springApplication.setBannerMode(Banner.Mode.OFF);
ApplicationContext ac = springApplication.run(args);
}
}
方法2
1、新建一个类继承HttpServlet类,实现相关方法
public class FristServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("FristServlet Runnint...");
PrintWriter writer = resp.getWriter();
writer.write("success...");
writer.flush();
writer.close();
}
}
2、在SpringBoot启动类上加上@ServletComponentScan注解扫描Servlet,并将Servlet注册到容器
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ServletComponentScan
public class BootDemoApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(BootDemoApplication.class);
springApplication.setBannerMode(Banner.Mode.OFF);
ApplicationContext ac = springApplication.run(args);
}
@Bean
public ServletRegistrationBean servletRegistrationBean(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new FristServlet());
servletRegistrationBean.addUrlMappings("/frist");
return servletRegistrationBean;
}
}