一、创建数据库表连接
这里我们创建一个数据库名为db_user,创建库的使用可视化工具很简单就不细说了,下面sql代码块是我们创建一个简易用户表为了方便我们后续进行登录注册操作。
下面就是建好的表:
1、建一个与数据库连接的file文件:db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_user
user=root
password=123456
二、创建前端页面
1、登录界面
使用form表单进行数据的提交,form表单中的action属性指的是将数据提交,method是使用post方法进行提交,post方法具有比get更好的数据隐蔽性,如果大家想更加了解form表单中的用户可以自己去学习一下,此处不在讲述,直接上代码。
在web包下面创一个login2.jsp文件
<%--
Created by IntelliJ IDEA.
User: ASUS
Date: 2023/9/27
Time: 9:06
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.HashMap" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
HashMap<String,String> error = ((HashMap<String, String>)request.getAttribute("error"));
String fail = (String)request.getAttribute("fail");
%>
<form action="UserController" method="post">
<input type="hidden" value="login" name="userAction">
<table border="1" align="center">
<tr align="center"><td colspan="2">登录</td></tr>
<tr>
<td>账号<input type="text" name="username"><span style="color:pink"> <%=fail==null?"":fail%></span><span style="color:pink"> <%=error==null?"":error.get("username")==null?"":error.get("username")%></span></td>
</tr>
<tr>
<td>密码<input type="text" name="password"><span style="color:pink"> <%=error==null?"":error.get("password")==null?"":error.get("password")%></span></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交"><input type="reset" value="重置"></td>
</tr>
</table>
</form>
</body>
</html>
2、注册界面
下面是注册界面的代码,和登录界面类似
<%@ page import="java.util.HashMap" %><%--
Created by IntelliJ IDEA.
User: ASUS
Date: 2023/9/21
Time: 9:32
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
HashMap<String,String> error = ((HashMap<String, String>)request.getAttribute("error"));
String registerfail = request.getParameter("registerfail");
%>
<span><%=registerfail==null?"":registerfail%></span>
<form action="UserController" method="post">
<table width="30%" height="300px" border="1" id="table01">
<tr align="center">
<td colspan="2">注册</td>
</tr>
<tr>
<td>用户名:</td><td><input type="text" name="username"><%=error==null?"":error.get("username")==null?"":error.get("username")%></td>
</tr>
<tr>
<td>密码:</td><td><input type="text" name="password"><%=error==null?"":error.get("password")==null?"":error.get("password")%></td>
</tr>
<tr>
<td>年龄:</td><td><input type="text" name="age"></td>
</tr>
<tr>
<td>出生年月:</td><td><input type="text" name="birthday"></td>
</tr>
<tr>
<td>性别:</td>
<td>
<input type="radio" value="female" name="gender">女
<input type="radio" value="male" name="gender">男
</td>
</tr>
<tr>
<td>爱好:</td>
<td>
<input type="checkbox" value="篮球" name="hobbies">篮球
<input type="checkbox" value="羽毛球" name="hobbies">羽毛球
<input type="checkbox" value="足球" name="hobbies">足球
</td>
</tr>
<tr>
<td>地址</td>
<td>
<select name="address">
<option value="成都">成都</option>
<option value="贵州">贵州</option>
</select>
</td>
</tr>
<tr>
<td>备注:</td>
<td><textarea cols="30" rows="10" name="remark"></textarea> </td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="提交">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>
三、后端数据处理
提示:本文Java后端采用MVC模式开发,MVC是当前主流开发模式,如果不理解的请看链接: MVC框架.
1、登录与注册实现
先在src中创建几个包,分别是service,dao,Controller,utils,domain。
- service层(业务层):封装通用的业务逻辑,操作;与数据层的交互。
- dao层(数据层):主要做数据持久层的工作,封装负责与数据库进行操作的代码。
- domain:实体类。
- utils :封装工具类。
service层应该既调用dao层的接口,又要提供接口给controller层的类来进行调用,它刚好处于一个中间层的位置。
处理流程为:controller层调用 service层, service层在调用dao层;dao层处理完数据返回 service层, service层在返回controller层,controller层最终返回前端。
实例:
domian:
import java.io.Serializable;
/**
* 一般带数据的实体类最好序列化(为了数据传输/存储)
*/
public class User implements Serializable{
private String username;
private String password;
private String gender;
private String hobbies;
private String address;
private String remark;
private int age;
private String birthday;
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public void setHobbies(String hobbies) {
this.hobbies = hobbies;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getHobby() {
return hobbies;
}
public void setHobby(String hobbies) {
this.hobbies = hobbies;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", gender='" + gender + '\'' +
", hobbies='" + hobbies + '\'' +
", address='" + address + '\'' +
", remark='" + remark + '\'' +
", age=" + age +
", birthday='" + birthday + '\'' +
'}';
}
public String getHobbies() {
return hobbies;
}
}
Controller:建一个UserContrller文件
import com.xinhua.domain.User;
import com.xinhua.service.UserService;
import com.xinhua.validate.ValidateDemo;
import org.apache.commons.beanutils.BeanUtils;
import utils.ArrayToString;
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.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
@WebServlet("/UserController")
public class UserController extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("userAction");
//处理中文乱码
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
//登录
if ("login".equals(action)){
User user = new User();
try {
BeanUtils.populate(user,req.getParameterMap());
Map<String,String> error = ValidateDemo.validateUser(user);
if (error.isEmpty()){
UserService userService = new UserService();
boolean flag = userService.login(user.getUsername(),user.getPassword());
if (flag){
resp.sendRedirect("index01.jsp?username="+ URLEncoder. encode(user.getUsername(),"utf-8"));
}else {
req.setAttribute("fail","登录失败");
req.getRequestDispatcher("login2.jsp").forward(req,resp);
}
}else {
req. setAttribute( "error", error);
req.getRequestDispatcher( "login2.jsp").forward(req,resp);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
//注册
if ("register".equals(action)){//接收数据和封装
User user = new User();
try {
BeanUtils.populate(user,req.getParameterMap());
user.setHobbies(ArrayToString.arrayToString(req.getParameterValues("hobbies")));
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}//验证数据
Map<String,String> error = new HashMap<>();
if (error.isEmpty()){
//调用service处理业务
UserService userService = new UserService();
int state = userService.register(user);
if (state==0){
resp.sendRedirect("/registerfail.jsp");
}
if (state==1){
resp.sendRedirect("/registersuccess.jsp");
}
if (state==2){
resp.sendRedirect("/register.jsp?registerfail="+ URLEncoder. encode( "该用户已经存在!", "utf-8"));
}
}else {//带错误数据跳转到注册界面
req. setAttribute( "error", error);
req.getRequestDispatcher( "/register.jsp").forward(req, resp);
}
}
}
}
service
import com.xinhua.dao.UserDao;
import com.xinhua.domain.User;
/**
* 处理user的相关业务
* 业务层命名的原则是表达具体业务
*/
public class UserService {
/**
* 用户登录
*/
public boolean login(String username,String password){
UserDao userDao = new UserDao();
boolean flag = userDao.findUserByUsernameAndPassword(username,password);
return flag;
}
/**
* 注册用户
* 如果只有两种返回结果状态用boolean
* 超过两种用int(0(注册没有成功)1(注册成功)2(表示用户存在))
* 业务函数的名字要体现业务
*/
public int register(User user){
//判断用户是否存在
UserDao userDao = new UserDao();
boolean flag = userDao.findUserByUsername(user.getUsername());
int state=0;
if (flag){//用户存在
state=2;
}else {
int i = userDao.addUser(user);
if (i>0){
state=1;
}else {
state=0;
}
}
return state;
}
}
dao
import com.xinhua.domain.User;
import utils.DBUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//数据处理
public class UserDao {
//通过用户名和密码查询用户
public boolean findUserByUsernameAndPassword(String username,String password){
Connection conn = null;
String sql = null;
PreparedStatement ps = null;
ResultSet rs = null;
boolean flag = false;
try {
conn = DBUtils.getConnection();
sql = "SELECT id FROM USER WHERE username=? AND password=?";
ps = conn.prepareStatement(sql);
ps.setString(1,username);
ps.setString(2,password);
rs = ps.executeQuery();
while (rs.next()){
if (rs.getInt(1)>0){
flag = true;
}
}
}catch (SQLException e){
e.printStackTrace();
}
DBUtils.closeDB(conn,ps,rs);
return flag;
}
//根据用户名查询用户
public boolean findUserByUsername(String username){
//连接数据库
Connection conn = null;
String sql = null;
PreparedStatement ps = null;
ResultSet rs = null;
boolean flag = false;
try {
conn = DBUtils.getConnection();
sql = "SELECT id FROM USER WHERE username=?";
ps = conn.prepareStatement(sql);
ps.setString(1,username);
rs = ps.executeQuery();
while (rs.next()){
if (rs.getInt(1)>0){
flag = true;
}
}
}catch (SQLException e){
e.printStackTrace();
}
DBUtils.closeDB(conn,ps,rs);
return flag;
}
//添加用户
public static int addUser(User user){
Connection conn = null;
String sql = null;
PreparedStatement ps = null;
int i = 0;
try {
conn = DBUtils.getConnection();
sql = "insert into user(username,password,gender,age,hoddies,remark,address) values(?,?,?,?,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1,user.getUsername());
ps.setString(2,user.getPassword());
ps.setString(3,user.getGender());
ps.setInt(4,user.getAge());
ps.setString(5,user.getAddress());
ps.setString(6,user.getHobbies());
ps.setString(7,user.getRemark());
i = ps.executeUpdate();
return i;
} catch (SQLException e) {
e.printStackTrace();
}
DBUtils.closeDB(conn,ps,null);
return i;
}
utils:建一个DBUtil
import java.sql.*;
import java.util.Properties;
/**
* 封装对数据库的连接等
*/
public class DBUtils {
//获得数据库连接
//拷贝数据库的连接相关的jar包
public static Connection getConnection(){//要获得配置信息
Properties properties = ReadFileDemo2.readFile("File/db.properties");
String driver = (String)properties.get("driver");
String url = (String)properties.get("url");
String user = (String)properties.get("user");
String password = (String)properties.get("password");
try {
Class.forName(driver);
Connection connection=DriverManager.getConnection(url,user,password);
return connection;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//关闭数据库连接
public static void closeDB(Connection conn, PreparedStatement ps, ResultSet rs){
//关闭资源要倒叙关闭
//不要因为关闭一个资源出现异常影响到其他的资源关闭
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
还有两个新添加的前端界面,分别是registerSuccess.jsp,registerfail.jsp,index01.jsp如下:
<%--
Created by IntelliJ IDEA.
User: ASUS
Date: 2023/9/21
Time: 10:30
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>注册成功</h1><a href="login2.jsp">返回</a>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: ASUS
Date: 2023/9/21
Time: 10:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>注册失败</h1><a href="register.jsp">返回</a>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: ASUS
Date: 2023/9/19
Time: 8:50
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<!-- jsp就是可以在网页中写入java脚本
脚本分为两种一是客户端脚本二是服务器端脚本!-->
恭喜<span style="color: pink"><%=request.getParameter("username")%></span>登录成功 Welcome to javaweb!
</body>
</html>
四、页面展示
1、注册
2、登录
文章来源:https://www.toymoban.com/news/detail-806005.html
3、登录成功
文章来源地址https://www.toymoban.com/news/detail-806005.html
到了这里,关于JavaWeb实现简易的注册登录功能(与数据库连接)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!