Javaweb MVC+dao实现简单用户登陆注册(实验)

本篇文章给大家分享一下简单用户登录注册界面的实现。含两周内免登陆、登陆次数、安全验证(非图片)、登录时间、兴趣爱好和用户简介。
代码放网盘里了,需要自取。注意是登录注册+购物车的,这两个实际运行是分开的,登录注册需运行user_login.jsp,购物车需运行cart.jsp。提取码:poem

首先给出截图,需要建这些文件,不会建的可以参考我上一篇文章的截图。黑线划掉的是购物车,我的购物车跟登录注册界面没有连,只是在一个文件夹放着,不用建划掉的。

在这里插入图片描述
build和images这两个文件夹不用管,都是购物车的。NewFile.html也不用建。
在这里插入图片描述

数据库

1、打开mysql服务(管理员打开),确保数据库已经连接好。
在这里插入图片描述
数据库连不上、不知道怎么操作,可以看看这篇文章。
2、连接成功,创建表user,设计表如下,goods不用创建!!!
在这里插入图片描述
3、数据库表里的数据可以随缘写,这一步写不写都行,刚开始userid是从1开始的,我因为删除了很多次所以是22开始的。
在这里插入图片描述

导入相应的包到WebRoot—>WebINF—>lib

只需导入下图所示第四个包即可,再点击包,Bulid Path—>Add to Bulid Path
在这里插入图片描述
可以下载使用到的包Javaweb常用登录和注册功能实现涉及的包

在src目录下创建包(注意命名,可以不一致,创建相应的类在相应包即可,下文会详细说明)

业务接口(包名:com.qianfeng.orderfood.biz)
业务实现(包名:com.qianfeng.orderfood.bizimpl)
dao层接口(包名:com.qianfeng.orderfood.dao)
dao层实现(包名:com.qianfeng.orderfood.daoimpl)
实体(包名: com.qianfeng.orderfood.entity)
场景(包名:com.qianfeng.orderfood.eums)
servlet服务(包名:com.qianfeng.orderfood.servlet)
工具包(包名:com.qianfeng.orderfood.util)

Java Resources–>src

(1)在com.qianfeng.orderfood.biz中创建UserBIZ.java

package com.qianfeng.orderfood.biz;

import javax.servlet.http.HttpServletRequest;

import com.qianfeng.orderfood.entity.User;

public interface UserBIZ {

	//用户登录
	String userLogin(User user, String validatecode,String syscode,HttpServletRequest req);

	//用户注册
	String userRegister(User user, String againpassword, String validatecode,String syscode,HttpServletRequest req);

}

(2)在com.qianfeng.orderfood.bizimpl中创建UserBIZImpl.java

package com.qianfeng.orderfood.bizimpl;

import javax.servlet.http.HttpServletRequest;

import com.qianfeng.orderfood.biz.UserBIZ;
import com.qianfeng.orderfood.dao.UserDAO;
import com.qianfeng.orderfood.daoimpl.UserDAOImpl;
import com.qianfeng.orderfood.entity.User;
import com.qianfeng.orderfood.eums.UserLoginEnum;
import com.qianfeng.orderfood.eums.UserRegisterEnum;
import com.qianfeng.orderfood.util.StringUtil;

public class UserBIZImpl implements UserBIZ {
	//business
	UserDAO userDAO = new UserDAOImpl();
	
