在web应用中Servlet的应用比较多,最开始的web应用就是全部以servlet来实现的,后来出现了Struts、Struts2,到今天应用非常广泛的SpringMvc,这些web mvc框架比原来的servlet功能更加强大,开发效率而更高,但是实际上这些框架底层都是servlet在做支撑。今天我们学习如何在SpringBoot添加Servlet的应用。

编写Servlet继承HttpServlet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.maxbill.core.webbox.servlet;

import org.apache.log4j.Logger;

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;

/**
* @功能 自定义servlet
* @作者 zuoshuai(MaxBill)
* @日期 2017/7/6
* @时间 14:57
* @备注 MyServlet
*/
public class MyServlet extends HttpServlet {

Logger log = Logger.getLogger(MyServlet.class);

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log.info("servlet通过get方式请求完成...");
}

}

这里只实现了doGet请求,post、put等请求同理实现即可。

注册servlet到启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.maxbill;

import com.maxbill.core.webbox.servlet.MyServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class MaxbillApplication {

/**
* 注册Servlet
*/
@Bean
public ServletRegistrationBean MyServlet1(){
return new ServletRegistrationBean(new MyServlet(),"/servlet/*");
}

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

}

使用注解注册servlet

首先在servlet上增加@WebServlet

1
2
3
4
5
6
7
8
9
10
@WebServlet(urlPatterns = "/servlet/*", description = "")
public class MyServlet extends HttpServlet {

Logger log = Logger.getLogger(MyServlet.class);

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.info("servlet通过get方式请求完成...");
}

}

然后在启动类中增加@ServletComponentScan,使项目中的servlet能够被扫描到

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.maxbill;

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

@ServletComponentScan
@SpringBootApplication
public class MaxbillApplication {

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

}

启动项目测试:访问http://127.0.0.1:520/servlet
控制台日志:INFO com.maxbill.core.webbox.servlet.MyServlet:25 - servlet通过get方式请求完成…