CookieTest.java
@WebServlet("/cookieTest")
public class CookieTest extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
boolean flag = false;
response.setContentType("text/html;charset=utf-8");
response.setHeader("content-type", "text/html;charset=utf-8");
Cookie[] cookies = request.getCookies();
if (cookies != null) {
//遍历cookies
for (Cookie cookie : cookies) {
String name = cookie.getName();
if ("lastTime".equals(name)) {
flag = true;
//不是第一次
//1.响应数据
String value = cookie.getValue();
value = URLDecoder.decode(value, "utf-8");
response.getWriter().write("欢迎回来,您上次的访问时间:" + value);
//2.修改value
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日
hh:mm:ss");
String str_date = sdf.format(date);
str_date = URLEncoder.encode(str_date, "utf-8");
cookie.setValue(str_date);
cookie.setMaxAge(60 * 60 * 24 * 30);
response.addCookie(cookie);
break;
}
}
}
if (cookies == null || cookies.length == 0 || !flag) {
//1.响应数据
response.getWriter().write("您好欢迎首次访问");
//2.创建cookie对象
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
String str_date = sdf.format(date);
str_date = URLEncoder.encode(str_date, "utf-8");
Cookie cookie = new Cookie("lastTime", str_date);
cookie.setMaxAge(60 * 60 * 24 * 30);
response.addCookie(cookie);
}
}
}
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
<script>
window.onload=function (){
document.getElementById("checkCode").onclick=function (){
this.src="http://localhost:8080/demo/checkCode?"+new Date().getTime();
}
}
</script>
</head>
<body>
<form action="loginServlet">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>验证码:</td>
<td><input type="text" name="checkCode"></td>
</tr>
<tr>
<td colspan="2"><img id="checkCode"
src="http://localhost:8080//demo/checkCode"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="登录"></td>
</tr>
</table>
</form>
<div><%=request.getAttribute("msgError") == null ? "" :
request.getAttribute("msgError")%></div>
<div><%=request.getAttribute("codeError") == null ? "" :
request.getAttribute("codeError")%></div>
</body>
</html>
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录成功</title>
</head>
<body>
<%=request.getSession().getAttribute("username")%>,您好
</body>
</html>
LoginServlet.java
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
String checkCode = request.getParameter("checkCode");
HttpSession session = request.getSession();
String code = (String) session.getAttribute("Code");
session.removeAttribute("Code");
if (checkCode.equalsIgnoreCase(code)) {
//验证码正确
if ("admin".equals(username) && "123".equals(password)) {
//用户名密码正确
session.setAttribute("username", username);
response.sendRedirect(request.getContextPath() + "/success.jsp");
} else {
request.setAttribute("msgError", "用户名或密码错误");
RequestDispatcher dispatcher =
request.getRequestDispatcher("/login.jsp");
dispatcher.forward(request, response);
}
} else {
//验证码错误
request.setAttribute("codeError", "验证码错误");
RequestDispatcher dispatcher = request.getRequestDispatcher("/login.jsp");
dispatcher.forward(request, response);
}
}
}
CheckCode.java
@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
int width = 100, height = 50;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.pink);
g.fillRect(0, 0, width, height);
g.setColor(Color.blue);
g.drawRect(0, 0, width - 1, height - 1);
String s = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random r = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 4; i++) {
int index = r.nextInt(s.length());
char ch = s.charAt(index);
sb.append(ch);
g.drawString(ch + "", width / 5 * i, height / 2);
}
String code = sb.toString();
HttpSession session = request.getSession();
session.setAttribute("Code", code);
g.setColor(Color.yellow);
for (int i = 1; i <= 10; i++) {
int x1 = r.nextInt(width);
int x2 = r.nextInt(width);
int y1 = r.nextInt(height);
int y2 = r.nextInt(height);
g.drawLine(x1, y1, x2, y2);
}
ImageIO.write(image, "jpg", response.getOutputStream());
}
}
MyServlet.java
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取请求中的用户名和密码参数
String username = request.getParameter("name");
String password = request.getParameter("password");
// 设置响应内容类型
response.setContentType("text/html");
// 输出参数到页面
PrintWriter out = response.getWriter();
out.println("<h1>Username: " + username + "</h1>");
out.println("<h1>Password: " + password + "</h1>");
}
}