目录
1、新建bean文件夹,作为JavaBean的开始,编写 bean.User,封装注册登录的用户名和密码的信息(name、password)
2、编写bean.Users,封装动物管理表的信息(id、uname、uage)
1.建立接口,UserDao包含实现登录(find)和注册(save)需要的功能性接口和接口的实现
2、信息管理界面需要实现的功能接口(显示、添加、删除、修改)和接口实现
前言
本篇文章内容主要介绍一下如何利用MVC架构实现一个简单的用户登录注册和管理(增删查改)的功能,下面内容就以描述如何一步步实现为主进行详细说明。
一、理解MVC框架
(JavaBean)M(模型)用于处理应用程序数据逻辑的部分通常模型对象负责在数据库中存取数据。
(Jsp)V(视图)应用程序中处理数据显示的部分通常视图是依据模型数据创建的。
(Servlet)C(控制器)应用程序中处理用户交互的部分通常控制器负责从视图读取数据,控制用户输入,并向模型发送数据。
下图的模型中就体现出了一个分层思想。
如果还想进行深一步的分开,可以将JavaBean再一次分割:业务逻辑、数据持久化。三层如下:
(1)表示层,JSP/Servlet;
(2)业务逻辑层:业务规则;
(3)持久化层:主要包装持久化的逻辑 ;
这个耦合度自然是最低的,也是比较适用于项目中去的,但是后来自然有新的Spring风靡全球。
二、项目结构
1、bean
Javabean用户封装设计,User包括注册和登录的用户名和密码(name,password),Users包括动物管理表格相关信息(id,uname,uage)。
2、dao
dao包括接口和impl子文件夹实现两个功能,impl子文件夹内的文件继承Dao文件。
3、servlet
作为控制层,收到请求后控制跟jsp和Dao的交互,把结果传送到jsp响应到浏览器。
4、tool
工具包,可以编写常用的代码,比如连接数据库。
5、jsp
最后的显示响应在浏览器上。
6、xml
别忘了配置xml。
三、详细设计
bean
1、新建bean文件夹,作为JavaBean的开始,编写 bean.User,封装注册登录的用户名和密码的信息(name、password)
User
package bean;
public class User {
private String name;
private String password;
//右键选生成Getter和Setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
// 构造方法用来传入数值
public User(String name, String password){
this.name = name;
this.password = password;
}
}
2、编写bean.Users,封装动物管理表的信息(id、uname、uage)
Users
package bean;
public class Users {
private int id;
private String uname;
private int uage;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public int getUage() {
return uage;
}
public void setUage(int uage) {
this.uage = uage;
}
@Override
public String toString() {
return "Users{" +
"id=" + id +
", uname='" + uname + '\'' +
", uage=" + uage +
'}';
}
}
dao
1.建立接口,UserDao包含实现登录(find)和注册(save)需要的功能性接口和接口的实现
UserDao
package dao;
import bean.User;
public interface UserDao {
static int find(User user) {
return 0;
}
static int save(User user) {
return 0;
}
}
UserDaoImpl
package dao.impl;
import bean.User;
import dao.UserDao;
import tool.Jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDaoImpl implements UserDao {
public static int find(User user) {
Connection conn = null;
PreparedStatement pstmt =null;
ResultSet rs = null;
int flag = -1;
try {
conn = Jdbc.getConn();
String sql = "select count(*) from user where username=? and password=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,user.getName());
pstmt.setString(2, user.getPassword());
rs = pstmt.executeQuery();
if (rs.next()) {
flag = rs.getInt(1);
}
if (flag > 0) { //登录成功
return 1;
} else{
return 0;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
return -1;
} catch (SQLException e) {
e.printStackTrace();
return -1;
}catch (Exception e){
e.printStackTrace();
return -1;
}finally {
try{
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static int save(User user) {
Connection conn = null;
PreparedStatement pstmt =null;
ResultSet rs = null;
int count =-1;
try {
conn = Jdbc.getConn(); //连接数据库
String sql = "insert into user values(?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getName());
pstmt.setString(2, user.getPassword());
count = pstmt.executeUpdate();
return count;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return -1;
} catch (SQLException e) {
e.printStackTrace();
return -1;
}catch (Exception e) {
e.printStackTrace();
return -1;
}finally {
try{
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
2、信息管理界面需要实现的功能接口(显示、添加、删除、修改)和接口实现
UserInfoDao
package dao;
import bean.Users;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public interface UserInfoDao {
static List userDisp(){
return null;
}
static void userAdd(Users users){
}
static void userDel(Users users){
}
static void userUp(Users users){
}
}
UserInfoDaoImpl
package dao.impl;
import bean.Users;
import dao.UserInfoDao;
import tool.Jdbc;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class UserInfoDaoImpl implements UserInfoDao {
//读取一个表的内容
public static List userDisp() throws Exception{
String sqlStr = "select * from users";
Connection conn = Jdbc.getConn();
Statement sta = conn.createStatement();
ResultSet rs = sta.executeQuery(sqlStr);
ArrayList<Users> list = new ArrayList<>();
while (rs.next()) {
Users user = new Users();
user.setId(rs.getInt("id"));
user.setUname(rs.getString("uname"));
user.setUage(rs.getInt("uage"));//封装完一条记录
list.add(user);
}
//关闭链接
rs.close();
sta.close();
conn.close();
return list;
}
public void userAdd(String uname,int uage) throws Exception{
String sqlStr = "insert into users (uname,uage) values(?,?)";//带参数的sql语句
Connection conn = Jdbc.getConn();
PreparedStatement sta = conn.prepareStatement(sqlStr);
sta.setString(1,uname);
sta.setInt(2,uage);
sta.executeUpdate();
//关闭
sta.close();
conn.close();
}
public void userDel(int id)throws Exception{
String sqlStr = "delete from users where id=?";
Connection conn = Jdbc.getConn();
PreparedStatement sta = conn.prepareStatement(sqlStr);
sta.setInt(1,id);
sta.executeUpdate();
sta.close();
conn.close();
}
public Users getUserById(int id)throws Exception{
String sqlStr = "select * from users where id=?"; //sql语句有错误,少了表名(已修复)
Connection conn = Jdbc.getConn();
PreparedStatement sta = conn.prepareStatement(sqlStr);
sta.setInt(1,id);
ResultSet rs = sta.executeQuery();
Users user = new Users();
if(rs.next()){
user.setId(rs.getInt("id"));
user.setUname(rs.getString("uname"));
user.setUage(rs.getInt("uage"));
return user;
}
return null;
}
public void userUp(int id,String uname,int uage) throws Exception{
String sqlStr = "update users set uname=?,uage=? where id=?";
Connection conn = Jdbc.getConn();
PreparedStatement sta = conn.prepareStatement(sqlStr);
sta.setString(1,uname);
sta.setInt(2,uage);
sta.setInt(3,id);
sta.executeUpdate();
sta.close();
conn.close();
}
}
Servlet
1、登录需要调用功能性实现(业务逻辑层)
LoginServlet
package servlet;
import bean.User;
import dao.impl.UserDaoImpl;
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;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//取值
request.setCharacterEncoding("utf-8");
String name = request.getParameter("uname");
String pwd = request.getParameter("upwd");
//封装
User user = new User(name, pwd);
//调用业务逻辑层
int result = UserDaoImpl.find(user);
if (result > 0) {
//登录成功
response.sendRedirect("success.jsp");//重定向到成功界面
} else {
//登录失败
response.sendRedirect("failure.jsp");//定位到失败页面
}
//请求转发
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
2、登出
LogoutServlet
package servlet;
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;
@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String encoding = "UTF-8";
request.setCharacterEncoding(encoding);
response.setContentType("text/html;charset="+encoding);
response.getWriter().write("注销成功。2秒后转向主页。");
response.setHeader("Refresh", "2;URL="+request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
3、注册
RegistServlet
package servlet;
import bean.User;
import dao.impl.UserDaoImpl;
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;
@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//注册功能、、向数据库添加数据
request.setCharacterEncoding("utf-8");
String name = request.getParameter("uname");
String pwd = request.getParameter("upwd");
User user = new User(name, pwd);//保存客户端输入的信息
int result = UserDaoImpl.save(user);
if (result > 0) {
//注册成功,2秒后转向主页
String encoding = "UTF-8";
request.setCharacterEncoding(encoding);
response.setContentType("text/html;charset="+encoding);
response.getWriter().write("注册成功。2秒后转向主页。");
response.setHeader("Refresh", "2;URL="+request.getContextPath());
} else {
//注册失败重新注册
response.sendRedirect("regist.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
4、添加
UserAddServlet
package servlet;
import dao.impl.UserInfoDaoImpl;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "UserAdd", value = "/UserAdd")
public class UserAddServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String uname;
int uage;
uname = request.getParameter("uname");
uage = Integer.parseInt(request.getParameter("uage"));
UserInfoDaoImpl userInfoDAO = new UserInfoDaoImpl();
try {
userInfoDAO.userAdd(uname,uage);
} catch (Exception e) {
System.out.println("User add error!!");
}
response.sendRedirect("UserDisp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
5、删除
UserDelServlet
package servlet;
import dao.impl.UserInfoDaoImpl;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "UserDel", value = "/UserDel")
public class UserDelServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
UserInfoDaoImpl userInfoDAO = new UserInfoDaoImpl();
try {
userInfoDAO.userDel(id);
} catch (Exception e) {
System.out.println("User delete error!!");
}
response.sendRedirect("UserDisp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
6、显示
UserDisp
package servlet;
import bean.Users;
import dao.impl.UserInfoDaoImpl;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
@WebServlet(name = "UserDisp", value = "/UserDisp")
public class UserDispServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("gbk");
PrintWriter out = response.getWriter();
out.print("<center>");
UserInfoDaoImpl userInfoDAO = new UserInfoDaoImpl();
ArrayList<Users> list = new ArrayList<>();
try {
list = (ArrayList<Users>) userInfoDAO.userDisp();
//遍历list
request.setAttribute("list",list);//保存了一个变量为list的数据,数据内容就是从数据库中读取的所有用户信息
//如何把request中保存的数据返回给客户端
request.getRequestDispatcher("disp.jsp").forward(request,response);//带数据的页面跳转
//response.sendRedirect("jisp.jsp");//也可以页面跳转但是不带数据
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
7、修改
UserModiServlet
package servlet;
import bean.Users;
import dao.impl.UserInfoDaoImpl;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "UserModi", value = "/UserModi")
public class UserModiServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
UserInfoDaoImpl userInfoDAO = new UserInfoDaoImpl();
Users users = new Users();
try {
users = userInfoDAO.getUserById(id);
} catch (Exception e) {
System.out.println("Get user by id error!!!");
}
request.setAttribute("user", users);
request.getRequestDispatcher("userModi.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
8、更新
UserUpServlet
package servlet;
import dao.impl.UserInfoDaoImpl;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "UserUp", value = "/UserUp")
public class UserUpServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
int id = Integer.parseInt(request.getParameter("id"));
String uname = request.getParameter("uname");
int uage = Integer.parseInt(request.getParameter("uage"));
UserInfoDaoImpl userInfoDAO = new UserInfoDaoImpl();
try {
userInfoDAO.userUp(id,uname,uage);
} catch (Exception e) {
System.out.println("User update error!!!");
}
response.sendRedirect("UserDisp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
Tool
1、连接数据库
Jdbc
package tool;
import java.sql.Connection;
import java.sql.DriverManager;
public class Jdbc {
private static String className = "com.mysql.cj.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/users?serverTimezone=Asia/Shanghai";
private static String username = "root";
private static String password = "123456";
public static Connection getConn() throws Exception {
Class.forName(className);
Connection conn = DriverManager.getConnection(url,username,password);
return conn;
}
}
Jsp
1、注册界面
regist
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册</title>
</head>
<body>
<style type="text/css">
body{
background-image: url("beijing.jpg");
background-size:cover;
}
</style>
<form action="RegistServlet" method="post">
<center>
<h2>用户注册</h2>
用户名:<input type="text" name="uname"/>
密码:<input type="password" name="upwd"/>
<input type="submit" value="注册"/>
</center>
</form>
</body>
</html>
2、登录界面
login
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<style type="text/css">
body{
background-image: url("beijing.jpg");
background-size:cover;
}
</style>
<form action="LoginServlet" method="post">
<center>
<h2>欢迎来到动物园动物管理系统</h2>
用户名:<input type="text" name="uname"/>
密码:<input type="password" name="upwd"/><br><br>
<input type="submit" value="登录"/>
<input type="reset" value="重置"/>
<a href="regist.jsp">注册新用户</a>
</center>
</form>
</body>
</html>
3、登录失败
failure
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录失败</title>
</head>
<body>
<style type="text/css">
body{
background-image: url("beijing.jpg");
background-size:cover;
}
</style>
<center>
<h2>登陆失败...请重试</h2><br>
<a href="login.jsp">返回首页</a>
</center>
</body>
</html>
4、登录成功
success
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录成功</title>
</head>
<body>
<style type="text/css">
body{
background-image: url("beijing.jpg");
background-size:cover;
}
</style>
<form action="LogoutServlet" method="post">
<center>
<h2>恭喜你!登录成功!</h2><br>
<h1>可以查看动物了!</h1>
<a href="UserDisp">查看动物信息</a>
<input type="submit" value="注销" />
</center>
</form>
</body>
</html>
5、显示页面
disp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%--
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<style type="text/css">
body{
background-image: url("beijing.jpg");
background-size:cover;
}
</style>
<center><h1>动物信息</h1>
<a href="userAdd.jsp">添加动物信息</a> <a href="login.jsp">返回首页</a>
<table border="1" align="center">
<tr>
<th width="200">动物编号</th><th width="200">动物名</th><th width="200">动物年龄/岁</th>
<th width="200">操作</th>
</tr>
<c:forEach items="${list}" var="user">
<tr>
<td>${user.id}</td><td>${user.uname}</td><td>${user.uage}</td>
<td><a href="UserModi?id=${user.id}">修改</a>
<a href="UserDel?id=${user.id}">删除</a> </td>
</tr>
</c:forEach>
</table>
</center>
</body>
</html>
6、 添加界面
userAdd
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加用户</title>
</head>
<body>
<style type="text/css">
body{
background-image: url("beijing.jpg");
background-size:cover;
}
</style>
<center>
<h1>添加动物信息</h1>
<form action="UserAdd" method="post">
动物名称:<input type="text" name="uname"><br/>
年龄 /岁:<input type="text" name="uage"><br/>
<input type="submit" value="提交">
<input type="reset" value="清空">
</form>
</center>
</body>
</html>
7、修改界面
userModi
<html>
<head>
<title>修改信息</title>
</head>
<body>
<style type="text/css">
body{
background-image: url("beijing.jpg");
background-size:cover;
}
</style>
<center>
<h1>动物信息修改</h1>
<form action="UserUp" method="post">
<input type="hidden" name="id" value="${user.id}">
用户名:<input type="text" name="uname" value="${user.uname}"><br />
年龄:<input type="text" name="uage" value="${user.uage}"><br />
<input type="submit" value="提交">
<input type="reset" value="清空">
</form>
</center>
</body>
</html>
xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 初始的页面 -->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<!-- 登录的servlet -->
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<!-- 注册的servlet -->
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>servlet.RegistServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
<!-- 注销的servlet -->
<servlet>
<servlet-name>Logout</servlet-name>
<servlet-class>servlet.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Logout</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>
</web-app>