	//用户登录
	public String userLogin(User user,String validatecode, String syscode,HttpServletRequest request) {
		if (StringUtil.isEmpty(user.getUsername())) {
			return UserLoginEnum.USER_NAME_IS_NUll.getValue();
		}
		if (StringUtil.isEmpty(user.getPassword())) {
			return UserLoginEnum.USER_PASSWORD_IS_NULL.getValue();
		}
		if (StringUtil.isEmpty(validatecode) || StringUtil.isEmpty(syscode)) {
			return UserLoginEnum.USER_VALIDATE_CODE_IS_FAIL.getValue();
		}
		if (!validatecode.equals(syscode)) {
			return UserLoginEnum.USER_VALIDATE_CODE_IS_FAIL.getValue();
		}

		user = userDAO.userLogin(user);
		if (user == null) {
			return UserLoginEnum.USER_NAME_OR_PASSWORD_IS_FAIL.getValue();
		}
		// 登录成功后 把当前登录成功后的用户 存入到SESSION中 基本是 所有后台的必备功能
		request.getSession().setAttribute("user", user);
		
	
		return UserLoginEnum.USER_LOGIN_SUCCESS.getValue();
	}
	
	
	//用户注册
	@SuppressWarnings("unused")
	public String userRegister(User user, String againpassword, String validatecode, String syscode, HttpServletRequest req) {//.
		
		if (StringUtil.isEmpty(user.getUsername())) {
			return UserRegisterEnum.USER_REGISTER_NAME_IS_NULL.getValue();
		}
		if (StringUtil.isEmpty(user.getPassword())) {
			return UserRegisterEnum.USER_REGISTER_PASSWORD_IS_NULL.getValue();
		}
		if (StringUtil.isEmpty(validatecode)) {
			return UserRegisterEnum.USER_REGISTER_VALIDATE_CODE_IS_NULL.getValue();
		}
		if(!user.getPassword().equals(againpassword)){
			return UserRegisterEnum.USER_REGISTER_AGAINPASSWORD_IS_DIFFERENT.getValue();
		}
		if (!validatecode.equals(syscode) || StringUtil.isEmpty(syscode)) {
			return UserRegisterEnum.USER_REGISTER_VALIDATE_CODE_IS_FAIL.getValue();
		}
		
		User _user = null;
		_user = userDAO.userToRegister(user.getUsername());
		if (_user != null) {
			return UserRegisterEnum.USER_REGISTER_NAME_IS_EXIST.getValue();
		}
		
		Integer executeCount =  null;
		executeCount = userDAO.userRegister(user);
		if(executeCount != null){
			return UserRegisterEnum.USER_REGISTER_SUCCESS.getValue();
		}
		
		return null;
	}

}

(3)在com.qianfeng.orderfood.dao中创建UserDAO.java

package com.qianfeng.orderfood.dao;
import com.qianfeng.orderfood.entity.User;

public interface UserDAO {
	// 阿里规范 公开 的 抽象的 这两个 描述 不需要手动的写出来
		//用户登录
		User userLogin(User user);
		User userLogin(String username);
		
		//用户注册
		int userRegister(User user);
		
		//判断注册用户名存在否
		User userToRegister(String username);
}

(4)在com.qianfeng.orderfood.daoimpl中创建UserDAOImpl.java

package com.qianfeng.orderfood.daoimpl;

import java.sql.SQLException;
import java.sql.Timestamp;

import com.qianfeng.orderfood.dao.UserDAO;
import com.qianfeng.orderfood.entity.User;
import com.qianfeng.orderfood.util.JDBCUtil;

