Servlet技术流程
Sum公司开发的JavaWeb项目
- 删除src使用模块编程
- 导入依赖
Servlet:
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
JSP
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
- 添加应用程序模块,使用artitype
- 补全子项目模块的结构
- 编写业务逻辑
接口结构:业务类 —继承—>GenericServlet—继承—>Servlet
Servlet接口构成
void init(ServletConfig var1) throws ServletException;
// 仅启动一次
ServletConfig getServletConfig();
//获取信息
void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
//服务注册的主要部分
String getServletInfo();
//返回信息
void destroy();
//仅销毁一次
GenericServlet:与协议无关的实现
HttpServlet:Http协议的servlet
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
PrintWriter printWriter = resp.getWriter();
printWriter.println("Hello,Servlet");
}
注册servlet的服务到浏览器配置文件
<servlet>
<servlet-name>hello</servlet-name>
<!-- 用于注册一个服务,服务名是hello -->
<servlet-class>cn.prelu.web.Servlet</servlet-class>
<!-- 服务所在的类位置 -->
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<!-- 要映射的服务名称 -->
<url-pattern>/hello</url-pattern>
<!-- 映射的地址 -->
</servlet-mapping>
Servlet方法
不应该调用父类的doget方法,否则会出现资源冲突
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Get success");
PrintWriter printWriter = resp.getWriter();
printWriter.println("Hello,Servlet");
}