一.案例要求
建库
要求登陆成功进入欢迎页面,显示用户信息(用自定义标签),完成用户信息输出
登录信息不正确回到登录页,并提示错误信息
注册时,用户名不可以重复,用ajax验证
注册成功,写入数据库,并返回登录页面
用户信息修改页面要求用在jsp页面使用Bean完成
-
各页面注意页面效果,用Bootstrap框架布局
注意:所有jsp页面不可以出现任何java代码
二.使用工具
工具
IDEA、Navicat 15 for MySQL、Tomcat服务器、java开发环境JDK1.8、xmind(思维导图工具)
相关文件的导入
- 在WEB-INF下新建lib文件夹,把jar包(843b)导入后按图示操作
- 按快捷键ctrl+shift+alt+s 打开Project Structure 选到Artifacts选区点击右下角的FIX... 选择Add ''to the artifact如果点完后还有FIX...继续重复操作,直至没有。
三.案例导图
四.案例实现
1.数据库建立
1.1 新建数据库
1.2 建表
1.3 添加记录
2.登录页面实现
Bootstrap部署
到Bootstrap下载文件,这里用的是Bootstrap4.4.1
下载好后把bootstrap-4.4.1下的dist文件夹中的两个文件夹复制粘贴到web目录下即可如下图(Bootstrap快速入门)
login.jsp实现
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%--导入标准库标签的包--%>
登录界面
<%--导入bootstrap的css样式--%>
<%--bootstrap的栅格布局--%>
用户登录
<%--mt调整margin-top--%>
<%--出错显示的信息框--%>
<%--如果request域中获取的errorMes不为空则显示下列信息--%>
<%--Bootstrap的警告框 直接从官网复制代码修改即可--%>
出错啦!
<%--导入bootstrap的js--%>
<%--导入jquery--%>
效果
3.JDBC的DAO模式实现
3.1 数据库连接类
需要加载的MySQL驱动已在提供的jar包中(mysql-connector-java-8.0.19)
package cn.lot.DB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnection {
/*加载的驱动程序名*/
private static final String DRIVER="com.mysql.cj.jdbc.Driver";
/*配置MySQL时的用户名和密码*/
private static final String USERNAME="你自己的用户名";
private static final String PASSWORD="密码";
/*URL指向访问的数据库名*/
private static final String URL="jdbc:mysql://localhost:3306/user?serverTimezone=Asia/Shanghai";/*设置为shanghai的时间*/
/*声明Connection对象*/
private Connection conn;
public Connection getConnction() throws Exception{
Class.forName(DRIVER);/*加载驱动*/
conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
return conn;
}
/*关闭数据库连接的方法*/
public void close(){
if(conn != null){
try{
this.conn.close();
}catch (SQLException e){
e.printStackTrace();
}
}
}
}
3.2 User实体类-JavaBean
User特征
- 有一个默认的无参构造函数
- 需要被序列化即实现Serializable接口
- 除userid属性只读外(本案例中userid由数据库自动生成)其余属性均可读写
- 所有属性均有getter和setter方法
User代码
package cn.lot.VO;
import java.io.Serializable;
public class User implements Serializable {
private int userid;
private String username;
private String address;
private String password;
private String sex;
private String email;
public User() {}
public User(int userid, String username, String address, String password, String sex, String email) {
this.userid = userid;
this.username = username;
this.password = password;
this.address = address;
this.sex = sex;
this.email = email;
}
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"userid=" + userid +
", username='" + username + '\'' +
", address='" + address + '\'' +
", password='" + password + '\'' +
", sex='" + sex + '\'' +
", email='" + email + '\'' +
'}';
}
}
3.3 UserDAO接口类
package cn.lot.DAO;
import cn.lot.VO.User;
public interface UserDAO {
/*通过用户名查找并返回用户信息*/
public User FindByName(String name)throws Exception;
/*更新用户信息*/
public boolean UpDateinfo(User user)throws Exception;
/*添加新用户*/
public boolean AddUser(User user)throws Exception;
}
3.4 UserDAOImpl实现类
package cn.lot.DAO;
import cn.lot.VO.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDAOImpl implements UserDAO {
private Connection conn;
private PreparedStatement pstmt;/*预编译 可以动态操作SQL语句*/
public UserDAOImpl(Connection conn){
this.conn = conn;
}
@Override
public User FindByName(String name)throws Exception{
User user = new User();
/*在Navicat for MySQL中新建查询写相关的SQL语句并执行,若成功则把语句赋值给sql并将=后面的条件换成?*/
String sql = "SELECT * FROM userinfo WHERE username = ?";
try {
this.pstmt = this.conn.prepareStatement(sql);/*执行sql语句*/
this.pstmt.setString(1,name);/*为sql语句中的第一个问号赋值*/
ResultSet rs = this.pstmt.executeQuery();/*将执行查询的结果存放在ResultSet的对象中*/
if(rs.next()){
/*将获得的属性传给新建的一个User对象*/
user.setUserid(rs.getInt(1));
user.setUsername(rs.getString(2));
user.setPassword(rs.getString(3));
user.setAddress(rs.getString(4));
user.setSex(rs.getString(5));
user.setEmail(rs.getString(6));
}else {
user = null;
System.out.println("user为空");
}
} catch (SQLException e) {
e.printStackTrace();
}
/*用完就要关闭PreparedStatement,释放内存*/
this.pstmt.close();
return user;
}
@Override
public boolean UpDateinfo(User user) throws Exception{
boolean flag = false;
String sql = "UPDATE userinfo SET username = ? ,password = ?,address = ?,sex = ?,email = ? WHERE userid = ?";
try {
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setString(1,user.getUsername());
this.pstmt.setString(2,user.getPassword());
this.pstmt.setString(3,user.getAddress());
this.pstmt.setString(4,user.getSex());
this.pstmt.setString(5,user.getEmail());
this.pstmt.setInt(6,user.getUserid());
if(this.pstmt.executeUpdate() > 0){
/*若执行了更新*/
flag = true;
}else {
System.out.println("更新失败");
}
} catch (SQLException e) {
e.printStackTrace();
}
this.pstmt.close();
return flag;
}
@Override
public boolean AddUser(User user) throws Exception{
boolean flag = false;
String sql = "INSERT INTO userinfo(username,password,address,sex,email)VALUES(?,?,?,?,?)";
try {
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setString(1,user.getUsername());
this.pstmt.setString(2,user.getPassword());
this.pstmt.setString(3,user.getAddress());
this.pstmt.setString(4,user.getSex());
this.pstmt.setString(5,user.getEmail());
if(this.pstmt.executeUpdate() > 0 ){
flag = true;
}else {
System.out.println("用户注册失败");
}
} catch (SQLException e) {
e.printStackTrace();
}
this.pstmt.close();
return flag;
}
}
3.5 UserDAOProxy代理类
package cn.lot.DAO;
import cn.lot.DB.MySQLConnection;
import cn.lot.VO.User;
public class UserDAOProxy implements UserDAO {
private MySQLConnection conn = null;
private UserDAO dao;
/*对数据库进行持久化操作*/
public UserDAOProxy()throws Exception{
this.conn = new MySQLConnection();
/*对DAO实现类进行实例化*/
this.dao = new UserDAOImpl(this.conn.getConnction());
}
@Override
public User FindByName(String name) throws Exception{
User user = new User();
try {
/*调用DAO实现类的同名方法*/
user = this.dao.FindByName(name);
} catch (Exception e) {
e.printStackTrace();
} finally {
/*操作完成后关掉连接*/
this.conn.close();
}
return user;
}
@Override
public boolean UpDateinfo(User user)throws Exception {
boolean flag = false;
try {
flag = this.dao.UpDateinfo(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
this.conn.close();
}
return flag;
}
@Override
public boolean AddUser(User user)throws Exception {
boolean flag = false;
try {
flag = this.dao.AddUser(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
this.conn.close();
}
return flag;
}
}
3.6 DAOFactiory工厂类
package cn.lot.FACTORY;
import cn.lot.DAO.UserDAO;
import cn.lot.DAO.UserDAOProxy;
public class DAOFactory {
/*UserDAO时抽象类 通过实现了接口的UserDAOProxy将其实例化*/
public static UserDAO getUserDAOInstance()throws Exception{
return new UserDAOProxy();
}
}
4.登录业务实现
4.1 loginServlet的实现
代码实现
package cn.lot.servlet;
import cn.lot.FACTORY.DAOFactory;
import cn.lot.VO.User;
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 {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
/*获取用户名和密码*/
String userName = request.getParameter("userName");
String userPassword = request.getParameter("userPassword");
/*错误信息*/
String errorMes;
try {
/* 通过用户名从数据库查找相关数据*/
User user = DAOFactory.getUserDAOInstance().FindByName(userName);
/*先判断user的name是否为空即该名字在数据库中不存在*/
if(user.getUsername() != null){
/* 判断输入的密码是否和数据库中该用户名的密码是一样的*/
if(userName.equals(user.getUsername()) && userPassword.equals(user.getPassword())){
//将用户信息传入session并跳转到success页面
request.getSession().setAttribute("user",user);
request.getRequestDispatcher("/success.jsp").forward(request, response);
}else{
errorMes = "您输入的密码有误!";
request.setAttribute("errorMes",errorMes);
//将密码错误信息带回login.jsp页面
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}else {
errorMes = "您输入的用户名不存在!";
request.setAttribute("errorMes",errorMes);
//将用户名错误信息带回login.jsp页面
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
·登陆成功
自定义标签
自定义标签实现步骤如下:
-
编写一个继承SimpleTagSupport的myout类
package cn.lot.myTaglib; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; public class myout extends SimpleTagSupport { private String value; //一定要有Setter方法 public void setValue(String value) { this.value = value; } @Override public void doTag() throws JspException, IOException { JspWriter writer = getJspContext().getOut(); writer.write(value); } }
-
在WEB-INF下新建tld文件并编辑(对标签处理类进行描述)
· tld新建如图所示:
· 编辑内容:
1.0
myshortname
http://mycompany.com
out
cn.lot.myTaglib.myout
empty
value
true
true
- 在jsp页面中用@taglib指令导入tld文件中的uri,即可使用
success.jsp实现
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入自定义标签--%>
<%@taglib prefix="my" uri="http://mycompany.com" %>
<%--导入标准库标签--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
登陆成功
<%--导入bootstrap的css样式--%>
<%--导入bootstrap的js--%>
<%--导入jquery--%>
效果图
·登陆失败
用户名错误提示页面
密码错误提示页面
5.修改业务实现
5.1 修改信息页面实现
updateinfo.jsp实现
- 用来修改信息
- 将修改的信息传给confirm.jsp
<%--加入下面两行(以后用Filter实现)不然JSP中用javabean传递会中文乱码--%>
<%@ page contentType="text/html;charset=GB2312" language="java" %>
<% request.setCharacterEncoding( "GB2312");%>
修改用户信息
用户信息修改
<%--导入bootstrap的js--%>
<%--导入jquery--%>
效果图
把密码从88888888改为11111111 地址从广东改到吉林
5.2 利用javaBean更新数据库实现
- 将获取到的信息通过jsp的useBean标签来获取名为userinfo的User对象(在loginServlet中将其存到了Session域里)
- 通过jsp的setProperty标签把从updateinfo.jsp获取到的与uerinfo属性名相对应的值重新赋给userinfo,因为该对象在session中,所以直接通过按钮跳转到ReturnServlet实现数据库的更新操作,并把更新好的userinfo重新放到session域里后跳转到succes.jsp
confirm.jsp实现
<%--加入下面两行(以后用Filter实现)不然JSP中用javabean传递会中文乱码--%>
<%@ page contentType="text/html;charset=GB2312" language="java" %>
<% request.setCharacterEncoding( "GB2312");%>
确认修改
<%--导入bootstrap的js--%>
<%--导入jquery--%>
ReturnServlet实现
package cn.lot.servlet;
import cn.lot.FACTORY.DAOFactory;
import cn.lot.VO.User;
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("/ReturnServlet")
public class ReturnServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
User user = (User)request.getSession().getAttribute("userinfo");
try {
Boolean flag = DAOFactory.getUserDAOInstance().UpDateinfo(user);
if(flag){
request.getSession().setAttribute("userinfo",user);
request.getRequestDispatcher("/success.jsp").forward(request, response);
}else {
System.out.println("更新失败了");
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
效果图
6.注册业务实现
6.1 注册用户页面实现
- 输入用户名时通过ajax(异步JavaScript 和 XML)实现不需要刷新来判断并提示用户名为空和数据库中是否已存在相同的名字
用ajax实现register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入标准库标签--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
注册页面
用户注册
<%--如果request域中获取的errorMes不为空则显示下列信息--%>
<%--Bootstrap的警告框 直接从官网复制代码修改即可--%>
出错啦!
效果图
用户名为空:
用户名可用:
用户名已存在:
6.2 AddUserServlet的实现
- 将获取到的信息赋值给一个user对象所对应的属性,存入session并跳转到success.jsp页面
代码实现
package cn.lot.servlet;
import cn.lot.FACTORY.DAOFactory;
import cn.lot.VO.User;
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.util.Map;
@WebServlet("/AddUserServlet")
public class AddUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
User user = new User();
//获取信息
String username = request.getParameter("username");
String password = request.getParameter("password");
String address = request.getParameter("address");
String sex = request.getParameter("sex");
String email = request.getParameter("email");
/*将信息存入新建的User对象中 这里可以更完善一下数据库并没有设置其他属性不能为空 所以如果不填信息也能保存进去*/
user.setUsername(username);
user.setPassword(password);
user.setAddress(address);
user.setSex(sex);
user.setEmail(email);
try {
Boolean flag = DAOFactory.getUserDAOInstance().AddUser(user);
if(flag){
request.getSession().setAttribute("userinfo",user);
request.getRequestDispatcher("/success.jsp").forward(request, response);
}else {
String msg = "注册失败啦!";
request.setAttribute("msg",msg);
request.getRequestDispatcher("/register.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
效果图
注册页面:
注册成功:
本人实力水平有限,很多地方有待改进,本次案例用到的都是课上所学,欢迎指出有误或着可以改进的地方。