public class UserDAOImpl implements UserDAO {

	
	//用户登录,查询用户是否存在
	public User userLogin(User user) {
//		User user = null;
		java.sql.Connection connection = null;
		java.sql.PreparedStatement preparedStatement = null;
		java.sql.ResultSet resultSet = null;
		
		try {
			connection = JDBCUtil.getConnection();
			preparedStatement = connection.prepareStatement("select * from user where username=? and password=?");
			preparedStatement.setObject(1, user.getUsername());
			preparedStatement.setObject(2, user.getPassword());
			resultSet = preparedStatement.executeQuery();
//			java.sql.Statement stmt = connection.createStatement();
//			String sql = "select * from user where username=\""+username+"\" and password=\""+password+"\"";
//			resultSet = stmt.executeQuery(sql);
			
			while (resultSet.next()) {
//				user = new User();
				user.setUserid(resultSet.getInt("USERID"));
//				user.setUsername(resultSet.getString("USERNAME"));
				user.setLogin_count(resultSet.getInt("login_count")+1);
				user.setLast_login_time(resultSet.getTimestamp("Last_login_time"));
				user.setHobby(resultSet.getString("Hobby"));
				user.setComment(resultSet.getString("Comment"));
				preparedStatement = connection.prepareStatement("update user set login_count=login_count+1,LAST_LOGIN_TIME=now() where username=?");
				preparedStatement.setString(1, user.getUsername());
				int i = preparedStatement.executeUpdate();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.close(resultSet, preparedStatement, connection);
		}
		return user;
	}
	
	public User userLogin(String username) {
		User user = null;
		java.sql.Connection connection = null;
		java.sql.PreparedStatement preparedStatement = null;
		java.sql.ResultSet resultSet = null;
		
		try {
			connection = JDBCUtil.getConnection();
			preparedStatement = connection.prepareStatement("select * from user where username=?");
			preparedStatement.setObject(1, username);
			resultSet = preparedStatement.executeQuery();

			while (resultSet.next()) {
				user.setUserid(resultSet.getInt("USERID"));
				user.setLogin_count(resultSet.getInt("login_count")+1);
				user.setLast_login_time(resultSet.getTimestamp("Last_login_time"));
				user.setHobby(resultSet.getString("Hobby"));
				user.setComment(resultSet.getString("Comment"));
				preparedStatement = connection.prepareStatement("update user set login_count=login_count+1,LAST_LOGIN_TIME=now() where username=?");
				preparedStatement.setString(1, username);
				int i = preparedStatement.executeUpdate();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.close(resultSet, preparedStatement, connection);
		}
		return user;
	}
	//用户注册过程,判断用户名存在否
	public User userToRegister(String username) {
		User user = null;
		java.sql.Connection connection = null;
		java.sql.PreparedStatement preparedStatement = null;
		java.sql.ResultSet resultSet = null;
		
		try {
			connection = JDBCUtil.getConnection();
			preparedStatement = connection.prepareStatement("select username from user where username=?");
			preparedStatement.setObject(1, username);
			resultSet = preparedStatement.executeQuery();
			
			while (resultSet.next()) {
				user = new User();
				user.setUsername(resultSet.getString("USERNAME"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.close(resultSet, preparedStatement, connection);
		}
		return user;
	}

	
	//用户注册过程,创建新用户
	public int userRegister(User user) {
//		User user = null;
		java.sql.Connection connection = null;
		java.sql.PreparedStatement preparedStatement = null;
		int executeCount = 0;
		
		try {
			
			connection = JDBCUtil.getConnection();
			preparedStatement = connection.prepareStatement("insert into user (username,password,hobby,comment) values(?,?,?,?)");
			preparedStatement.setObject(1, user.getUsername());
			preparedStatement.setObject(2, user.getPassword());
			preparedStatement.setObject(3, user.getHobby());
			preparedStatement.setObject(4, user.getComment());
			executeCount = preparedStatement.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.close(preparedStatement, connection);
		}
		return executeCount;
	}

}

(5)在com.qianfeng.orderfood.entity中创建User.java

package com.qianfeng.orderfood.entity;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
// 什么样的文件才有资格叫实体类?
// 1:要符合ORM规范 
// (保持3个一直  表名和文件名一致)
// JAVA文件的属性名和数据库中的字段名要保持一致
// 数据库中的类型和JAVA中的类型要可以转换
// 2:要符合JAVABEAN规范
// 符合最基础的JAVABEAN 规范要满足以下几点
// (1)私有的属性
// (2)为私有的属性提供 GETER STEER
// (3)提供无参构造函数
// (4)实现序列化接口 (可以把文件存储内存中)

public class User implements Serializable { //User类,VO类
	private int userid;
	private String username;
	private String password;
	private Timestamp createtime;
	private Timestamp updatetime;
	private int login_count;
	private Timestamp last_login_time;//增加实体及其属性
	private String hobby;
	private String comment;
	
	//快捷键ALT+SHIFT+S生成get和set函数
	
	public User(HttpServletRequest req) {
		super();
		username = req.getParameter("username");
		password = req.getParameter("password");
//		try {
				System.out.printf("%v","asd".getBytes("ISO-8859-1"));
//			System.out.println(new String(req.getParameterValues("hobby")[0].getBytes(req.getParameter("username")),req.getParameter("password")));
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		hobby = "";
		comment = "";
		if(req.getParameterValues("hobby")!=null) {			
			for(String _hobby :req.getParameterValues("hobby"))
			hobby += _hobby;
			hobby += ",";
		}
		if(req.getParameter("comment")!=null) {			
			comment = req.getParameter("comment");
		}
//		if(username==null||password==null)
		this.username = username;
		this.password = password;
		try {
			this.hobby = new String(hobby.getBytes("ISO-8859-1"),"UTF-8");
			this.comment = new String(comment.getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public User() {
		// TODO Auto-generated constructor stub
	}

	public int getLogin_count() {
		return login_count;
	}
	public String getComment() {
		return comment;
	}
	public void setComment(String comment) {
		this.comment = comment;
	}
	public String getHobby() {
		return hobby;
	}
	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	public void setLogin_count(int login_count) {
		this.login_count = login_count;
	}
	public Timestamp getLast_login_time() {
		return last_login_time;
	}
	public void setLast_login_time(Timestamp last_login_time) {
		this.last_login_time = last_login_time;
	}
	public int getUserid() {
		return userid;
	}
	public void setUserid(int userid) {
		this.userid = userid;
	}
	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 Timestamp getCreatetime() {
		return createtime;
	}
	public void setCreatetime(Timestamp createtime) {
		this.createtime = createtime;
	}
	public Timestamp getUpdatetime() {
		return updatetime;
	}
	public void setUpdatetime(Timestamp updatetime) {
		this.updatetime = updatetime;
	}
	
	
}

(6)在com.qianfeng.orderfood.eums中创建UserLoginEnum.java和UserRegisterEnum.java

package com.qianfeng.orderfood.eums;

public enum UserLoginEnum {

	// 枚举的格式   是全部要大写 多个单词 用下划线隔开
		// ctrl + shift + y + x  (大小写转换)
		// 一个功能如果 有涉及到业务场景 那么这个时候 我们就要考虑到封装一个枚举文件 用来记录这些业务场景,而不是
		// 让开发开发人员去死记硬背 这些 单词
		USER_NAME_IS_NUll("user_name_is_null","用户名不能为空"),
		USER_PASSWORD_IS_NULL("user_password_is_null","密码不能为空"),
		USER_NAME_OR_PASSWORD_IS_FAIL("user_name_or_password_is_fail","用户名或密码错误"),
		USER_VALIDATE_CODE_IS_FAIL("user_validate_code_is_fail","验证码错误"),
		USER_LOGIN_SUCCESS("user_login_success","登录成功");
		
		private String value;
		private String desc;
		// 添加构造函数的 快捷键 是 alt + shift + s
		private UserLoginEnum(String value, String desc) {
			this.value = value;
			this.desc = desc;
		}
		public String getValue() {
			return value;
		}
		public void setValue(String value) {
			this.value = value;
		}
		public String getDesc() {
			return desc;
		}
		public void setDesc(String desc) {
			this.desc = desc;
		}
}
package com.qianfeng.orderfood.eums;

public enum UserRegisterEnum {
	
	// 枚举的格式   是全部要大写 多个单词 用下划线隔开
	// ctrl + shift + y + x  (大小写转换)
	// 一个功能如果 有涉及到业务场景 那么这个时候 我们就要考虑到封装一个枚举文件 用来记录这些业务场景,而不是
	// 让开发开发人员去死记硬背 这些 单词
	
	USER_REGISTER_NAME_IS_EXIST("user_register_name_is_exist","该用户名已存在"),
	USER_REGISTER_NAME_IS_NULL("user_register_name_is_null","注册的用户名不能为空"),
	USER_REGISTER_PASSWORD_IS_NULL("user_register_password_is_null","注册的密码不能为空"),
	USER_REGISTER_AGAINPASSWORD_IS_DIFFERENT("user_register_againpassword_is_different","两次密码不一致"),
	USER_REGISTER_VALIDATE_CODE_IS_NULL("user_register_validate_code_is_null","验证码不能为空"),
	USER_REGISTER_VALIDATE_CODE_IS_FAIL("user_register_validate_code_is_fail","验证码错误"),
	USER_REGISTER_SUCCESS("user_register_success","注册成功");
	
	private String value;
	private String desc;
	
	private UserRegisterEnum(String value, String desc) {
		this.value = value;
		this.desc = desc;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	public String getDesc() {
		return desc;
	}
	public void setDesc(String desc) {
		this.desc = desc;
	}
}

(7)在com.qianfeng.orderfood.servlet中创建UserLoginServlet.java和UserRegisterServlet.java

package com.qianfeng.orderfood.servlet;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qianfeng.orderfood.biz.UserBIZ;
import com.qianfeng.orderfood.bizimpl.UserBIZImpl;
import com.qianfeng.orderfood.eums.UserLoginEnum;
import com.qianfeng.orderfood.entity.User;
public class UserLoginServlet extends HttpServlet {
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp){
		String result = null;
//		String username = req.getParameter("username");
//		String password = req.getParameter("password");
//		String hobby =req.getParameter("hobby");
//		String comment =req.getParameter("comment");
		User user = new User(req);
		String validatecode = req.getParameter("validatecode");
		String syscode = (String) req.getSession().getAttribute("syscode");
		String id = req.getSession().getId();
		if(req.getParameter("rememberMe")!=null) {
			Cookie session_cookie = new Cookie("User",user.getUsername());
			session_cookie.setMaxAge(60*60*24*14);
			resp.addCookie(session_cookie);
		}
		try {
			UserBIZ userBIZ = new UserBIZImpl();
			result = userBIZ.userLogin(user, validatecode,syscode,req);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (result.equals(UserLoginEnum.USER_LOGIN_SUCCESS.getValue())) {
				req.getRequestDispatcher("index.jsp").forward(
						req, resp);
			} else {
				req.getRequestDispatcher("user_login.jsp?msg=" + result + "")
						.forward(req, resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
//	@Override
//	protected void doGet(HttpServletRequest req, HttpServletResponse resp){
//		doPost(req,resp);
//	}
}
package com.qianfeng.orderfood.servlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qianfeng.orderfood.biz.UserBIZ;
import com.qianfeng.orderfood.bizimpl.UserBIZImpl;
import com.qianfeng.orderfood.entity.User;
import com.qianfeng.orderfood.eums.UserLoginEnum;
import com.qianfeng.orderfood.eums.UserRegisterEnum;

public class UserRegisterServlet extends HttpServlet {
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp){
		String result = null;
//		String username = req.getParameter("username");
//		String password = req.getParameter("password");
		String againpassword = req.getParameter("againpassword");
		String validatecode = req.getParameter("validatecode");
		String syscode = (String) req.getSession().getAttribute("syscode");
//		String hobby = String.join(",", req.getParameterValues("hobby"));
//		String comment = req.getParameter("comment");
		User user = new User(req);
		System.out.println(user.getHobby());
		System.out.println(user.getComment());
		try {
			UserBIZ userBIZ = new UserBIZImpl();
			result = userBIZ.userRegister(user, againpassword,validatecode, syscode,req);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (result.equals(UserRegisterEnum.USER_REGISTER_SUCCESS.getValue())) {
				req.getRequestDispatcher("user_login.jsp?msg=" + result + "").forward(
						req, resp);
			} else {
				req.getRequestDispatcher("user_register.jsp?msg=" + result + "")
						.forward(req, resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}//没有传userid。解决:每次userid自动设置,自动加1
	}
	protected void doGet(HttpServletRequest req, HttpServletResponse resp){
		doPost(req,resp);
	}
}

(8)在com.qianfeng.orderfood.util中创建JDBCUtil.java、StringUtil.java和ValidateUtil.java,数据库密码要改成自己的

package com.qianfeng.orderfood.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCUtil {

	//useSSL=false 是Mysql数据库的SSL连接问题,提示警告不建议使用没有带服务器身份验证的SSL连接
	private static final String driver="com.mysql.jdbc.Driver";
	//数据库名称填写自己的:这里是test
	private static final String url="jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8";
	private static final String user="root";//mysql -u用户名 -p密码
	private static final String password="root";
	static{
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	public static Connection getConnection(){
		
		try {
			return DriverManager.getConnection(url,user,password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	// 查询使用的关闭
	public static void close(ResultSet resultSet,
			PreparedStatement preparedStatement, Connection connection) {
		try {
				resultSet.close();
				preparedStatement.close();
				connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 增删查改的关闭
	public static void close(PreparedStatement preparedStatement,
			Connection connection) {
		try {
			preparedStatement.close();
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}

package com.qianfeng.orderfood.util;

public class StringUtil {
	
	// 为何要判断NULL 和 空字符串呢?
	
	// NULL 在用户没有在请求报文中传输该KEY的时候发生
	// "" 是用户在表单没有输入数据的情况下发生
	public static boolean isEmpty(String arg){
		return arg == null || arg.equals("");
	}

	public static boolean isNotEmpty(String arg){
		return arg != null && !arg.equals("");
	}
}


package com.qianfeng.orderfood.util;

import java.util.Random;

public class ValidateUtil {

	public static String createValidateCode() {
		String temp = "1234567890qwertyuioplkjhgfdsazxcvbnm";
		StringBuilder validateCode = new StringBuilder();
		for (int i = 0; i < 4; i++) {
			validateCode.append(temp.charAt(new Random().nextInt(temp
					.length())));
		}
		return validateCode.toString();
	}

	public static void main(String[] args) {
		System.out.println(createValidateCode());
	}
}


WebContent

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- 页面跳转失败,原因是没有index.jsp页面 -->
<%@ page import="com.qianfeng.orderfood.entity.User" %>
<%
User user = null;
if(session.getAttribute("user")!=null){	
	user=(User)session.getAttribute("user");
	}

if(user==null){
	request.getRequestDispatcher("user_login.jsp").forward(
			request, response);
}


%>
<html><h1>Hello <%  out.println(user.getUsername()); %></h1>
用户登陆次数:<%=user.getLogin_count() %> <br>
最新登录时间:<%=user.getLast_login_time() %><br>
用户爱好:<%=user.getHobby() %><br>
用户简介:<%=user.getComment() %><br>
<a href="./logout.jsp">Log out</a>
</html>

<!-- 
Model:某一类数据 View:你看到的页面 Controller:业务功能

登陆计数
1.修改Model 加一个属性和数据表列
2.增加数据回显
3.修改Controller 找到最终功能的实现代码,进行修改。
 -->

user_login.jsp

<%@page import="com.qianfeng.orderfood.util.ValidateUtil"%>
<%@page import="com.qianfeng.orderfood.eums.UserLoginEnum"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
session.setMaxInactiveInterval(60*24*14);
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>用户登陆注册页面</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<meta charset="UTF-8">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	
<script type="text/javascript">

	<%String msg = request.getParameter("msg") == null ? "" : request
					.getParameter("msg");%>
					
	<%if (msg.equals(UserLoginEnum.USER_NAME_IS_NUll.getValue())) {%>
	 alert("<%=UserLoginEnum.USER_NAME_IS_NUll.getDesc()%>");
	<%}%>			
			
	<%if (msg.equals(UserLoginEnum.USER_PASSWORD_IS_NULL.getValue())) {%>
	 alert("<%=UserLoginEnum.USER_PASSWORD_IS_NULL.getDesc()%>");
	<%}%>
		
	<%if (msg.equals(UserLoginEnum.USER_VALIDATE_CODE_IS_FAIL.getValue())) {%>
	 alert("<%=UserLoginEnum.USER_VALIDATE_CODE_IS_FAIL.getDesc()%>");
	<%}%>
					
	<%if (msg.equals(UserLoginEnum.USER_NAME_OR_PASSWORD_IS_FAIL.getValue())) {%>
	 alert("<%=UserLoginEnum.USER_NAME_OR_PASSWORD_IS_FAIL.getDesc()%>");
	<%}%>

	<%if (msg.equals(UserLoginEnum.USER_LOGIN_SUCCESS.getValue())) {%>
	 alert("<%=UserLoginEnum.USER_LOGIN_SUCCESS.getDesc()%>");
<%}%>
	
</script>

  </head>
  
  <body >
  	<div style="position: absolute;top:0;bottom: 0;left: 0;right: 0;height: 300px;width: 500px;margin:auto;">
  	<form action="./UserLoginServlet" method="post">
  		<center><h1 style="color:red">用户登陆注册页面</h1>
  		<table style="text-align:justify;text-align-last: justify;">
  			<tr>
  				<td>用 户 名:</td>
  				<td><input name="username"></td>
  			</tr>
  			<tr>
  				<td>密  码:</td>
  				<td><input name="password"></td>
  			</tr>
  			<tr>
 				<%
					String validateCode = ValidateUtil.createValidateCode();
					session.setAttribute("syscode", validateCode);
				%>
  				<td>验 证 码:</td>
  				<td><input name="validatecode"></td>
  				<td><b><i style="color: red"><%=validateCode%></i> </b></td>
  			</tr>
  			<tr>
  				<td>
  					<form>
  						<input type = "checkbox" value="两周内免登陆" id="login" check="checked" name="rememberMe"><label for="login">两周内免登陆</label>
  					</form>
  				</td>
  				<td></td>
  			</tr>
  			<tr>	
	  			<td><button type="submit">登录</button></td>
	  			<td><input type="button" value="注册" onclick="location='user_register.jsp'"/></td>
  			</tr>
  		</table></center>
  	</form>
  	</div>
  	  <%
    Date date = new Date();
    out.print("服务器当前时间:"+date.toString());
  %>
  </body>
</html>


user_register.jsp

<%@page import="com.qianfeng.orderfood.util.ValidateUtil"%>
<%@page import="com.qianfeng.orderfood.eums.UserRegisterEnum"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>用户注册</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<meta charset="UTF-8">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	
	<script type="text/javascript">

	<%String msg = request.getParameter("msg") == null ? "" : request
					.getParameter("msg");%>
					
	<%if (msg.equals(UserRegisterEnum.USER_REGISTER_NAME_IS_EXIST.getValue())) {%>
	 alert("<%=UserRegisterEnum.USER_REGISTER_NAME_IS_EXIST.getDesc()%>");
	<%}%>			
	
	<%if (msg.equals(UserRegisterEnum.USER_REGISTER_NAME_IS_NULL.getValue())) {%>
	 alert("<%=UserRegisterEnum.USER_REGISTER_NAME_IS_NULL.getDesc()%>");
	<%}%>
					
	<%if (msg.equals(UserRegisterEnum.USER_REGISTER_PASSWORD_IS_NULL.getValue())) {%>
	 alert("<%=UserRegisterEnum.USER_REGISTER_PASSWORD_IS_NULL.getDesc()%>");
	<%}%>
	
	<%if (msg.equals(UserRegisterEnum.USER_REGISTER_AGAINPASSWORD_IS_DIFFERENT.getValue())) {%>
	 alert("<%=UserRegisterEnum.USER_REGISTER_AGAINPASSWORD_IS_DIFFERENT.getDesc()%>");
	<%}%>
	
	<%if (msg.equals(UserRegisterEnum.USER_REGISTER_VALIDATE_CODE_IS_NULL.getValue())) {%>
	 alert("<%=UserRegisterEnum.USER_REGISTER_VALIDATE_CODE_IS_NULL.getDesc()%>");
	<%}%>
	
	<%if (msg.equals(UserRegisterEnum.USER_REGISTER_VALIDATE_CODE_IS_FAIL.getValue())) {%>
	 alert("<%=UserRegisterEnum.USER_REGISTER_VALIDATE_CODE_IS_FAIL.getDesc()%>");
	<%}%>

	<%if (msg.equals(UserRegisterEnum.USER_REGISTER_SUCCESS.getValue())) {%>
	 alert("<%=UserRegisterEnum.USER_REGISTER_SUCCESS.getDesc()%>");
<%}%>
	
</script>

  </head>
   <body >
  	<div style="position: absolute;top:0;bottom: 0;left: 0;right: 0;height: 300px;width: 500px;margin:auto;">
  	<form action="UserRegisterServlet" method="post" accept-charset="UTF-8">
  		<center><h1 style="color:red">用户注册</h1>
  		<table style="text-align:justify;text-align-last: justify;">
  			<tr>
  				<td>用户名:</td>
  				<td><input name="username"></td>
  			</tr>
  			<tr>
  				<td>密  码:</td>
  				<td><input name="password"></td>
  			</tr>
  			<tr>
  				<td>确认密码:</td>
  				<td><input name="againpassword"></td>
  			</tr>
  			<tr>
  				<td>兴趣爱好:</td>
				<td><input type="checkbox" name="hobby" value="唱歌">唱歌<input type="checkbox" name="hobby" value="跳舞">跳舞
				 <input type="checkbox" name="hobby" value="打豆豆">打豆豆</td>  <!-- hobby写进数据库,并在前端打印出来 -->
  			</tr>
  			<tr>
  				<td>简 介:</td>
  				<td>
  					<textarea cols="22" rows="2" name="comment" ></textarea>
  				</td>
  			</tr>
  			<tr>
 				<%
					String validateCode = ValidateUtil.createValidateCode();
					session.setAttribute("syscode", validateCode);
				%>
  				<td>验证码:</td>
  				<td><input name="validatecode"></td>
  				<td><b><i style="color: red"><%=validateCode%></i> </b></td>
  			</tr>
  			
  			<tr>
	  			<td><button type="submit">注册</button></td>
	  			<td><input type="button" value="返回" onclick="location='user_login.jsp'"/></td>
  			</tr>
  		</table></center>
  	</form>
  	</div>
  </body>
</html>


logout.jsp


<%  session.setAttribute("user",null);%>
<html><h1>Hello <%  out.println(session.getAttribute("user")); %></h1>

</html>

WebContent–>WEB-INF

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>WebRoot</display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>UserLoginServlet</servlet-name>
    <servlet-class>com.qianfeng.orderfood.servlet.UserLoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UserLoginServlet</servlet-name>
    <url-pattern>/UserLoginServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>UserRegisterServlet</servlet-name>
    <servlet-class>com.qianfeng.orderfood.servlet.UserRegisterServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UserRegisterServlet</servlet-name>
    <url-pattern>/UserRegisterServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

运行的时候要运行user_login.jsp

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

参考文章https://blog.csdn.net/weixin_44253375/article/details/108290462,写的时候遇到了很多问题,比如Navicat连接不上、端口号占用等等,后面把网址都总结发出来,如果遇到什么问题可以去看一下有没有一样的。

  • 3
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值