Servlet执行流程
- 用户请求
<a href="sevlet/HelloServlet">
- 在web.xml中寻找与之对应的url地址
<servlet-mapping>
<servlet-name>HelloServlet<servlet-name>
<url-pattern>/servlet/HelloServlet</url-pattern>
</servlet-mapping>
- 在servlet标签寻找与之对应的处理类
<servlet>
<servlet-name>HelloServlet<servlet-name>
<servlet-class>servlet.HelloServlet</servlet-class>
</servlet>
- 根据用户提交的请求方式get/post取执行这个类中的doGet()/doPost()方法
public class HelloServlet extends HttpServlet {
@ Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
......
}
......
}
Servlet生命周期
- 初始化阶段,调用init()方法
- 响应客户请求阶段,调用service()方法,由service()方法根据提交方式get/post选择执行doGet()或doPost()方法
- 终止阶段,调用destroy()方法
Tomcat装载servlet的三种情况:
- Servlet容器启动时自动装载某些Servlet,即创建Servlet实例并调用init()方法,需在web.xml文件中添加代码:
<loadon-startup>1</loadon-startup>
,数字越小优先级越高 - Servlet容器启动后,客户端首次向Servlet发送请求
- Servlet类文件被更新后,重新装载Servlet
Servlet与jsp内置对象关系
Servlet获取表单数据
// 表单
<form action="servlet/RegServlet" method="post">
<label>用户名</label>
<input type="text" name="username" />
<label>密码</label>
<input type="password" name="username" />
<button type="submit">提交</button>
</form>
// 实体类
package entity;
public class Users {
private String username; // 用户名
private String password; // 密码
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public String setUsername() {
retrun this.username;
}
public String setPassword() {
retrun this.password;
}
}
// 处理用户信息的servlet类
package servlet;
public class RegServlet extends HttpServlet {
......
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Users user = new Users();
String username, password;
try {
username = request.getParameter("username");
password = request.getParameter("password");
user.setUsername(username);
user.setPassword(password);
request.getRequestDispatcher("../forward.jsp").forward(request, response);
} catch(Exception e) {
e.printStackTrace();
}
}
......
}