0%

内置Tomcat并使用servlet

文章字数:159,阅读全文大约需要1分钟

  1. servlet
1
2
3
4
5
6
7
8
9
10
11
public class HelloServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("hellowrld");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
  1. 创建内置的tomcat并使用servlet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 创建tomcat应用对象
Tomcat tomcat = new Tomcat();
// 设置端口
tomcat.setPort(8080);
// 是否自动部署
tomcat.getHost().setAutoDeploy(false);
// 创建上下文
StandardContext standardContext = new StandardContext();
// 设置项目名
standardContext.setPath("/sb");
// 监听上下文
standardContext.addLifecycleListener(new FixContextListener());
// 向tomcat容器对象添加上下文配置 tomcat.getHost().addChild(standardContext);
// 创建Servlet
tomcat.addServlet("/sb", "helloword", new HelloServlet());
// Servlet映射
standardContext.addServletMappingDecoded("/hello", "helloword");
//启动tomcat容器
tomcat.start();
//等待
tomcat.getServer().await();