SpringBoot学习笔记之Servlet使用

Springboot Servlet注册
1)、代码注册通过ServletRegistrationBean、 FilterRegistrationBean 和ServletListenerRegistrationBean 获得控制
@Bean
public ServletRegistrationBean servletRegistrationBean() {
return new ServletRegistrationBean(new MyServlet(), "/xs/*");}

2)、在 SpringBootApplication 上使用@ServletComponentScan 注解后,Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码。

@SpringBootApplication
@ServletComponentScan
public class SpringBootSampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSampleApplication.class, args);
}
}


3)、Servlet需要继承HttpServlet类
public class LiyjServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doGet(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("this is liyjServlet doposet method");
PrintWriter pw = resp.getWriter();
pw.write("hello springboot servlet register by LiyjServlet");
pw.flush();
pw.close();
}

@Override
public void init() throws ServletException {
super.init();
}
}
/**
* 这里是通过代码的形式注册一个Servlet,这种形式不需要@ServletComponentScan注解
*
* @return
*/
@Bean
public ServletRegistrationBean servletRegistrationBean(){
return new ServletRegistrationBean(new LiyjServlet(),"/web/*");
}
手动注册一个servlet

/**
* 带 @WebServlet注解的Servlet注册需要@ServletComponentScan注解的扫描
*
*/
@WebServlet(urlPatterns="/jeff/*")
public class ShanServlet extends HttpServlet {

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

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("this is ShanServlet doposet method");
PrintWriter pw = resp.getWriter();
pw.write("hello springboot servlet register by ShanServlet");
pw.flush();
pw.close();
}

@Override
public void init() throws ServletException {
super.init();
}
}

filter测试类请看com.vk.liyj.filter.LiyjFilter
Listener测试类请看 com.vk.liyj.listener.LiyjListener

http://localhost:8080/web/jeff


源码下载:http://download.csdn.net/download/liyuejin/9986140


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值