Servlet的具体使用,核心是三个类
Servlet的生命周期
Servlet在实例化之后调用一次init
Servlet每次收到请求,调用一次service
Servlet在销毁之前,调用一次destroy
一:HttpServlet
写 Servlet 代码的时候, 首先第一步就是先创建类, 继承自 HttpServlet, 并重写其中的某些方法。继承HttpServlet是为了重写类里面的方法,重写方法的目的是为了能够让程序员定义的逻辑给插入到Tomcat这个框架中,好让Tomcat能够调用。
方法名称 | 调用时机 |
---|---|
init | 在HttpServlet实例化之后被调用一次 |
destory | 在HttpServlet实例不再使用的时候调用一次 |
service | 收到HTTP请求的时候调用 |
doGet | 收到GET请求的时候调用(由service方法调用) |
doPost | 收到POST请求的时候调用(由service方法调用) |
doPut/doDelete/dooptions/… | 收到其他请求的时候调用(由service方法调用) |
最常用的就是重写doGet和doPost方法了。
二:HttpServletRequset
这个类表示一个HTTP请求
打印请求信息
@WebServlet("/showRequest")
public class ShowRequestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
StringBuilder respBody = new StringBuilder();
respBody.append(req.getRequestURL());
respBody.append("<br>");
respBody.append(req.getMethod());
respBody.append("<br>");
respBody.append(req.getProtocol());
respBody.append("<br>");
respBody.append(req.getQueryString());
respBody.append("<br>");
respBody.append(req.getContextPath());
respBody.append("<br>");
respBody.append("<h3>headers:</h3>");
Enumeration<String> headerNames = req.getHeaderNames();
while (headerNames.hasMoreElements()){
String headerName = headerNames.nextElement();
respBody.append(headerName+" ");
respBody.append(req.getHeader(headerName));
respBody.append("<br>");
}
resp.getWriter().write(respBody.toString());
}
}
获取GET请求中的参数
@WebServlet("/getParameter")
public class GetParameter extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset==utf-8");
// String getParameter(String name) 以字符串形式返回请求参数的值,或者如果参数不存在则返回null。
String userId = req.getParameter("userId");
String classId = req.getParameter("classId");
/**
* 某些时候需要对query string进行判定是否存在
* if(userId==null || userId.equals("")){
*
* }
* */
resp.getWriter().write("userId:"+userId+","+"classId:"+classId);
}
}
获取POST请求中的参数
POST请求的参数一般通过body传递给服务器。body中的数据格式有很多种。如果是采用form表单的形式。仍然可以通过getParameter获取参数的值。
创建PostParameter
@WebServlet("/postParameter")
public class PostParameter extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
String userId = req.getParameter("userId");
String classId = req.getParameter("classId");
resp.getWriter().write("userId"+userId+","+"classId:"+classId);
}
}
创建testPost.html,放到webapp目录中
<form action="postParameter" method="post">
<input type="text" name="userId">
<input type="text" name="classId">
<input type="submit" value="提交">
</form>
POST请求中的body按照JSON的格式来传递
创建PostParameterJson类
@WebServlet("/postParameterJson")
public class PostParameterJson extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
// 读取整个Body
String body = readBody(req);
resp.getWriter().write(body);
}
private String readBody(HttpServletRequest req) throws IOException {
// 读取body需要根据 req.getInputStream 得到一个流对象,从这个流对象中读取
InputStream inputStream = req.getInputStream();
// 通过 contentLength 拿到请求中的 body 的字节数
int contentLength = req.getContentLength();
byte[] buffer = new byte[contentLength];
inputStream.read(buffer);
return new String(buffer,"utf-8");
}
}
<button onclick="sendJson()">发送JSON格式的POST请求</button>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
function sendJson() {
let body = {
userId:100,
classId: 1
};
$.ajax({
url:'postParameterJson',
type:'POST',
contentType:'application/json;charset=utf-8',
data:JSON.stringify(body),
success:function (body,status) {
console.log(body);
}
});
}
</script>
由于json格式本身解析起来比较复杂,更好的办法是直接使用第三方库。从maven仓库中引入Jachson
// 通过这个类来表示解析后的结果
class JsonData{
public int userId;
public int classId;
}
@WebServlet("/postParameterJson")
public class PostParameterJson extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
// 读取整个Body
String body = readBody(req);
//字符串到json对象的解析过程
ObjectMapper objectMapper = new ObjectMapper();
JsonData jsonData = objectMapper.readValue(body,JsonData.class);
resp.getWriter().write("userId:"+jsonData.userId+","+"classId:"+jsonData.classId);
}
private String readBody(HttpServletRequest req) throws IOException {
// 读取body需要根据 req.getInputStream 得到一个流对象,从这个流对象中读取
InputStream inputStream = req.getInputStream();
// 通过 contentLength 拿到请求中的 body 的字节数
int contentLength = req.getContentLength();
byte[] buffer = new byte[contentLength];
inputStream.read(buffer);
return new String(buffer,"utf-8");
}
}
三:HttpServletResponse
用户在浏览器通过参数指定要返回响应的状态码
@WebServlet("/status")
public class StatusServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
// 让用户传入一个请求
// 请求在query string中带一个参数。表示响应的状态码
// 然后根据用户的输入,返回不同的状态码的响应
String statusString = req.getParameter("status");
if(statusString == null || statusString.equals("")){
resp.getWriter().write("当前的请求参数 status 缺失");
return;
}
resp.setStatus(Integer.parseInt(statusString));
resp.getWriter().write("status:"+statusString);
}
}
让浏览器每秒钟自动刷新,并显示当前时间戳和当前时间
@WebServlet("/autoRefreshServlet")
public class AutoRefreshServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
resp.setHeader("Refresh","1");
long timeStamp = new Date().getTime();
resp.getWriter().write("timeStamp:"+timeStamp+"<br>");
Date now=new Date();
SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dataStr = myFmt.format(now);
resp.getWriter().write(dataStr);
}
}
重定向
@WebServlet("/redirect")
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("http://www.baidu.com");
}
}