package com.example.demo.learn.servlet;
import org.apache.commons.lang3.time.DateFormatUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
/**
* init() 初始化一次
* service() 只会执行一次
* destroy() 只会执行一次
* 先走service(), 首先判断是什么样的请求方法,然后具体执行对应的请求方法。
* <p>
* 线程不安全,不用共享全局变量, 使用局部变量
*/
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private int i = 0;
public HelloServlet() {
System.out.println("构造函数被执行.....");
}
@Override
public void init() throws ServletException {
System.out.println("init()方法执行.....");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置响应编码
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
System.out.println("doPost() ........");
String code = req.getParameter("code");
// 对共享变量进行加锁操作
synchronized (HelloServlet.class) {
code = "您请求的数据: " + code + ", 请求的次数: " + i +
", 当前时间: " + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
out.write(code);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
out.close();
}
@Override
public void destroy() {
System.out.println("destory()方法被执行.....");
}
}