![在这里插入图
我们在这之前我们需要先看过本专栏的第一篇文章(一)实现购物系统的一些前置准备
<%--登录表单--%>
<div class="container__form container--signin">
<form action="/MyProject/userProcessServlet" method="post" class="form" id="form2">
<h2 class="form__title">Sign Inh2>
<input type="hidden" name="method" value="login">
<input type="text" placeholder="username" name="username" required="required" value="<%=username%>" class="input" />
<input type="password" placeholder="Password" name="password" required="required" value="<%=password%>" class="input" />
<div>
<input style="width: 48%" type="text" name="answer" placeholder="验证码" required="required" id="answer" class="input">
<img style="width: 50%" src="simpleImg" title="看不清,换一张" id="securityCode" />
div>
<span>
<input type="checkbox" name="remember">记住我
<a href="#" class="link">忘记密码a>
span>
<button type="submit" class="btn" id="login">登录button>
form>
div>
<%--注册表单--%>
<div class="container__form container--signup">
<form action="/MyProject/userProcessServlet" class="form" id="form1" method="post">
<h2 class="form__title">Sign Uph2>
<input type="hidden" name="method" value="register">
<input type="text" placeholder="User" name="username" required="required" class="input" />
<input type="password" placeholder="Password" name="password" required="required" class="input" />
<input type="email" placeholder="Email" name="email" required="required" class="input" />
<div class="input" style="text-align: justify;background: transparent;font-size: 15px">
爱好:
<input style="margin-left: 20px;" type="checkbox" name="hobby" value="basketball ">篮球
<input style="margin-left: 20px;" type="checkbox" name="hobby" value="football ">足球
div>
<button type="button" class="btn" id="register">注册button>
form>
div>
注册表单的处理采用的是
Ajax
发送请求,便于根据后端的处理结果来给前端返回对应的结果。
// 注册
$("#register").click(
function () {
var username = $("input[name='username']").val();
var password = $("input[name='password']").val();
var email = $("input[name='email']").val();
// 获取复选框被选中的值
var check_value =[];
$("input[name='hobby']:checked").each(function(){
check_value.push($(this).val());
});
var check_value_str = check_value.join();
if (username.length==0 ||
password.length==0 ||
email.length==0 ||
check_value_str.length==0){
alert("不能有空!")
return false;
}
$.post(
"/MyProject/userProcessServlet",
{
method: "register",
username: username,
password: password,
email: email,
hobby: check_value_str
},
function (data) {
alert(data);
window.location.href = "/MyProject/login.jsp"
},
"json"
)
}
)
使用Ajax请求,根据后端返回结果来处理的效果。
效果如下:
首先我们需要明白登录都需要实现哪些功能,这样才能有的放矢。
package com.controller;
import com.entity.User;
import com.google.gson.Gson;
import com.myUtil.JdbcUtil;
import com.myUtil.ProcessUtil;
import com.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
public class UserProcessServlet extends BasicServlet {
private UserService userService = new UserService();
// 用户注册
protected void register(HttpServletRequest request,HttpServletResponse response){
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
String[] hobbies = request.getParameterValues("hobby");
PrintWriter writer = null;
Gson gson = new Gson();
try {
response.setContentType("text/plain;charset=utf-8");
writer = response.getWriter();
boolean existUsername = userService.isExistUsername(username);
if (!existUsername){
userService.addUser(new User(null, username, password, email, Arrays.toString(hobbies)));
JdbcUtil.commit();
writer.write(gson.toJson("注册成功"));
}else {
writer.write(gson.toJson("用户已存在"));
}
} catch (IOException e) {
JdbcUtil.rollback();
try {
writer = response.getWriter();
writer.write(gson.toJson("注册失败"));
} catch (IOException ioException) {
ioException.printStackTrace();
}
e.printStackTrace();
}
}
// 用户登录
protected void login(HttpServletRequest request,HttpServletResponse response){
try {
String username = request.getParameter("username");
String password = request.getParameter("password");
String remember = request.getParameter("remember");
HttpSession session = request.getSession();
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
Date date = new Date(System.currentTimeMillis());
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
if (userService.checkUserName(username,password)){
// 设置session防止非法登录(格式:用户名_用户id)
session.setAttribute("user",username+"_"+userService.showDetailInfo(username).getId());
// 如果勾选 记住我 设置cookie
if ("on".equals(remember)){
setCookie(request,response);
}
// 记录次数
recordCount(request);
try {
request.getRequestDispatcher("/index.jsp").forward(request,response);
} catch (ServletException e) {
e.printStackTrace();
}
}else {
writer.write("fault!");
writer.write("");
writer.write("");
writer.write(formatter.format(date));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 用户修改信息
protected void update(HttpServletRequest request,HttpServletResponse response){
String username = request.getParameter("username");
String email = request.getParameter("email");
String hobby = request.getParameter("hobby");
int id = Integer.parseInt(request.getParameter("id"));
// 修改用户名得判断用户名是否被使用
if (!userService.isExistUsername(username)){
// 不修改密码
Boolean aBoolean = userService.updateUserInfo(id, new User(null, username, null, email, hobby));
if (aBoolean){
try {
request.getSession().setAttribute("user",username + "_" + ProcessUtil.getUserIdBySessionId(request.getSession()));
response.sendRedirect("/MyProject/userDetailInfo.jsp");
} catch (IOException e) {
e.printStackTrace();
}
}
}else{ // 用户名被使用
try {
response.setContentType("text/plain;charset=utf-8");
response.getWriter().write("用户名已被使用");
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 写Cookie
protected void setCookie(HttpServletRequest request, HttpServletResponse response){
String username = request.getParameter("username");
String password = request.getParameter("password");
Cookie cookie1 = new Cookie("username",username);
cookie1.setMaxAge(3600*24*14);
Cookie cookie2 = new Cookie("password", password);
cookie2.setMaxAge(3600*24*14);
response.addCookie(cookie1);
response.addCookie(cookie2);
}
// 记录登录次数/登陆时间
protected void recordCount(HttpServletRequest request){
HttpSession session = request.getSession();
if (session.getAttribute("count") == null){
int count = 1;
session.setAttribute("count",count);
}else {
Integer count = (Integer)session.getAttribute("count");
count++;
session.setAttribute("count",count);
}
}
// 用户注销
protected void logout(HttpServletRequest request,HttpServletResponse response){
HttpSession session = request.getSession();
session.removeAttribute("user");
try {
response.sendRedirect("/MyProject/index.jsp");
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.service;
import com.dao.UserDao;
import com.entity.User;
import java.util.List;
public class UserService {
private UserDao userDao = new UserDao();
// 验证用户是否存在
public boolean isExistUsername(String username){
User user = userDao.queryUserByName(username);
if (user!=null){
return true;
}
return false;
}
// 验证用户的密码
public boolean checkUserName(String username,String password){
if (!isExistUsername(username)){
return false;
}
User user = userDao.queryUserByNameAndPwd(username, password);
if (user!=null){
return true;
}else {
return false;
}
}
// 显示个人信息
public User showDetailInfo(String username){
User user = userDao.queryUserByName(username);
if (user!=null){
return user;
}else {
return null;
}
}
// 修改用户信息
public Boolean updateUserInfo(Integer id,User user){
Boolean result = userDao.updateInfo(id, user);
return result;
}
// 添加用户
public boolean addUser(User user){
boolean result = userDao.addData(user);
return result;
}
// 显示列表的所有用户信息
public List<User> showAllUser(){
return userDao.showAllData();
}
}
我们的具体类的Dao都继承`BasicDao`这个公共类,通过泛型来实现自己具体Dao。
package com.dao;
import com.entity.User;
import java.util.List;
public class UserDao extends BasicDao<User>{
// 根据用户名查询用户
public User queryUserByName(String username){
String sql = "SELECT * FROM USER WHERE username=" + "'" + username + "'";
User user = querySingle(sql,User.class);
return user;
}
// 根据用户名和密码查询用户
public User queryUserByNameAndPwd(String username,String password){
String sql = "SELECT * FROM USER WHERE username = '" + username + "'" + "and " + "password" + "=" + "MD5('"+ password +"')";
User user = querySingle(sql,User.class);
return user;
}
// 修改数据
public Boolean updateInfo(Integer id,User user){
String sql = "UPDATE `user` SET `username`='"+ user.getUsername() + "',`email`= '"+ user.getEmail() +"',`hobby`='" + user.getHobby() + "' WHERE `id`="+ id;
return dmlData(sql);
}
// 添加数据
public boolean addData(User user){
String sql = "INSERT INTO USER(`username`,`password`,`email`,`hobby`) VALUES('" + user.getUsername() + "'," + "MD5('" + user.getPassword() + "')," + "'" + user.getEmail() + "','" + user.getHobby() + "')";
System.out.println(sql);
return dmlData(sql);
}
// 显示列表所有信息
public List<User> showAllData(){
String sql = "select * from user";
List<User> users = queryMulti(sql, User.class);
if (users != null){
return users;
}
return null;
}
}
package com.entity;
public class User {
private Integer id;
private String username;
private String password;
private String email;
private String hobby;
public User() {
}
public User(Integer id, String username, String password, String email, String hobby) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
this.hobby = hobby;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", hobby='" + hobby + '\'' +
'}';
}
}
列名 | 数据类型 | 长度 | 主键? | 非空? | 自增? |
---|---|---|---|---|---|
id | int | √ | √ | √ | |
username | varchar | 32 | √ | √ | |
password | varchar | 32 | √ | ||
varchar | 32 | √ | |||
hobby | varchar | 32 | √ |
这里我们需要注意的是:实体类的属性必须要和对应表中的字段类型保持一致!!!
前端使用的都是jsp(jsp是前端这种说法并不准确,jsp应该是前后端的结合,这里只是为了描述方便)。我们在
UserProcessServlet
controller层中,通过cookie
,对其做了处理,详细的逻辑读者可以看上边的代码。这里展示的是在jsp前端页面中写的java代码,初始化都为空,只有本地浏览器的cookie
中有用户名和密码的时候,才会将其读取到登陆框中。
<%!
String username = "";
String password = "";
%>
<%
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if ("username".equals(cookie.getName())){
username = cookie.getValue();
}
if ("password".equals(cookie.getName())){
password = cookie.getValue();
}
}
%>