目录
前言
一、理解MVC框架
二、项目结构
三、详细设计
bean
1、新建bean文件夹,作为JavaBean的开始,编写 bean.User,封装注册登录的用户名和密码的信息(name、password)
2、编写bean.Users,封装动物管理表的信息(id、uname、uage)
dao
1.建立接口,UserDao包含实现登录(find)和注册(save)需要的功能性接口和接口的实现
UserDaoImpl
2、信息管理界面需要实现的功能接口(显示、添加、删除、修改)和接口实现
Servlet
1、登录需要调用功能性实现(业务逻辑层)
2、登出
3、注册
4、添加
5、删除
6、显示
7、修改
8、更新
Tool
1、连接数据库
Jsp
1、注册界面
2、登录界面
3、登录失败
4、登录成功
5、显示页面
6、 添加界面
7、修改界面
xml
前言
本篇文章内容主要介绍一下如何利用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和Setterpublic 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;}@Overridepublic 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=" /> 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 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)throwsException{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 {@Overrideprotected 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");}@Overrideprotected 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 {@Overrideprotected 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");}@Overrideprotected 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 {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setCharacterEncoding("gbk");PrintWriter out = response.getWriter();out.print("");UserInfoDaoImpl userInfoDAO = new UserInfoDaoImpl();ArrayList list = new ArrayList();try {list = (ArrayList) userInfoDAO.userDisp();//遍历listrequest.setAttribute("list",list);//保存了一个变量为list的数据,数据内容就是从数据库中读取的所有用户信息//如何把request中保存的数据返回给客户端request.getRequestDispatcher("disp.jsp").forward(request,response);//带数据的页面跳转//response.sendRedirect("jisp.jsp");//也可以页面跳转但是不带数据} catch (Exception e) {throw new RuntimeException(e);}}@Overrideprotected 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 {@Overrideprotected 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);}@Overrideprotected 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 {@Overrideprotected 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");}@Overrideprotected 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
注册 body{background-image: url("beijing.jpg");background-size:cover;}用户注册
用户名:密码:
2、登录界面
login
登录 body{background-image: url("beijing.jpg");background-size:cover;}欢迎来到动物园动物管理系统
用户名:密码:
注册新用户
3、登录失败
failure
登录失败 body{background-image: url("beijing.jpg");background-size:cover;}登陆失败...请重试
返回首页
4、登录成功
success
登录成功 body{background-image: url("beijing.jpg");background-size:cover;}恭喜你!登录成功!
可以查看动物了!
查看动物信息
5、显示页面
disp
<%--Title body{background-image: url("beijing.jpg");background-size:cover;}动物信息
添加动物信息返回首页动物编号 动物名 动物年龄/岁 操作 ${user.id} ${user.uname} ${user.uage} 修改删除
6、 添加界面
userAdd
添加用户 body{background-image: url("beijing.jpg");background-size:cover;}添加动物信息
动物名称:
年龄 /岁:
7、修改界面
userModi
修改信息 body{background-image: url("beijing.jpg");background-size:cover;}动物信息修改
用户名:
年龄:
xml
login.jspLoginservlet.LoginServletLogin/loginRegisterservlet.RegistServletRegister/registerLogoutservlet.LogoutServletLogout/logout