3. 常见实现功能
实体类:
父类(Person)
public class Person {
@FieldInfo(name= "id",type = "int",length = 10)
private int id;
@FieldInfo(name= "name",type = "varchar",length = 10)
private String name;
@FieldInfo(name= "username",type = "varchar",length = 10)
private String username;
@FieldInfo(name= "password",type = "varchar",length = 10)
private String password;
@FieldInfo(name= "sex",type = "varchar",length = 10)
private String sex;
@FieldInfo(name= "age",type = "int",length = 10)
private int age;
public Person() {
}
public Person(int id, String name, String username, String sex, int age) {
this.id = id;
this.name = name;
this.username = username;
this.sex = sex;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
子类(Student)
public class Student extends Person {
@FieldInfo(name= "hobby",type = "varchar",length = 10)
private String hobby;
public Student() {
}
public Student(int id, String name, String username, String sex, int age, String hobby) {
super(id, name, username, sex, age);
this.hobby = hobby;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
}
3.1 后端实现自动生成验证码
要点:
1.要随机生成验证码,需要Random随机类,与图像缓冲区类BufferedImage。
2.前端页面能够点击验证码图片,切换验证码。
3.生成的验证码信息要实时保存在Session中,验证时再从Session中获取。
@WebServlet("/CodeServlet")
public class CodeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置验证码的大小(宽高)
int width = 100;
int height = 40;
//1.获取画布画笔
//1.1创建画布
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//1.2获取画笔
Graphics graphics = image.getGraphics();
//2.填充背景颜色
//2.1设置画笔的颜色
graphics.setColor(Color.PINK);
//2.2使用画笔填充验证码背景颜色(0,0)~(width,height)
graphics.fillRect(0,0,width,height);
//3.生成验证码,并画在画布上
//3.1字验证码字符内容数组
String[] ranTexts = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0"};
//3.2验证码字符颜色数组
Color[] colors = {Color.RED,Color.BLACK,Color.BLUE,Color.MAGENTA,Color.GREEN,Color.LIGHT_GRAY};
Random ran = new Random();
//4.画验证码
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4; i++) {
//4.1设置字体,随机大小
graphics.setFont(new Font("宋体",Font.BOLD,20+ran.nextInt(20)));
//4.2设置随机颜色
graphics.setColor(colors[ran.nextInt(colors.length-1)]);
//4.3获取随机内容
String str = ranTexts[ran.nextInt(ranTexts.length - 1)];
//4.4将随机内容设置在画布上
graphics.drawString(str,8+i*20,20+ran.nextInt(10));
//4.5拼接字符
sb.append(str);
}
//5.将验证码存入Session对象中
HttpSession session = request.getSession();
session.setAttribute("code",sb.toString());
//6.画干扰线
graphics.setColor(Color.BLACK);
for (int i = 0; i < 5; i++) {
graphics.drawLine(ran.nextInt(width),ran.nextInt(height),ran.nextInt(width),ran.nextInt(height));
}
//7.将画布传给前端
ImageIO.write(image,"jpg",response.getOutputStream());
}
}
前端设计:
<body>
<%
//获取请求中的错误信息
String msg = (String) request.getAttribute("msg");
%>
<%=(msg!=null)?msg:""%>
<h1 style="text-align: center;">登录界面</h1>
<div class="con">
<form action="LoginServlet" method="post">
<table >
<tr>
<th width="100px">账号:</th>
<td width="400px">
<input type="text" name="username" id="username"/>
</td>
</tr>
<tr>
<th>密码:</th>
<td>
<input type="password" name="password" id="password"/>
</td>
</tr>
<tr>
<th>验证码:</th>
<td>
<input type="text" name="code" id="code"/>
<img src="CodeServlet" width="100px" height="40px" οnclick="loadCode()">
</td>
</tr>
<tr>
<th>角色:</th>
<td>
<select name="role">
<option value="student">学生</option>
<option value="teacher">教师</option>
</select>
</td>
</tr>
<tr>
<th colspan="2">
<input type="checkbox" name="checkbox" >记住我<br/>
</th>
</tr>
<tr>
<th colspan="2">
<input type="submit" style="width:90px;height:30px" value="登录"><br/>
</th>
</tr>
</table>
</form>
<script type="text/javascript">
var img = document.getElementsByTagName("img")[0];
function loadCode() {
img.src = "CodeServlet?" + new Date();
}
loadCode();
</script>
</div>
</body>
3.2 Cookie+Session 免登陆
1.在前端页面增加checkedbox控件,实现用户能够主动勾选记住我
<input type="checkbox" name="checkbox" >记住我<br/>
2.登录按钮点击提交之后,增加对checkedbox的判断(当checkedbox被勾选时,从请求中获取的checkedbox为on,未勾选则获取的值为null。)
if(checkbox!=null) {
//通过CookieUtil创建cookie添加入响应域中。
response.addCookie(CookieUtil.createCookie("username", p.getUsername(),60*60*24));
response.addCookie(CookieUtil.createCookie("name", p.getName(),60*60*24));
response.addCookie(CookieUtil.createCookie("role", role,60*60*24));
}
3.在Cookie中存储登录过后的界面所需要的相关信息,并设置过期时间为需要免登陆的时间期限。
CookieUtil(创建Cookie的工具类):
public class CookieUtil {
public static Cookie createCookie(String key,String value,int time){
Cookie cookie = null;
try {
cookie = new Cookie(URLEncoder.encode(key,"UTF-8"),URLEncoder.encode(value,"UTF-8"));
cookie.setMaxAge(time);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return cookie;
}
}
注:在存储Cookie时,如果可能出现中文,需要使用URLEncoder.encode()进行编码,在获取 Cookie中的数据时还要记得使用URLDecoder.decode()解码
4.在登录界面之前,优先判断是否含有免登陆所需要的信息,如果有,就通过Session存储,再通过 重定向或转发 实现跳转(跳过登录界面)。
<%
//获取Cookie
Cookie[] cookies = request.getCookies();
if (cookies!=null){
int num = 0;
for (Cookie cookie :cookies){
String key = URLDecoder.decode(cookie.getName(),"UTF-8");
String value = URLDecoder.decode(cookie.getValue(),"UTF-8");
if(key.equals("username")){
num++;
request.getSession().setAttribute(key,value);
}
if(key.equals("role")){
num++;
request.getSession().setAttribute(key,value);
}
if(key.equals("name")){
num++;
request.getSession().setAttribute(key,value);
}
if(num == 3){
response.sendRedirect("page.jsp");
}
}
}
%>
5.安全退出,即消除当前账号免登陆的功能,通过将Cookie对应的数据清空实现。
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().setAttribute("username",null);
req.getSession().setAttribute("name",null);
req.getSession().setAttribute("role",null);
//将Cookie对应数据设置为过期。
resp.addCookie(CookieUtil.createCookie("username","",0));
resp.addCookie(CookieUtil.createCookie("name","",0));
resp.addCookie(CookieUtil.createCookie("role","",0));
//返回到欢迎页面
resp.sendRedirect("welcome.html");
}
3.3 修改信息功能
1.首先,前端页面点击修改信息之后,应当先跳入一个Servlet中,并且将详情页面的用户标志信息传入这个Servlet中。
<a href="StuInitModifyServlet?username=<%=username%>" >修改学生信息</a>
2.通过Servlet接受前端传来的请求,在数据库中查询这个学生的所有信息,并将信息转发给一个jsp页面。
@WebServlet("/StuInitModifyServlet")
public class StuInitModifyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置请求和响应的编码格式
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String username = request.getParameter("username");
ArrayList<Student> students = DBUtil.commonQuery(Student.class, "select * from student where username=?", username);
request.setAttribute("student",students.get(0));
request.getRequestDispatcher("stuinfo.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
3.在jsp页面中获取请求的数据,进行处理和展示。
<%@ page import="com.dream.vo.Student" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="java"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fun"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>学生信息页面</h1>
<form action="StuModifyServlet" method="post">
<input type="hidden" name="currentPage" value="${currentPage}">
<input type="hidden" name="role" value="${role}" >
<input type="hidden" name="username" value="${student.username}"/>
账号:${student.username}<br/>
姓名:<input name="name" type="text" value="${student.name}"/><br/>
年龄:<input name="age" type="number" value="${student.age}"/><br/>
性别:
<input name="sex" value="man" type="radio" <java:if test="${student.sex eq 'man'}">checked='checked'</java:if>/>男
<input name="sex" value="woman" type="radio" <java:if test="${student.sex eq 'woman'}">checked='checked'</java:if>/>女
<br/>
爱好:
<input name="hobby" value="football" type="checkbox" <java:if test="${fun:contains(student.hobby, 'football')}">checked='checked'</java:if>/>足球
<input name="hobby" value="basketball" type="checkbox" <java:if test="${fun:contains(student.hobby, 'basketball')}">checked='checked'</java:if>/>篮球
<input name="hobby" value="shop" type="checkbox" <java:if test="${fun:contains(student.hobby, 'shop')}">checked='checked'</java:if>/>购物
<br/>
<input type="submit" value="确认修改"/><a href="page.jsp" >取消修改</a>
</form>
</body>
4.确认修改之后再跳转到另一个Servlet中进行修改处理。
@WebServlet("/StuModifyServlet")
public class StuModifyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置请求和响应的编码格式
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//获取请求传来的数据
String username = request.getParameter("username");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String age = request.getParameter("age");
String[] hobbies = request.getParameterValues("hobby");
try {
DBUtil.commUpdate("update student set name=?,sex=?,age=?,hobby=? where username=?",name,sex,age, HobbyUtil.getHobby(hobbies),username);
} catch (SQLException e) {
e.printStackTrace();
}
response.sendRedirect("page.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}