一、注解方式

1.1 使用Servlet3注解方式写一个Servlet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@WebServlet(urlPatterns = "/testServlet",initParams = {
@WebInitParam(name="name",value="wno704")
})
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = -4316351735748478174L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
resp.getWriter().println("he " + name + " hello world");
resp.getWriter().flush();
resp.getWriter().close();
}

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

1.2 在启动类添加注解扫描servlet

@ServletComponentScan(basePackages = "com.wno704.boot.servlet")

1.3 测试

启动项目,访问 http://localhost:8080/testServlet?name=wno7042

二、通过SpringBoot配置类实现

2.1 编写一个普通servlet类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class HeServlet extends HttpServlet {
private static final long serialVersionUID = -4316351735748478173L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("he servlet hello world");
resp.getWriter().flush();
resp.getWriter().close();
}

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

2.2 编写一个springboot配置类

1
2
3
4
5
6
7
8
@Configuration
public class WebConfig {
@Bean
public ServletRegistrationBean heServletRegistrationBean() {
ServletRegistrationBean registration = new ServletRegistrationBean(new HeServlet(),"/heServlet");
return registration;
}
}

2.3 测试

启动项目,访问 http://localhost:8080/heServlet

三、动态注册

3.1 编写一个普通的Servlet类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class HeServlet extends HttpServlet {
private static final long serialVersionUID = -4316351735748478173L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("he servlet hello world");
resp.getWriter().flush();
resp.getWriter().close();
}

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

3.2编写一个Servlet注册类

1
2
3
4
5
6
7
8
9
10
@Component
public class ServletConfig implements ServletContextInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
ServletRegistration iniServlet = servletContext.addServlet("iniServlet", HeServlet.class);
iniServlet.addMapping("/iniServlet");
//iniServlet.setInitParameter("name","wno704");

}
}

3.3 测试

启动项目,访问 http://localhost:8080/iniServlet