案列需求:
在主测页面中输入用户数据,点击注册按钮完成用户注册
实现步骤:
1.创建数据库表,Mysql代码如下:
CREATE TABLE tb_user(
id int primary key auto_increment,
username VARCHAR(32),
password VARCHAR(32),
nickname varchar(32),
age int
);
2.创建web项目
添加有必要的jar,配置文件,工具类,JavaBean(user类)
创建自己的包
3.编写页面
4.编写服务器servlet
目录结构:
资源文件
dao层:
dao层接口:servletdao:
import ll.com.entity.tbuser;
import java.util.List;
public interface servletdao {
public boolean register(tbuser user);//注册的方法
public tbuser denglu1(tbuser user);//登录的方法
public List<tbuser> FindAll();//查询所有是数据
public boolean AddServlet(tbuser user);//添加的方法
boolean delete(int id);//根据id删除一个数据
public boolean update(tbuser user);//根据id修改数据
public int findTotal(); //查询总条数
List<tbuser> findPage(int i, int pageSize);
public tbuser findById(int id);//根据id查询数据
}
dao层实现类servletimpl
package ll.com.dao.impl;
import ll.com.dao.servletdao;
import ll.com.entity.tbuser;
import ll.com.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class servletimpl implements servletdao {
@Override
public boolean register(tbuser user) {
String sql="insert into tb_user values(null,?,?,?,?)";
boolean b = DBUtil.updateTable(sql, user.getUsername(), user.getPassword()
, user.getNickname(), user.getAge());
return b;
}
@Override
public tbuser denglu1(tbuser user) {
String sql="select * from tb_user where username=? and password=?";
List<tbuser> tbusers = DBUtil.queryTable(sql, tbuser.class,user.getUsername(),user.getPassword());
if(tbusers.size()>0){
return tbusers.get(0);
}
return null;
}
@Override
public List<tbuser> FindAll() {
String sql="select * from tb_user";
List<tbuser> tbusers = DBUtil.queryTable(sql, tbuser.class);
return tbusers;
}
@Override
public boolean AddServlet(tbuser user) {
String sql="insert into tb_user values(null,?,?,?,?)";
boolean b = DBUtil.updateTable(sql, user.getUsername(), user.getPassword()
, user.getNickname(), user.getAge());
return b;
}
@Override
public boolean delete(int id) {
String sql="delete from tb_user where id = ?";
boolean b = DBUtil.updateTable(sql, id);
return b;
}
@Override
public boolean update(tbuser user) {
String sql ="update tb_user set password = ?,nickname = ?,age = ? where id = ?";
boolean b = DBUtil.updateTable(sql,
user.getPassword(), user.getNickname(),
user.getAge(), user.getId());
return b;
}
@Override
public int findTotal() {
Connection connection = DBUtil.getConnection();
String sql="select count(*) from Tb_user";
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
int total=0;
while (resultSet.next()){
total = resultSet.getInt(1);
}
resultSet.close();
preparedStatement.close();
connection.close();
return total;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return 0;
}
@Override
public List<tbuser> findPage(int i, int pageSize) {
String sql="select * from tb_user limit ?,?";
List<tbuser> tbusers = DBUtil.queryTable(sql, tbuser.class, i, pageSize);
return tbusers;
}
@Override
public tbuser findById(int id) {
String sql="select * from tb_user where id = ?";
List<tbuser> userList = DBUtil.queryTable(sql, tbuser.class, id);
if(userList.size()>0){
return userList.get(0);
}
return null;
}
}
:实体类tbuser:
package ll.com.entity;
public class tbuser {
private int id;
private String username;
private String password;
private String nickname;
private int age;
public tbuser() {
}
public tbuser(int id, String username, String password, String nickname, int age) {
this.id = id;
this.username = username;
this.password = password;
this.nickname = nickname;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getNickname() {
return nickname;
}
public void setNickname(String nikname) {
this.nickname = nikname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "tbuser{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", nikname='" + nickname + '\'' +
", age='" + age + '\'' +
'}';
}
}
实体类PageBean:
package ll.com.entity;
import java.util.List;
public class PageBean<T> {
private int count;
private int totalPage;
private List<T> userList;
private int currentPage;
private int pageSize;
public PageBean() {
}
public PageBean(int count, int totalPage, List<T> userList, int currentPage, int pageSize) {
this.count = count;
this.totalPage = totalPage;
this.userList = userList;
this.currentPage = currentPage;
this.pageSize = pageSize;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<T> getUserList() {
return userList;
}
public void setUserList(List<T> userList) {
this.userList = userList;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
@Override
public String toString() {
return "PageBean{" +
"count=" + count +
", totalPage=" + totalPage +
", userList=" + userList +
", currentPage=" + currentPage +
", pageSize=" + pageSize +
'}';
}
}
过滤器filterServlet:
package ll.com.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/*")
public class filterServlet implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
String uri = request.getRequestURI();
if(uri.contains("zhuce.jsp") || uri.contains("denglu.jsp") || uri.contains("login") || uri.contains("checkCode")){
filterChain.doFilter(servletRequest,servletResponse);
}else{
HttpSession session = request.getSession();
Object username = session.getAttribute("username");
if(username != null){
filterChain.doFilter(servletRequest,servletResponse);
}else {
session.setAttribute("msg","请先登录");
request.getRequestDispatcher("/denglu.jsp").forward(request,servletResponse);
}
}
}
@Override
public void destroy() {
}
}
业务层Userservrceimpl:
package ll.com.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/*")
public class filterServlet implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
String uri = request.getRequestURI();
if(uri.contains("zhuce.jsp") || uri.contains("denglu.jsp") || uri.contains("login") || uri.contains("checkCode")){
filterChain.doFilter(servletRequest,servletResponse);
}else{
HttpSession session = request.getSession();
Object username = session.getAttribute("username");
if(username != null){
filterChain.doFilter(servletRequest,servletResponse);
}else {
session.setAttribute("msg","请先登录");
request.getRequestDispatcher("/denglu.jsp").forward(request,servletResponse);
}
}
}
@Override
public void destroy() {
}
}
业务层Userservrce:
package ll.com.servlce;
import ll.com.entity.PageBean;
import ll.com.entity.tbuser;
import java.util.List;
public interface Userservice {
public boolean register(tbuser user);//注册的方法
public tbuser denglu1(tbuser user);//登录的方法
public List<tbuser> FindAll();//查询所有是数据
public boolean AddServlet(tbuser user);//添加的方法
boolean delete(int id);//根据id删除一个数据
public boolean update(tbuser user);//根据id修改数据
//查询总条数
public tbuser findById(int id);//根据id查询数据
public PageBean findByPage(String page, String size);
}
工具类DButil:
package ll.com.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
//数据库工具类
public class DBUtil {
private static DataSource ds = null;
public static DataSource getDataSource(){
return ds;
}
//加载jdbc.properties配置文件,得到数据库连接的参数,加载驱动
static {
try {
//从jdbc.properties文件读取我们需要的参数
//1.创建出Properties对象
Properties properties = new Properties();
//2.打开读jdbc.properties文件的输入流(可以是字符流,也可以字节流)
InputStream reader = DBUtil.class.getClassLoader().getResourceAsStream("druid.properties");
//3.通过properties对象的load方法加载输入流--把jdbc.properties中内容读到properties中
properties.load(reader);
//4.DruidDataSourceFactory获得数据源对象
ds = DruidDataSourceFactory.createDataSource(properties);
//加载驱动
} catch (Exception e) {
e.printStackTrace();
}
}
//连接数据库
public static Connection getConnection(){
try {
//改成从数据库连接池获取连接
return ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//断开连接回收资源
public static void closeConnection(Connection conn){
try {
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//通用的表的 增删改操作
public static boolean updateTable(String sql ,Object... params){
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i+1,params[i]);
}
int number = pstmt.executeUpdate();
if(number>0){
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
closeConnection(conn);
}
return false;
}
//jdbc的封装可以用反射机制来封装,把从数据库中获取的数据封装到一个类的对象里
public static <T> List<T> queryTable(String sql, Class<T> cls, Object... params) {
List<T> list = new ArrayList<T>();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet resultSet = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
if (params != null && params.length>0) {
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i+1, params[i]);
}
}
resultSet = pstmt.executeQuery();
//封装数据:列名获得是关键
ResultSetMetaData metaData = resultSet.getMetaData();
int len = metaData.getColumnCount();//得到列的个数
while(resultSet.next()){
//获得参数中Class<T> cls对应的实体类的对象
T objectInstance = cls.newInstance();//实体的无参构造
for (int i = 0; i < len; i++) {
String column_name = metaData.getColumnName(i+1);
Object column_value = resultSet.getObject(column_name);
// System.out.println(column_name+"\t"+column_value);
//把属性名和值,与对应的实体类进行关联
Field field = cls.getDeclaredField(column_name);
field.setAccessible(true);
field.set(objectInstance, column_value);
}
list.add(objectInstance);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
closeConnection(conn);
}
return list;
}
//获得链接的方法
public static Connection getConnecttion(){
Connection connection = null;
try {
connection = ds.getConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
}
}
表面层AddServlet:
package ll.com.Web;
import ll.com.dao.servletdao;
import ll.com.entity.tbuser;
import ll.com.dao.impl.servletimpl;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;
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("/add")
public class AddServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String nickname = req.getParameter("nickname");
String age = req.getParameter("age");
tbuser user = new tbuser();
user.setUsername(username);
user.setPassword(password);
user.setNickname(nickname);
user.setAge(Integer.parseInt(age));
Userservice servletdao = new Userviceimpl();
boolean b = servletdao.AddServlet(user);
resp.sendRedirect(req.getContextPath()+"/FindByPage");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
表面层checkCodeservlet:
package ll.com.Web;
import cn.dsna.util.images.ValidateCode;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/checkCode")
public class checkCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ValidateCode validateCode = new ValidateCode(200,40,4,6);
String code = validateCode.getCode();//获取验证码
HttpSession session = req.getSession();//把验证码储存到session域里面
session.setAttribute("code",code);
//接受是否记住此次数据
String remember = req.getParameter("remember");
//把验证码以流的形式响应给客户
validateCode.write(resp.getOutputStream());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
表面层DeleteServlet:
package ll.com.Web;
import ll.com.dao.servletdao;
import ll.com.dao.impl.servletimpl;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;
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("/delete")
public class DeleteServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
//2.封装数据
//3.调用DAO层
Userservice userDao=new Userviceimpl();
boolean b = userDao.delete(Integer.parseInt(id));
//4.跳转资源
resp.sendRedirect(req.getContextPath()+"/FindByPage");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
表面层findAllServlet:
package ll.com.Web;
import ll.com.dao.servletdao;
import ll.com.dao.impl.servletimpl;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;
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("/delete")
public class DeleteServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
//2.封装数据
//3.调用DAO层
Userservice userDao=new Userviceimpl();
boolean b = userDao.delete(Integer.parseInt(id));
//4.跳转资源
resp.sendRedirect(req.getContextPath()+"/FindByPage");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
表面层FindByidServlet:
package ll.com.Web;
import ll.com.dao.servletdao;
import ll.com.entity.tbuser;
import ll.com.dao.impl.servletimpl;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;
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("/findById")
public class FindByIdServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.接受数据
String id = req.getParameter("id");
//2.封装数据
//3.调用DAO
Userservice userDao = new Userviceimpl();
tbuser user = userDao.findById(Integer.parseInt(id));
//4.资源跳转
req.setAttribute("user", user);
req.getRequestDispatcher("/update.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
表面层FindByPageServlet:
package ll.com.Web;
import ll.com.dao.servletdao;
import ll.com.entity.PageBean;
import ll.com.entity.tbuser;
import ll.com.dao.impl.servletimpl;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;
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("/FindByPage")
public class FindByPageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.接受数据
String Page = req.getParameter("currentPage");//当前页
String Size = req.getParameter("pageSize");//每页查多少
if(Page=="" || Page==null){
Page="1";
}
if(Size=="" || Size==null){
Size="2";
}
//2.封装数据
//3.调用业务层
Userservice servletdao = new Userviceimpl();
PageBean PageBean = servletdao.findByPage(Page, Size);
//4.资源跳转
req.setAttribute("pageBean",PageBean);
req.getRequestDispatcher("/listAdd.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
表面层LoginServlet:
package ll.com.Web;
import ll.com.dao.servletdao;
import ll.com.entity.tbuser;
import ll.com.dao.impl.servletimpl;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理中文乱码
req.setCharacterEncoding("utf-8");
//接收数据
String username = req.getParameter("username");
String password = req.getParameter("password");
//接受验证码
String code = req.getParameter("checkCode");
HttpSession session = req.getSession();
String code1 = (String) session.getAttribute("code");
//接受是否记住用户名的数据
String remember = req.getParameter("remember");
if(code1.equalsIgnoreCase(code)){
//1.校验成功,
//2.封装数据
tbuser user = new tbuser();
user.setUsername(username);
user.setPassword(password);
//调用DAO
Userservice dao = new Userviceimpl();
tbuser tbuser = dao.denglu1(user);
if(tbuser==null){
//重新登录:请求转发到登录的页面,同时携带提示消息
req.setAttribute("omg","账号或者密码有误");
req.getRequestDispatcher("/denglu.jsp").forward(req,resp);
}else{
if(remember !=null){
//把用户名存储到cookie
Cookie cookie = new Cookie("username",tbuser.getUsername());
//设置cookie存活时间
cookie.setMaxAge(60*60);
//设置cookie的作用范围
cookie.setPath(req.getContextPath());
//把cookie相应给游览器
resp.addCookie(cookie);
}else {
Cookie cookie = new Cookie("username",tbuser.getUsername());
//设置cookie存活时间
cookie.setMaxAge(0);
//设置cookie的作用范围
cookie.setPath(req.getContextPath());
//把cookie相应给游览器
resp.addCookie(cookie);
}
//登录成:重定向到一个查询所有数据的servlet/web/findAll
//登录成功后 把用户的信息储存到session中
session.setAttribute("username",username);
session.setAttribute("loginUser",tbuser);
resp.sendRedirect(req.getContextPath()+"/FindByPage");
}
}else {
session.setAttribute("msg","验证码错误");
req.getRequestDispatcher("/denglu.jsp").forward(req,resp);
}
}
}
表面层RegidterServlet:
package ll.com.Web;
import ll.com.entity.tbuser;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;
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("/register")
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收数据
req.setCharacterEncoding("utf-8");
String username=req.getParameter("username");
String password = req.getParameter("password");
String nickname = req.getParameter("nickname");
String age = req.getParameter("age");
//封装数据
tbuser user = new tbuser();
user.setUsername(username);
user.setPassword(password);
user.setNickname(nickname);
user.setAge(Integer.parseInt(age));
//调用工作成
Userservice userdao = new Userviceimpl();
boolean b = userdao.register(user);
if(b){
resp.sendRedirect(req.getContextPath()+"/denglu.jsp");
}else{
req.getRequestDispatcher("/zhuce.jsp").forward(req,resp);
}
}
}
表面层UpdateServlet:
package ll.com.Web;
import ll.com.dao.servletdao;
import ll.com.entity.tbuser;
import ll.com.dao.impl.servletimpl;
import ll.com.servlce.Userservice;
import ll.com.servlce.impl.Userviceimpl;
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("/update")
public class UpdateSrevlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String id = req.getParameter("id");
String password = req.getParameter("password");
String nickname = req.getParameter("nickname");
String age = req.getParameter("age");
//2.封装数据
tbuser user=new tbuser();
user.setId(Integer.parseInt(id));
user.setPassword(password);
user.setNickname(nickname);
user.setAge(Integer.parseInt(age));
//3.调用DAO
Userservice userDao=new Userviceimpl();
boolean b = userDao.update(user);
//4.资源跳转
resp.sendRedirect(req.getContextPath()+"/FindByPage");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
接下类就是处理我们前端的带代码:
前端Add.jsp:
<%--
Created by IntelliJ IDEA.
Date: 2024/9/11
Time: 11:17
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<style>
.one{
display: inline-block;
width: 45px;
height: 23px;
background-color: gainsboro;
color: black;
}
</style>
</head>
<body>
${sessionScope.username}
<div align="center">
<h1>添加页面</h1>
<form id="reg-form" action="${pageContext.request.contextPath}/add" method="post">
<table>
<tr>
<td>账号:</td>
<td>
<input name="username" type="text" id="username" onblur="checkusername">
<span id="username_err" class="err_msg" style="color: red; display: none">添加账号不正确</span>
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<input name="password" type="password" id="psd" onblur="checkpassword">
<span id="password_err" class="err_msg" style="color: red; display: none">密码输入有误</span>
</td>
</tr>
<tr>
<td>网名:</td>
<td>
<input name="nickname" type="text">
</td>
</tr>
<tr>
<td>年龄:</td>
<td>
<input name="age" type="text" id="age" onblur="checkage">
<span id="age_err" class="err_msg" style="color: red; display: none">年龄不符</span>
</td>
</tr>
</table>
<div>
<input value="添加" type="submit" id="reg_btn"/>
<a href="/web/FindByPage" class="one">返回</a>
</div>
</form>
<script>
function checkusername() {
let usernameValue = document.getElementById("username").value;
let reg = /^\w{10}$/;
if (reg.test(usernameValue)) {
document.getElementById("username_err").style.display = "none";
return true;
} else {
document.getElementById("username_err").style.display = "block";
return false;
}
}
function checkpassword() {
let passwordValue = document.getElementById("psd").value;
let reg = /^.{6,12}$/;
if (reg.test(passwordValue)) {
document.getElementById("password_err").style.display = "none";
return true;
} else {
document.getElementById("password_err").style.display = "block";
return false;
}
}
function checkage() {
let value = document.getElementById("age").value;
let num= parseInt(value);
if(num>=15 && num<=80){
document.getElementById("age_err").style.display = "none";
return true;
}else {
document.getElementById("age_err").style.display = "block";
return false;
}
}
document.getElementById("reg-form").onsubmit=function(){
//4.2 三个输入框只要有一个非法就阻止表单提交,都合法才能提交表单
return checkusername() && checkpassword() && checkage();
}
</script>
</div>
</body>
</html>
前端denglu.jsp:
<%--
Created by IntelliJ IDEA.
Date: 2024/9/10
Time: 10:08
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<style>
.one{
margin-top: 150px;
}
.one1{
display: inline-block;
width: 45px;
height: 23px;
background-color: gainsboro;
}
.one1>a{
color: black;
font-size: 14px;
}
.one1:hover{
width: 45px;
height: 23px;
background-color: azure;
}
</style>
</head>
<body>
<%
String username=null;
Cookie [] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie:cookies){
String name = cookie.getName();
if(name.equals("username")){
username=cookie.getValue();
}
}
}
if(username==null){
username="";
}
%>
<div align="center" class="one">
<h1>登录页面</h1>
<h4 style="color: red" >${requestScope.omg}</h4>
<h4 style="color: red">${sessionScope.msg}</h4>
<form action="${pageContext.request.contextPath}/login" method="post">
账号: <input type="text" name="username" value="<%=username%>"><br>
密码: <input type="password" name="password"><br>
验证码:<input type="text" name="checkCode"><br/>
<img src="/web/checkCode" id="img" onclick="checkcode()"><br/>
记住用户名:<input type="checkbox" name="remember"><br/>
<span>
<input type="submit" value="登录">
<span class="one1" border="black"><a href="/web/zhuce.jsp" class="four">注册</a></span>
</span>
</form>
<script>
function checkcode() {
let ing = document.getElementById("img");
img.src="/web/checkCode?time="+new Date().getTime();
}
</script>
</div>
</body>
</html>
前端listAdd.jsp:
<%--
Created by IntelliJ IDEA.
Date: 2024/9/10
Time: 17:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
<style>
a {
text-decoration: none;
}
.active{
color:red;
font-weight:bold;
}
</style>
</head>
<body>
欢迎:${sessionScope.username}
<table width="1000" align="center" border="1px">
<tr>
<td colspan="5" align="right">
<a href="${pageContext.request.contextPath}/Add.jsp" style="color: aqua" >添加数据</a>
</td>
</tr>
<tr>
<td>user.id</td>
<td>账号</td>
<td>昵称</td>
<td>年龄</td>
<td>操作</td>
</tr>
<c:forEach items="${requestScope.pageBean.userList}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.nickname}</td>
<td>${user.age}</td>
<td>
<a href="/web/findById?id=${user.id}">修改 |</a>
<a href="javascript:deleteById(${user.id})">删除</a>
</td>
</tr>
</c:forEach>
<tr>
<td colspan="5">
<%--如果是第一页则没有上一页 --%>
<c:if test="${requestScope.pageBean.currentPage>1}">
<a href="/web/FindByPage?currentPage=${requestScope.pageBean.currentPage-1}&
pageSize=${requestScope.pageBean.pageSize}">上一页</a>
</c:if>
<c:forEach begin="1" end="${requestScope.pageBean.totalPage}" var="i">
<%--如果是当前页 添加字体颜色样式 --%>
<c:if test="${i==requestScope.pageBean.currentPage}">
<a class="active" href="/web/FindByPage?currentPage=${i}&pageSize=${requestScope.pageBean.pageSize}">${i}</a>
</c:if>
<c:if test="${i!=requestScope.pageBean.currentPage}">
<a href="/web/FindByPage?currentPage=${i}&pageSize=${requestScope.pageBean.pageSize}">${i}</a>
</c:if>
</c:forEach>
<%--如果是最后一页则没有下一页 --%>
<c:if test="${requestScope.pageBean.currentPage!=requestScope.pageBean.totalPage}">
<a href="/web/FindByPage?currentPage=${requestScope.pageBean.currentPage+1}&
pageSize=${requestScope.pageBean.pageSize}">下一页</a>
</c:if>
总${requestScope.pageBean.totalPage}页
共${requestScope.pageBean.count}条
每页查${requestScope.pageBean.pageSize}条
</td>
</tr>
</table>
<script>
function deleteById(id) {
let b=window.confirm("你确定要删除吗?")
if(b){
location.href="http://localhost:8080/web/delete?id="+id;
}
}
</script>
</body>
</html>
前端update.jsp:
<%--
Created by IntelliJ IDEA.
Date: 2024/9/11
Time: 15:02
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<style>
.one{
display: inline-block;
width: 45px;
height: 23px;
background-color: gainsboro;
color: black;
}
</style>
</head>
<body>
<div align="center">
<h3>修改名为:${sessionScope.username}的账号</h3>
<form id="reg-form" action="${pageContext.request.contextPath}/update" method="post">
<input type="hidden" name="id" value="${requestScope.user.id}"/>
<div>
账号:<input name="username" type="text" id="username" onblur="checkusername" value="${requestScope.user.username} " readonly/>
</div>
<div>
密码:<input name="password" type="password" id="psd" onblur="checkpassword" value="${requestScope.user.password}"/>
</div>
<div>
网名:<input name="nickname" type="text" value="${requestScope.user.nickname}"/>
</div>
<div>
年龄:<input name="age" type="text" id="age" onblur="checkage" value="${requestScope.user.age}"/>
</div>
<div>
<input value="修改" type="submit" id="reg_btn">
<a href="/web/FindByPage" class="one">返回</a>
</div>
</form>
</div>
</body>
</html>
前端zhuce.jsp:
<%--
Created by IntelliJ IDEA.
User: 龙蕾
Date: 2024/9/9
Time: 14:15
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<style>
.one{
margin-top: 150px;
}
a{
text-decoration: none;
}
.two{
color: cornflowerblue;
}
.one1{
display: inline-block;
width: 45px;
height: 23px;
background-color: gainsboro;
}
.one1>a{
color: black;
font-size: 14px;
}
.one1:hover{
width: 45px;
height: 23px;
background-color: azure;
}
</style>
</head>
<body>
<div align="center" class="one">
<h1 class="two">注册页面</h1>
<form id="reg-form" action="${pageContext.request.contextPath}/register" method="post" class="five">
<table>
<tr>
<td>账号:</td>
<td>
<input name="username" type="text" id="username" onblur="checkusername">
<span id="username_err" class="err_msg" style="color: red; display: none">账号不正确</span>
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<input name="password" type="password" id="psd" onblur="checkpassword">
<span id="password_err" class="err_msg" style="color: red; display: none">密码输入有误</span>
</td>
</tr>
<tr>
<td>网名:</td>
<td>
<input name="nickname" type="text">
</td>
</tr>
<tr>
<td>年龄:</td>
<td>
<input name="age" type="text" id="age" onblur="checkage">
<span id="age_err" class="err_msg" style="color: red; display: none">年龄不符</span>
</td>
</tr>
</table>
<span >
<span> <input value="注 册" type="submit" id="reg_btn" class="three"></span>
<span class="one1" border="black"><a href="/web/denglu.jsp" class="four">登录</a></span>
</span>
</form>
</div>
<script>
function checkusername() {
let usernameValue = document.getElementById("username").value;
let reg = /^\w{10}$/;
if (reg.test(usernameValue)) {
document.getElementById("username_err").style.display = "none";
return true;
} else {
document.getElementById("username_err").style.display = "block";
return false;
}
}
function checkpassword() {
let passwordValue = document.getElementById("psd").value;
let reg = /^.{6,12}$/;
if (reg.test(passwordValue)) {
document.getElementById("password_err").style.display = "none";
return true;
} else {
document.getElementById("password_err").style.display = "block";
return false;
}
}
function checkage() {
let value = document.getElementById("age").value;
let num= parseInt(value);
if(num>=15 && num<=80){
document.getElementById("age_err").style.display = "none";
return true;
}else {
document.getElementById("age_err").style.display = "block";
return false;
}
}
document.getElementById("reg-form").onsubmit=function(){
//4.2 三个输入框只要有一个非法就阻止表单提交,都合法才能提交表单
return checkusername() && checkpassword() && checkage();
}
</script>
</body>
</html>