IDEA实现前端页面登录,注册增删改查操作-完整版
Posted 卷柏@*
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IDEA实现前端页面登录,注册增删改查操作-完整版相关的知识,希望对你有一定的参考价值。
分层思想: entity层:存放实体类 vo层:消息模型(重复使用的一些属性) mapper层:接口(写方法的) mapper.xml:MyBatis与数据库相关的一些内容 controller(web)层: 接收前端传回的参数 调用service层,返回结果 转发、响应结果(跳转页面) service层: 业务逻辑判断,写方法的. utils层: 工具类:写通用的方法、类。 test包: 测试类、测试方法(测试代码) MyBatis-config.xml: 连接数据库的
pom.xml: 导入相关依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hsd</groupId>
<artifactId>Servlet_Maven</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>Servlet_Maven Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson</groupId>
<artifactId>jackson-datatype-json-org</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<!--junit:封装类的jar包-->
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- 将配置文件复制到编译目录中-->
<resources>
<resource>
<!-- 所在的目录-->
<directory>src/main/java</directory>
<includes>
<!-- .xml和.properties结尾的文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
<finalName>Servlet_Maven</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
MyBatis-config.xml: 连接数据库
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--properties标签配置的整个文件都可使用,在任何位置配置的值都可以引入进来-->
<!--resource和url都可配置,但不能同时使用-->
<!--<properties resource="Mysql.properties"/>-->
<!-- <properties url="Mysql.properties"/>-->
<!--扫描实体类-->
<!-- <typeAliases>
<package name="com.hsd.entity"/>
<!–<typeAliases alias="User" type="com.hsd.entity.User"/>–>
</typeAliases>-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!--我的数据库:h2022-->
<property name="url" value="jdbc:mysql:///h2022?useSSL=false&useServerPrepStmts=true"/>
<!--我的数据库的名称和密码-->
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--mapper映射器-->
<mappers>
<!--1.映射文件一个一个扫描-->
<!--<mapper resource="com.hsd.mapper.UserMapper"/>
<mapper class="com.hsd.mapper.UserMapper"/>-->
<!--2.扫描mapper,自动扫描mapper中的接口和xml-->
<package name="com.hsd.mapper"/>
</mappers>
</configuration>
utils层: GetSessionUtil类:
package com.hsd.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class GetSessionUtil
public static SqlSession SqlSession()
InputStream inputStream=null;
SqlSessionFactory sqlSessionFactory=null;
SqlSession sqlSession=null;
//获取MyBatis的配置文件
try
String resources="MyBatis-config.xml";
//通过输入流拿到MyBatis-config.xml的配置文件
inputStream=Resources.getResourceAsStream(resources);
//MyBatis通过读取配置文件信息,构造出sqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取sqlSession
sqlSession=sqlSessionFactory.openSession();
return sqlSession;
catch (IOException e)
e.printStackTrace();
return null;
//测试配置环境无问题
public static void main(String[] args)
System.out.println(SqlSession());
test包: UserTest类:
package com.hsd.test;
import com.hsd.entity.User;
import com.hsd.mapper.UserMapper;
import com.hsd.utils.GetSessionUtil;
import org.apache.ibatis.session.SqlSession;
public class UserTest
public static void main(String[] args)
//获取sqlSession
SqlSession sqlSession= GetSessionUtil.SqlSession();
//获取mapper
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
//调用mapper的方法
User user = mapper.selectByUsername("aaa");
//
System.out.println(user);
登录: 1.数据库建表user 2.前端页面:user.jsp 登录表单: (1)form表单,创建账号和密码的输入框 (2)将登陆按钮绑定点击事件 (3)获取用户名和密码的值 (4)判断账号是否为空 若为空,就提示“账号不能为空”(赋值给span标签)并return返回 (5)判断密码是否为空 若为空,就提示“密码不能为空”(赋值给span标签)并return返回 (6)若都不为空,提交表单,跳转到后端 3.后端代码: (1)接收客户端请求(账号、密码) (2)调用service中的登录方法 (3)判断账号是否存在 若账号不存在,就提示“用户账号不存在”,返回到登录页面继续登录。 (4)判断密码是否有误 若密码有误,就提示“用户密码有误”,返回到登录页面继续登录。 (5)若都没问题就跳转到首页 controller层:(接收请求、响应结果) 1、接收客户端请求(账号、密码) 2、调用service中的登录方法 3、判断是否登录成功,成功的话跳转到首页,失败的话继续登录 service层:(业务逻辑) 1、创建消息模型对象(状态、提示信息、回显数据) 2、判断账号是否存在 若账号不存在,就提示“用户账号不存在”,回显数据到消息模型对象中,返回消息模型对 象 3、判断密码是否有误 若密码有误,就提示“用户密码有误”,回显数据到消息模型对象中,返回消息模型对象 4、若无问题就将用户信息放到消息模型中 mapper层: mapper接口:定义对应的接口 mapper.xml:写对应的sql语句 entity层: vo层:消息模型(重复使用的一些属性,写在MessageModel类中) student.jsp:首页
1.数据库建表user
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(20),
PASSWORD VARCHAR(20)
);
INSERT INTO USER(username,PASSWORD)VALUE
('admin','123');
entity层:User类
package com.hsd.entity;
public class User
private int id;
private String username;
private String password;
public User()
public User(int id, String username, String password)
this.id = id;
this.username = username;
this.password = password;
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;
@Override
public String toString()
return "User" +
"id=" + id +
", username='" + username + '\\'' +
", password='" + password + '\\'' +
'';
entity层:Student类
package com.hsd.entity;
//学生实体类
public class Student
private int id;//编号
private String name;//姓名
private int age;//年龄
private String sex;//性别
private String hobby;//爱好
private String time;//日期
public Student()
public Student(int id, String name, int age, String sex, String hobby, String time)
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
this.hobby = hobby;
this.time = time;
public int getId()
return id;
public void setId(int id)
this.id = id;
public String getName()
return name;
public void setName(String name)
this.name = name;
public int getAge()
return age;
public void setAge(int age)
this.age = age;
public String getSex()
return sex;
public void setSex(String sex)
this.sex = sex;
public String getHobby()
return hobby;
public void setHobby(String hobby)
this.hobby = hobby;
public String getTime()
return time;
public void setTime(String time)
this.time = time;
@Override
public String toString()
return "Student" +
"id=" + id +
", name='" + name + '\\'' +
", age=" + age +
", sex='" + sex + '\\'' +
", hobby='" + hobby + '\\'' +
", time='" + time + '\\'' +
'';
2.前端页面:user.jsp
<%--
Created by IntelliJ IDEA.
User: 30868
Date: 2022/10/27
Time: 16:55
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<div style="text-align: center">
<h1>登录页面</h1>
<form action="UserServlet" method="get" id="userForm">
账号:<input type="text" name="username" id="username" value="$messageModel.object.username"><br>
密码:<input type="password" name="password" id="password" value="$messageModel.object.password"><br>
<div style="color: red" id="div">$messageModel.msg</div><br>
<button type="button" id="but">登录</button>
<button type="button"><a href="register.jsp" style="text-decoration: none">注册</a></button>
</form>
</div>
</body>
<%--加载jquery-3.4.1.js插件--%>
<script src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
<%--通过id选择器,给登录按钮绑定一个点击事件--%>
$("#but").click(function ()
//通过id选择器获取账号和密码
var username=$("#username").val();
var password=$("#password").val();
//判断用户名和密码是否为空,若为空返回true,不为空返回false
function isEmpty(str)
if(str==null||str.trim()=="")
return true;
return false;
//判断账号是否为空
if(isEmpty(username))
//若账号为空,提示并返回:
$("#div").html("账号不能为空!")
return;
if(isEmpty(password))
/* //若密码为空,提示并返回:*/
$("#div").html("密码不能为空!")
return;
$("#userForm").submit()
);
</script>
</html>
相关的MessageModel类:entity层:-->vo层-->消息模型:写入重复使用的一些属性。
package com.hsd.entity.vo;
public class MessageModel
private int code=1;//状态码(1:成功。0:失败。默认为1)
private String msg="成功";//提示信息(成功和失败,默认成功,失败提示错误信息)
private Object object;//回显对象(基本数据类型、引用数据类型、数组、集合)
public MessageModel()
public MessageModel(int code, String msg, Object object)
this.code = code;
this.msg = msg;
this.object = object;
public int getCode()
return code;
public void setCode(int code)
this.code = code;
public String getMsg()
return msg;
public void setMsg(String msg)
this.msg = msg;
public Object getObject()
return object;
public void setObject(Object object)
this.object = object;
3.后端代码:controller层:UserServlet类
package com.hsd.controller;
import com.hsd.entity.vo.MessageModel;
import com.hsd.service.UserService;
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;
/*controller层:(接收请求、响应结果)
1、接收客户端请求(账号、密码)
2、调用service中的登录方法
3、判断是否登录成功,成功的话跳转到首页,失败的话继续登录*/
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
//获取UserService对象
UserService userService=new UserService();
// 1、接收客户端请求(账号、密码)
String username=req.getParameter("username");
String password=req.getParameter("password");
//2、调用service中的登录方法
MessageModel messageModel=userService.selectByUsername(username,password);
//3、判断是否登录成功,成功的话跳转到首页,失败的话继续登录
if(messageModel.getCode()==1)
//成功,将消息模型存到req中,并重定向到首页
//转发(req)
req.getSession().setAttribute("messageModel",messageModel);
//重定向(resp)
//路径不加‘/’
resp.sendRedirect("StudentServlet");
else
//失败,将消息模型存到req中,并转发到登录页面
req.setAttribute("messageModel",messageModel);
//路径加‘/’
req.getRequestDispatcher("/user.jsp").forward(req,resp);
service层:UserService类
package com.hsd.service;
import com.hsd.entity.User;
import com.hsd.entity.vo.MessageModel;
import com.hsd.mapper.UserMapper;
import com.hsd.utils.GetSessionUtil;
import org.apache.ibatis.session.SqlSession;
/*1、创建消息模型对象(状态、提示信息、回显数据)
2、判断账号是否存在
若账号不存在,就提示“用户账号不存在”,回显数据到消息模型对象中,返回消息模型对象
3、判断密码是否有误
若密码有误,就提示“用户密码有误”,回显数据到消息模型对象中,返回消息模型对象
4、若无问题就将用户信息放到消息模型中*/
public class UserService
public MessageModel selectByUsername(String username, String password)
//1、创建消息模型对象(状态、提示信息、回显数据)
MessageModel messageModel=new MessageModel();
//回显数据,当账号和密码输入错误时,不会自动清空账号和密码,仍保留。
User u=new User();
u.setUsername(username);
u.setPassword(password);
//将回显的数据放在回显对象中
messageModel.setObject(u);
//获取sqlSession对象
SqlSession sqlSession= GetSessionUtil.SqlSession();
//调用UserMapper的登录方法
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
User user=mapper.selectByUsername(username);
//2、判断账号是否存在
if(user==null)
//若账号不存在,就提示“用户账号不存在”,回显数据到消息模型对象中,返回消息模型对象
messageModel.setCode(0);//修改状态为0
messageModel.setMsg("该账号不存在");
return messageModel;
//3、判断密码是否有误
if(!password.equals(user.getPassword()))
messageModel.setCode(0);//修改状态为0
messageModel.setMsg("密码有误");
return messageModel;
//4、若无问题就将用户信息放到消息模型中
messageModel.setObject(user);
//释放资源
sqlSession.close();
return messageModel;
/*service层:(业务逻辑)
1、创建消息模型对象(状态、提示信息、回显数据)
2、判断账号是否存在
若账号存在,就提示“用户账号已存在不能注册”,回显数据到消息模型对象中,返回消息模型对象
3、若无问题就将用户信息放到消息模型中*/
public MessageModel Register(User user)
// 1、创建消息模型对象(状态、提示信息、回显数据)
MessageModel messageModel = new MessageModel();
//回显数据
User u = new User();
u.setUsername(user.getUsername());
u.setPassword(user.getPassword());
//将回显的数据存到数据模型中
messageModel.setObject(u);
//获取sqlSession
SqlSession sqlSession = GetSessionUtil.SqlSession();
//获取mapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用mapper中查找用户名的方法
User user1 = mapper.selectByUsername(user.getUsername());
//2、判断账号是否存在
if(user1!=null)
//若账号存在,就提示“用户账号已存在不能注册”,
messageModel.setCode(0);//消息模型的状态修改为0
messageModel.setMsg("该账号已存在不能注册");//提示信息
return messageModel;//将错误的信息返回给messageModel
//不存在,3、若无问题就将用户信息放到消息模型中
//调用mapper中的注册方法
mapper.Register(user);
messageModel.setObject(user);
//提交事务:添加时需要提交,查询时不需要提交
//将数据放到数据库时,需要提交事务;从数据库中取出数据时,不需要提交事务
sqlSession.commit();
return messageModel;
//释放资源
mapper层:UserMapper
package com.hsd.mapper;
import com.hsd.entity.User;
import org.apache.ibatis.annotations.Select;
public interface UserMapper
//@Select("select * from user")
User selectByUsername(String name);
void Register(User user);
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace:命名空间,对应Mapper接口的路径-->
<mapper namespace="com.hsd.mapper.UserMapper">
<!--id(必写)对应Mapper接口中的方法名称,parameterType:接口中的方法的参数类型,resultType:实体类-->
<select id="selectByUsername" parameterType="String" resultType="com.hsd.entity.User">
select * from user where username=#username;
</select>
<insert id="Register">
insert into user value (null,#username,#password);
</insert>
</mapper>
设置xml:File-->Settings-->Editor-->Code Style-->File and Code Templates:点击'+'号,设置:Name:Mapper,Extension:xml-->Apply-->OK
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="">
</mapper>
注册:
1.前端页面register.jsp 注册表单:
(1)form表单,账号、密码、重复密码和注册的按钮
(2)将注册按钮绑定点击事件
(3)获取账号、密码、重复密码的值
(4)判断账号是否为空 若为空,就提示“账号不能为空”(赋值给div标签)并return返回 (5)判断密码是否为空 若为空,就提示“密码不能为空”(赋值给div标签)并return返回 (6)判断重复密码是否为空 若为空,就提示“重复密码不能为空”(赋值给div标签)并return返回
(7)判断密码和重复密码是否一致
(8)判断密码长度是否符合要求(>3&&<6)
(9)提交表单
2.后端代码:
(1)接收客户端请求(账号、密码)
(2)把接收的数据封装到实体类
(3)调用service中的注册方法
(4)判断账号是否存在 若账号存在,就提示“用户账号已存在不能注册”,返回到注册页面继续注册。
(5)若该账号不存在,就跳转到登录页面
controller层:(接收请求、响应结果)
1、接收客户端请求(账号、密码)
2、把接收的数据封装到实体类
3、调用service中的注册方法
4、判断是否注册成功,成功的话跳转到登录页面,失败的话继续注册
service层:(业务逻辑)
1、创建消息模型对象(状态、提示信息、回显数据)
2、判断账号是否存在 若账号存在,就提示“用户账号已存在不能注册”,回显数据到消息模型对象中,返回消息模型对象
3、若无问题就将用户信息放到消息模型中
mapper层:
1、mapper接口:定义对应的接口
2、mapper.xml:写对应的sql语句
1.前端页面register.jsp:
里面用到了jQuery:
jQuery 是一个 JavaScript 库,里面存在大量的JavaScript函数
jQuery 极大地简化了 JavaScript 编程
jQuery 的获取:官网
https://jquery.com/
<%--
Created by IntelliJ IDEA.
User: 30868
Date: 2022/10/28
Time: 10:30
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<span style="text-align: center">
<h1>注册页面</h1>
<form action="RegisterServlet" method="get" id="registerForm">
账号:<input type="text" name="username" id="username" value="$messageModel.object.username"><br>
密码:<input type="password" name="password" id="password" value="$messageModel.object.password"><br>
重复密码:<input type="password" name="password2" id="password2"><br>
<div style="color: red" id="div">$messageModel.msg</div><br>
<button type="button" id="but">注册</button>
<button type="button"><a href="user.jsp" style="text-decoration: none">登录</a></button>
</form>
</span>
</body>
<script src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
/*通过id选择器获取注册的按钮,给注册按钮绑定点击事件*/
$("#but").click(function ()
//获取账号、密码、重复密码的值
var username=$("#username").val();
var password=$("#password").val();
var password2=$("#password2").val();
//判断是否为空
function isEmpty(str)
if(str==null||str.trim()=="")
return true;
return false;
if(isEmpty(username))
$("#div").html("账号不能为空")
return;
if(isEmpty(password))
$("#div").html("密码不能为空")
return;
if(isEmpty(password2))
$("#div").html("重复密码不能为空")
return;
//判断密码和重复密码是否一致
if(password!=password2)
$("#div").html("密码不一致")
return;
//判断密码长度是否符合要求(>3&&<6)
if(username.length<3||username.length>6)
$("#div").html("账号长度不能小于3位,也不能大于6位")
return;
//提交表单
$("#registerForm").submit();
);
</script>
</html>
2.后端代码:controller层:RegisterServlet类:
package com.hsd.controller;
import com.hsd.entity.User;
import com.hsd.entity.vo.MessageModel;
import com.hsd.service.UserService;
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("/RegisterServlet")
public class RegisterServlet extends HttpServlet
@Override
/*controller层:(接收请求、响应结果)
1、接收客户端请求(账号、密码)
2、把接收的数据封装到实体类
3、调用service中的注册方法
4、判断是否注册成功,成功的话跳转到登录页面,失败的话继续注册*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
//获取userService对象
UserService userService = new UserService();
// 1、接收客户端请求(账号、密码)
String username=req.getParameter("username");
String password=req.getParameter("password");
//2、把接收的数据封装到实体类
User user=new User();
user.setUsername(username);
user.setPassword(password);
//3、调用service中的注册方法
MessageModel messageModel=userService.Register(user);
//4、判断是否注册成功,成功的话跳转到登录页面,失败的话继续注册
if(messageModel.getCode()==1)
//成功,将消息模型存到req中,并重定向到登录页面
req.setAttribute("messageModel",messageModel);
resp.sendRedirect("user.jsp");
else
//失败,将消息模型存到req中,并转发到注册页面
req.setAttribute("messageModel",messageModel);
req.getRequestDispatcher("/register.jsp").forward(req,resp);
student.jsp:首页
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: 30868
Date: 2022/10/28
Time: 8:44
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>展示页面</title>
</head>
<body>
<center>
<h1>展示页面</h1>
<h2>欢迎$messageModel.object.username登录成功!</h2>
<a href="add.jsp">添加</a>
<table border="1px" cellspacing="0">
<tr>
<%--th:加粗居中--%>
<th>选项</th>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>爱好</th>
<th>日期</th>
<th>操作</th>
</tr>
<%--c:forEach :循环--%>
<c:forEach items="$list" var="l">
<tr>
<td>
<input type="checkbox" name="option" value="$l.id">
</td>
<td>$l.id</td>
<td>$l.name</td>
<td>$l.age</td>
<td>
<c:if test="$l.sex==1">
男
</c:if>
<c:if test="$l.sex!=1">
女
</c:if>
</td>
<td>$l.hobby</td>
<td>$l.time</td>
<td>
<%--修改根据id--%>
<a href="selectByIdServlet?id=$l.id">修改</a>
<%--删除根据id--%>
<a href="deleteByIdServlet?id=$l.id">删除</a>
</td>
</tr>
</c:forEach>
</table>
<input type="submit" value="全选" onclick="checkAll()">
<input type="submit" value="全不选" onclick="checkNoAll()">
</center>
</body>
<script type="text/javascript">
/*在js中获取点击框*/
var option=document.getElementsByName("option");
//全选
function checkAll()
for (let i = 0; i < option.length; i++)
option[i].checked=true;
function checkNoAll()
for (let i = 0; i < option.length; i++)
option[i].checked=false;
</script>
</html>
StudentServlet类:
package com.hsd.controller;
import com.hsd.entity.Student;
import com.hsd.service.StudentService;
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.List;
@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
//获取StudentService对象
StudentService studentService = new StudentService();
//调用Service层的selectAll方法
List<Student> list=studentService.selectAll();
//将拿到的数据存到req域中
req.setAttribute("list",list);
//转发到student.jsp展示页面
req.getRequestDispatcher("/student.jsp").forward(req,resp);
service层:StudentService类:
package com.hsd.service;
import com.hsd.entity.Student;
import com.hsd.mapper.StudentMapper;
import com.hsd.utils.GetSessionUtil;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class StudentService
//获取工具类中的SqlSession对象
SqlSession sqlSession= GetSessionUtil.SqlSession();
//获取Mapper
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
public List<Student> selectAll()
//获取mapper接口中查看所有的方法
List<Student> list=mapper.selectAll();
//释放资源
sqlSession.close();
//返回到Servlet
return list;
public void addServlet(Student student)
//获取mapper中添加的方法
mapper.addServlet(student);
//提交事务
sqlSession.commit();
//释放资源
sqlSession.close();
public void deleteById(int id)
//获取mapper中删除的方法
mapper.deleteById(id);
//提交事务
sqlSession.commit();
sqlSession.close();
public Student selectById(int id)
//获取mapper中根据id查找的方法
Student student=mapper.selectById(id);
sqlSession.close();
return student;
public void update(Student student)
//获取mapper中的修改方法
mapper.update(student);
//提交事务
sqlSession.commit();
sqlSession.close();
mapper层:
package com.hsd.mapper;
import com.hsd.entity.Student;
import java.util.List;
public interface StudentMapper
//查看所有
List<Student> selectAll();
void addServlet(Student student);
void deleteById(int id);
Student selectById(int id);
void update(Student student);
StudentMapper.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hsd.mapper.StudentMapper">
<select id="selectAll" resultType="com.hsd.entity.Student">
select * from student;
</select>
<insert id="addServlet">
insert into student value (null,#name,#age,#sex,#hobby,#time);
</insert>
<delete id="deleteById">
delete from student where id=#id;
</delete>
<select id="selectById" resultType="com.hsd.entity.Student">
select * from student where id=#id;
</select>
<update id="update">
update student set name=#name,age=#age,sex=#sex,hobby=#hobby,time=#time where id=#id;
</update>
</mapper>
添加: 1.前端页面add.jsp 2.后端代码: (1)接收客户端请求(添加的数据) (2)把接收的数据封装到实体类 (3)调用service中的添加方法 (4)添加完毕后返回首页。 controller层:(接收请求、响应结果) 1、接收客户端请求(添加的数据) 2、把接收的数据封装到实体类 3、调用service中的添加方法 4、添加成功的话跳转到首页 service层:(业务逻辑) 1、获取工具类中的SqlSession对象 2、获取Mapper 3、获取mapper中添加的方法 mapper层: mapper接口:定义对应的接口 mapper.xml:写对应的sql语句
1.前端页面add.jsp:
<%--
Created by IntelliJ IDEA.
User: 30868
Date: 2022/10/29
Time: 8:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加页面</title>
</head>
<body>
<form action="AddServlet" method="get">
姓名:<input type="text" name="name"><br>
年龄:<input type="text" name="age"><br>
性别:<input type="radio" name="sex" value="1">男
<input type="radio" name="sex" value="0">女<br>
爱好:<input type="checkbox" name="hobby" value="吃">吃
<input type="checkbox" name="hobby" value="喝">喝
<input type="checkbox" name="hobby" value="玩">玩
<input type="checkbox" name="hobby" value="乐">乐<br>
日期:<input type="date" name="time"><br>
<input type="reset" value="重置"><br>
<input type="submit" value="添加"><br>
</form>
</body>
</html>
controller层:AddServlet类:
package com.hsd.controller;
import com.hsd.entity.Student;
import com.hsd.service.StudentService;
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.Arrays;
@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
//获取StudentService
StudentService studentService = new StudentService();
String name=req.getParameter("name");
String age=req.getParameter("age");
String sex=req.getParameter("sex");
//多选框实现添加用数组
String[] hobby=req.getParameterValues("hobby");
String time=req.getParameter("time");
//将获取到的数据封装到对应的实体类中
//Student student = new Student(Integer.parseInt(null),name,Integer.parseInt(age),sex,hobby,time);
Student student = new Student();
student.setName(name);
student.setAge(Integer.parseInt(age));
student.setSex(sex);
student.setHobby(Arrays.toString(hobby));
student.setTime(time);
//调用StudentService中的添加方法,将添加的数据传回去,添加不需要返回值
studentService.addServlet(student);
//转发到首页
req.getRequestDispatcher("StudentServlet").forward(req,resp);
service层:在StudentService中写入添加方法。mapper层:在StudentMapper中写入添加方法,在StudentMapper.xml中写入添加的sql语句。
删除: 后端代码: (1)创建studentService对象 (2)接收客户端请求(根据id删除) (3)删除后返回首页 controller层:(接收请求、响应结果) 1、接收客户端请求(根据id删除) 2、调用service中的删除方法 3、删除成功的话跳转到首页 service层:(业务逻辑) 1、获取工具类中的SqlSession对象 2、获取Mapper 3、获取mapper中删除的方法 mapper层: mapper接口:定义对应的接口 mapper.xml:写对应的sql语句
deleteByIdServlet类:
package com.hsd.controller;
import com.hsd.service.StudentService;
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("/deleteByIdServlet")
public class deleteByIdServlet extends HttpServlet
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
//创建studentService对象
StudentService studentService = new StudentService();
//获取id,根据id删除
String id=req.getParameter("id");
//删除不需要返回值
studentService.deleteById(Integer.parseInt(id));
//删除后返回首页
req.getRequestDispatcher("StudentServlet").forward(req,resp);
service层:在StudentService中写入根据id查找和删除的方法。
mapper层:在StudentMapper中写入根据id查找的方法和删除的方法,在StudentMapper.xml中写入根据id查找和删除的sql语句。
修改: 1.前端页面update.jsp: 进行数据回显 2.后端代码: 获取要修改的数据: (1)获取studentService类中的获取id的方法 (2)将数据存到req域中,通过setAttribute发送给回显页面,方便回显数据 (3)若找到数据,跳转到修改页面,进行回显 对获取的数据进行修改 (1)接收修改后的数据 (2)把修改后的数据封装到实体类student中 (3)调用studentService类中的修改方法 (4)修改后跳转到主页面 controller层:(接收请求、响应结果) 1、接收客户端请求(根据id修改) 2、调用service中的修改方法 3、修改成功的话跳转到首页 service层:(业务逻辑) 1、获取工具类中的SqlSession对象 2、获取Mapper 3、获取mapper中修改的方法 mapper层: mapper接口:定义对应的接口 mapper.xml:写对应的sql语句
1.前端页面update.jsp:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%--
Created by IntelliJ IDEA.
User: 30868
Date: 2022/10/29
Time: 14:37
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>修改页面</title>
</head>
<body>
<form action="UpdateServlet" method="get">
编号:<input type="text" name="id" value="$s.id"><br>
姓名:<input type="text" name="name" value="$s.name"><br>
年龄:<input type="text" name="age" value="$s.age"><br>
性别:<input type="radio" name="sex" value="1" <c:if test="$s.sex==1"></c:if> checked="checked">男
<input type="radio" name="sex" value="0" <c:if test="$s.sex==0"></c:if> checked="checked">女<br>
爱好:<input type="checkbox" name="hobby" value="吃" <c:if test="$fn:contains(s.hobby,'吃' )">checked="checked"</c:if>>吃
<input type="checkbox" name="hobby" value="喝" <c:if test="$fn:contains(s.hobby,'喝' )">checked="checked"</c:if>>喝
<input type="checkbox" name="hobby" value="玩" <c:if test="$fn:contains(s.hobby,'玩' )">checked="checked"</c:if>>玩
<input type="checkbox" name="hobby" value="乐" <c:if test="$fn:contains(s.hobby,'乐' )">checked="checked"</c:if>>乐<br>
日期:<input type="date" name="time" value="$s.time"><br>
<input type="reset" value="重置"><br>
<input type="submit" value="修改"><br>
</form>
</body>
</html>
2.后端代码:controller层:selectByIdServlet类:修改时,先根据id回显。
package com.hsd.controller;
import com.hsd.entity.Student;
import com.hsd.service.StudentService;
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("/selectByIdServlet")
public class selectByIdServlet extends HttpServlet
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
//获取studentService对象
StudentService studentService = new StudentService();
//获取id
String id = req.getParameter("id");
//获取studentService类中的获取id的方法
Student student=studentService.selectById(Integer.parseInt(id));
//将数据存到req域中,通过setAttribute发送给回显页面,方便回显数据
req.setAttribute("s",student);
//若找到数据,跳转到修改页面,进行回显
req.getRequestDispatcher("update.jsp").forward(req,resp);
UpdateServlet类:
package com.hsd.controller;
import com.hsd.entity.Student;
import com.hsd.service.StudentService;
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.Arrays;
@WebServlet("/UpdateServlet")
public class UpdateServlet extends HttpServlet
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
//获取studentService对象
StudentService studentService = new StudentService();
//接收修改后的数据
String id = req.getParameter("id");
String name = req.getParameter("name");
String age = req.getParameter("age");
String sex = req.getParameter("sex");
//多选框用数组类型接收数据
String[] hobby = req.getParameterValues("hobby");
String time = req.getParameter("time");
//把修改后的数据封装到实体类student中
Student student = new Student();
student.setId(Integer.parseInt(id));
student.setName(name);
student.setAge(Integer.parseInt(age));
student.setSex(sex);
//将数组类型转换为String
student.setHobby(Arrays.toString(hobby));
student.setTime(time);
//调用studentService类中的修改方法,修改不需要返回值
studentService.update(student);
//修改后跳转到主页面
req.getRequestDispatcher("StudentServlet").forward(req,resp);
service层:在StudentService中写入根据id修改的方法。
mapper层:在StudentMapper中写入根据id修改的方法,在StudentMapper.xml中写入根据id修改的sql语句。
页面效果:
功能完善
1、选中删除功能
2、根据姓名查询功能
3、根据年龄区间查询功能
:student.jsp页面:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: 30868
Date: 2022/10/28
Time: 8:44
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>展示页面</title>
</head>
<body>
<center>
<h1>展示页面</h1>
<h2>欢迎$messageModel.object.username登录成功!</h2>
<a href="add.jsp">添加</a>
<form action="SelectByNameServlet" method="get">
根据姓名查询:<input type="text" name="name" value="$s.name">
<input type="submit" value="查询">
</form>
<form action="SelectByAgeServlet" method="get">
根据年龄区间查询:<input type="text" name="age1" value="$s.age1">---<input type="text" name="age2" value="$s.age2">
<input type="submit" value="查询">
</form>
<table border="1px" cellspacing="0">
<tr>
<%--th:加粗居中--%>
<th>选项</th>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>爱好</th>
<th>日期</th>
<th>操作</th>
</tr>
<%--c:forEach :循环--%>
<c:forEach items="$list" var="l">
<tr>
<td>
<input type="checkbox" name="option" value="$l.id">
</td>
<td>$l.id</td>
<td>$l.name</td>
<td>$l.age</td>
<td>
<c:if test="$l.sex==1">
男
</c:if>
<c:if test="$l.sex!=1">
女
</c:if>
</td>
<td>$l.hobby</td>
<td>$l.time</td>
<td>
<%--修改根据id--%>
<a href="selectByIdServlet?id=$l.id">修改</a>
<%--删除根据id--%>
<a href="deleteByIdServlet?id=$l.id">删除</a>
</td>
</tr>
</c:forEach>
</table>
<input type="submit" value="全选" onclick="checkAll()">
<input type="submit" value="全不选" onclick="checkNoAll()">
<input type="submit" value="选中删除" onclick="XDelete()">
</center>
</body>
<script type="text/javascript">
/*在js中获取点击框*/
var option=document.getElementsByName("option");
//全选
function checkAll()
for (let i = 0; i < option.length; i++)
option[i].checked=true;
//全不选
function checkNoAll()
for (let i = 0; i < option.length; i++)
option[i].checked=false;
//选中删除
function XDelete()
//定义一个id变量,初始化值为null,用来存储选中的数据
var id="";
//循环多选框
for (let i = 0; i < option.length; i++)
if(option[i].checked==true)
//选中的id赋值给id变量,用逗号分隔开
id=id+option[i].value+","
location.href="XDeleteServlet?id="+id;
</script>
</html>
1、选中删除功能
controller层:XDeleteServlet类:
package com.hsd.controller;
import com.hsd.service.StudentService;
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("/XDeleteServlet")
public class XDeleteServlet extends HttpServlet
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
//创建StudentService对象
StudentService studentService = new StudentService();
//接收页面发送过来的id
String ids=req.getParamet基于php的简单图书管理系统 ,登录,注册,退出登录,数据库增删改查 ,建立sessioon ,建立mysql数据库。
目录
一.建立MySQL数据库
1.我使用的是xampp,在浏览器地址栏输入http://localhost//phpmyadmin
注意:端口号默认是80端口,也就是http://localhost:80//phpmyadmin,如果你改了你的端口号注意更改
2.点击新建数据库(库名是itcast52)两个表明,book52(增删改查用)user52(登录注册用)
以下是数据库的文件,建立一个记事本,把代码粘贴上去,点击保存,把后缀从text改成sql,然后在数据库建立一个itcast52数据库,在数据库里面导入sql文件即可(数据库就完毕了)
-- phpMyAdmin SQL Dump
-- version 3.5.2.2
-- http://www.phpmyadmin.net
--
-- 主机: 127.0.0.1
-- 生成日期: 2022 年 05 月 16 日 05:24
-- 服务器版本: 5.5.27
-- PHP 版本: 5.4.7
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- 数据库: `itcast52`
--
-- --------------------------------------------------------
--
-- 表的结构 `book52`
--
CREATE TABLE IF NOT EXISTS `book52` (
`id` varchar(20) NOT NULL,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_estonian_ci NOT NULL,
`price` varchar(20) NOT NULL,
`data` varchar(20) NOT NULL,
`type` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- 转存表中的数据 `book52`
--
INSERT INTO `book52` (`id`, `name`, `price`, `data`, `type`) VALUES
('003', 'csdn', '55', '2025-11-6', '数据库设计'),
('012', '雕塑', '17777', '20255-5-6', '雕塑'),
('066', '固化剂', '255', '2001-09-06', '添加剂'),
('3119050152', '张修博', '999999', '2000-01-12', '人');
-- --------------------------------------------------------
--
-- 表的结构 `user52`
--
CREATE TABLE IF NOT EXISTS `user52` (
`account` char(100) NOT NULL,
`username` char(100) NOT NULL,
`sex` char(100) NOT NULL,
`age` char(100) NOT NULL,
`address` char(100) NOT NULL,
`mail` char(100) NOT NULL,
`password` char(100) NOT NULL,
`number` char(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- 转存表中的数据 `user52`
--
INSERT INTO `user52` (`account`, `username`, `sex`, `age`, `address`, `mail`, `password`, `number`) VALUES
('3119050152', '张修博', '男', '21', '河南商丘', '3119050152@qq.com', '3119050152', '3119050152');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
二.链接数据库文件(conn.php)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>conn文件</title>
</head>
<body>
<?php
$mysql_server_name = 'localhost'; //改成自己的mysql数据库服务器
$mysql_username = 'root'; //改成自己的mysql数据库用户名
$mysql_password = ''; //改成自己的mysql数据库密码
$mysql_database = 'itcast52'; //改成自己的mysql数据库名
$conn=mysqli_connect($mysql_server_name,$mysql_username,$mysql_password,$mysql_database); //连接数据库
//连接数据库错误提示
mysqli_query($conn, 'set names utf8');
mysqli_query($conn, 'set character set utf8');
if (mysqli_connect_errno($conn))
die("连接 MySQL 失败: " . mysqli_connect_error());
?>
</body>
</html>
三.前端登录页面(log.php)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<style type="text/css">
#aaawidth: 300px;
height: 30px;
</style>
<body>
<center>
<h2>登录界面</h2>
<form method="POST" action="log_ok.php">
账号 :<input id="aaa" type="text" name="uname" placeholder="用户名" />
<br /><br/>
密码 :<input id="aaa"type="password" name="pwd" placeholder="密码" />
<br />
<input type="submit" >
<input type="reset"> <a href="register.php">注册账号</a>
</form>
</center>
</body>
</html>
四.登录实现页面(log_ok.php)
<?php
//------文件编码格式,为了显示中文--------
header("content-type:text/html; charest=UTF-8");
//-------收受web的传值-------
$uname=$_POST["uname"];
$pwd=$_POST["pwd"];
//-----链接mysql数据库---
include("conn.php");
//----免除一些警告-------
error_reporting(0);
//-------启动session------
session_start();
//判断$uname与$pwd是否为空值-->true 返回上一步-->false 执行数据库查询,并且给session赋值
if(!($uname && $pwd))
echo"<script>alert('输入的账号或密码为空!请重新输入账号和密码');history.go(-1);</script>";
else
$sqlstr ="SELECT * FROM user52 WHERE (account='$uname') AND (password='$pwd')";
$result = $conn->query($sqlstr);
if($result->num_rows > 0)
$_SESSION["user"]=$uname;
echo"<script>alert('登录成功,即将转到主页面');location='index1.php'</script>";
else
echo"<script>alert('密码或者账号错误,登录失败,请重新输入账号和密码');history.go(-1);</script>";
?>
五.前端注册页面(register.php)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<style type="text/css">
.aaawidth: 300px;
height: 30px;
</style>
<style type="text/javascript">
</style>
<body>
<?php
$a=mt_rand(333333,999999999);
?>
<center>
<h2>注册界面</h2>
<form method="post" name="from1" action="register_ok.php"><!-- 在数据库中id是自动增长列 -->
账号: <input name="id" class="aaa" type="text" value="<?php echo"$a";?>"><br/><br/>
姓名: <input class="aaa" type="text" name="username"><br/><br/>
性别: <input class="aaa" type="text" name="sex"><br/><br/>
年龄: <input class="aaa" type="text" name="age"><br/><br/>
地址: <input class="aaa" type="text" name="address"><br/><br/>
邮箱: <input class="aaa" type="text" name="mail"><br/><br/>
密码: <input class="aaa" type="text" name="password"><br/><br/>
确认 密码: <input class="aaa" type="text" name="repsw"><br/><br/>
手机号: <input class="aaa"type="text" name="number"><br/><br/>
<input type="reset"name="reset" value="重置">
<input type="submit"name="submit" value="注册" onClick="myfunction">
<a href="log.php"><< 返回上一页</a>
<a href="register.php">点击注册</a>
</form>
</body>
</html>
六.注册实现界面(register_ok.php)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
</body>
<body>
<?php
include_once("conn.php");
header("content-type:text/html; charest=UTF-8");//文件编码格式
session_start();
$id=$_POST['id'];
$username=$_POST['username'];
$sex=$_POST['sex'];
$age=$_POST['age'];
$address=$_POST['address'];
$mail=$_POST['mail'];
$password=$_POST['password'];
$repsw=$_POST['repsw'];
$number=$_POST['number'];
if(!($id and $username and $sex and $age and $address and $mail and $password and $number and $repsw ))
echo"<script>alert('输入值不许为空');history.go(-1);</script>";
else
if(!($repsw==$password))
echo"<script>alert('两次密码不一致');history.go(-1);</script>";
else
$sql = "SELECT * FROM user52 WHERE (account='$id')";//在数据库中找相应信息!
$res = $conn->query($sql);
//判断结果集的记录数是否大于0
if ($res->num_rows > 0)
echo"<script>alert('已经有相同账号,请您换个账号进行注册');history.go(-1);</script>";
else
$_SESSION['user']=$id;
$sqlstr1="insert into user52 values('".$id."','".$username."','".$sex."','".$age."','".$address."','".$mail."','".$password."','".$number."')";
//执行sql insert语句 把用post引用的变量接入到register中
$result = mysqli_query($conn,$sqlstr1);//承接结果集
if($result)
echo"<script>alert('注册成功');location='index1.php'</script>";
else
echo"<script>alert('注册失败');history.go(-1);</script>";
?>
</body>
</html>
七.主页面(index1.php)增删改查中的 查
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>图书管理系统</title>
</head>
<body>
<?php
error_reporting(0);
session_start();
include("conn.php");
?>
<center>
<table width="799" height="247" border="1" cellpadding="0" cellspacing="0">
<tr>
<td height="220" background="1.jpg"> </td>
</tr>
<tr>
<td>
<table width="100%" height="27" border="1" cellpadding="0" cellspacing="0">
<tr bgcolor="#9791C2">
<td width="149" align="center" valign="middle"><b>
<?php
echo date("Y-m-d")."";
?>
</b></td>
<td width="130" align="center" valign="middle"><a href="index1.php" class="s">浏览目录</a></td>
<td width="130" align="center" valign="middle"><a href="index_ok.php" class="s">添加图书</a></td>
<td width="130" align="center" valign="middle"><a href="index-select.php" class="s">简单查询</a></td>
<td width="130" align="center" valign="middle"><a href="update1.php" class="s">删除图书</a></td>
<td width="130" align="center" valign="middle"><a href="delete.php" class="s">修改图书</a></td>
<td width="130" align="center" valign="middle"><a href="back.php" class="s">退出系统</a></td>
<td width="130" align="center" valign="middle"><a href="index1.php" class="s"><?php if(!($_SESSION['user']))
echo'session为空';
else
echo"欢迎 :";
echo $_SESSION['user'];
?></a></td>
</tr>
</table>
</td>
</tr>
</table>
<table width="799" border="0" cellpadding="0" cellspacing="0">
<tr>
<tr align="center" valign="middle">
<?php
include_once("conn.php");
?>
<table width="52.5%" border="1" cellpadding="0" cellspacing="0">
<tr bgcolor="#F7E0A3">
<td width="3%" height="25" class="top" align="center">id</td>
<td width="10%" class="top" align="center">图书名称</td>
<td width="10%" class="top" align="center">价格</td>
<td width="10%" class="top" align="center">出版日期</td>
<td width="5%" class="top" align="center">类型</td>
</tr>
<?php
$result = mysqli_query($conn,"select * from book52 ");
/*$sums = mysqli_num_rows($result);
echo $nums;*/
while($myrows = mysqli_fetch_array($result))
?>
<tr>
<td align="center"><span class="STYLE2"><?php echo $myrows['id'];?></span></td>
<td align="center"><span class="STYLE2"><?php echo $myrows['name'];?></span></td>
<td align="center"><span class="STYLE2"><?php echo $myrows['price'];?></span></td>
<td align="center"><span class="STYLE2"><?php echo $myrows['data'];?></span></td>
<td align="center"><span class="STYLE2"><?php echo $myrows['type'];?></span></td>
</tr>
<?php
?>
</table>
</tr>
</tr>
</table>
</center>
<?php
$sum = mysqli_num_rows($result);
echo $sum;
?>
</body>
</html>
八.添加图书(index_ok.php)增删改查中的 增
这个代码包含了实现的代码!
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>添加数据</title>
</head>
<body>
<?php
error_reporting(0);
session_start();
include("conn.php");
?>
<center>
<table width="799" height="247" border="1" cellpadding="0" cellspacing="0">
<tr>
<td height="220" background="1.jpg"> </td>
</tr>
<tr>
<td>
<table width="100%" height="27" border="1" cellpadding="0" cellspacing="0">
<tr bgcolor="#9791C2">
<td width="149" align="center" valign="middle">
<b>
<?php
echo date("Y-m-d")."";
?>
</b>
</td>
<td width="130" align="center" valign="middle"><a href="index1.php" class="s">浏览目录</a></td>
<td width="130" align="center" valign="middle"><a href="index_ok.php" class="s">添加图书</a></td>
<td width="130" align="center" valign="middle"><a href="index-select.php" class="s">简单查询</a></td>
<td width="130" align="center" valign="middle"><a href="back.php" class="s">退出系统</a></td>
<td width="130" align="center" valign="middle"><a href="index1.php" class="s"><?php if(!($_SESSION['user']))
echo'session为空';
else
echo"欢迎 :";
echo $_SESSION['user'];
?></a></td>
</tr>
</table>
</td>
</tr>
</table>
<form method="post" name="form1" action="index_ok.php">
编号 : <input type="text" name="id" ></input><br/><br/>
姓名 : <input type="text" name="name"></input><br/><br/>
价格 : <input type="text" name="price"></input><br/><br/>
日期 : <input type="text" name="data"></input><br/><br/>
类型 : <input type="text" name="type"></input><br/><br/>
<input type="reset" name="5" value="重置"></input>
<input type="submit" name="6" value="提交"></input>
</form>
<?php
error_reporting(0);
header("content-type:text/html; charest=UTF-8");//文件编码格式
include_once("conn.php");//连接数据库文件
$a=$_POST["id"];
$b=$_POST["name"];
$c=$_POST["price"];
$d=$_POST["data"];
$e=$_POST["type"];
//把input中的namejie
if(!($a and $b and $c and $d and $e))
echo"<script>alter('输入值不许为空');history.go(-1);</script>";//判断变量名是否为空值
else
$sqlstr1="insert into book52 values('".$a."','".$b."','".$c."','".$d."','".$e."')";
//执行sql insert语句 把用post引用的变量接入到bookable中
$result = mysqli_query($conn,$sqlstr1);//承接结果集
if($result)
echo"<script>alter('添加成功');location='index1.php'</script>";
else
echo"<script>alter('添加失败');history.go(-1);</script>";
?>
</center>
</body>
</html>
九.修改和删除页面(index-select.php)
这个页面包含了两个功能 修改 和 删除 但是 功能实现 在另外两个页面里
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>简单查询</title>
</head>
<body>
<?php
error_reporting(0);
session_start();
include("conn.php");
?>
<center>
<table width="799" height="247" border="1" cellpadding="0" cellspacing="0">
<tr>
<td height="220" background="1.jpg"> </td>
</tr>
<tr>
<td>
<table width="100%" height="27" border="1" cellpadding="0" cellspacing="0">
<tr bgcolor="#9791C2">
<td width="149" align="center" valign="middle"><b>
<?php
echo date("Y-m-d")."";
?>
</b></td>
<td width="130" align="center" valign="middle"><a href="index1.php" class="s">浏览目录</a></td>
<td width="130" align="center" valign="middle"><a href="index_ok.php" class="s">添加图书</a></td>
<td width="130" align="center" valign="middle"><a href="index-select.php" class="s">简单查询</a></td>
<td width="130" align="center" valign="middle"><a href="back.php" class="s">退出系统</a></td>
<td width="130" align="center" valign="middle"><a href="index1.php" class="s"><?php if(!($_SESSION['user']))
echo'session为空';
else
echo"欢迎 :";
echo $_SESSION['user'];
?></a></td>
</tr>
</table>
</td>
</tr>
</table>
<table width="799" border="0" cellpadding="0" cellspacing="0">
<tr>
<tr align="center" valign="middle">
<?php
include_once("conn.php");
?>
<table width="52.5%" border="1" cellpadding="0" cellspacing="0">
<tr bgcolor="#F7E0A3">
<td width="3%" height="25" class="top" align="center">id</td>
<td width="10%" class="top" align="center">图书名称</td>
<td width="10%" class="top" align="center">价格</td>
<td width="10%" class="top" align="center">出版日期</td>
<td width="5%" class="top" align="center">类型</td>
<td width="5%" class="top" align="center">芜湖</td>
</tr>
<?php
header("content-type:text/html; charest=UTF-8");//文件编码格式
include_once("conn.php");//连接数据库文件
$sqlstr="select * from book52 order by id ";//通过把sql语句放到变量值中 来执行php
$result = mysqli_query($conn,$sqlstr);//承接结果集 一般来说结果集之后会被用在循环中例如index_ok.php ,或者遍历输出数据库中的值例如index1.php
while($rows= mysqli_fetch_row($result))
?>
<tr>
<td align="center"><span class="m_td"><?php echo $rows[0];?></span></td>
<td align="center"><span class="m_td"><?php echo $rows[1];?></span></td>
<td align="center"><span class="m_td"><?php echo $rows[2];?></span></td>
<td align="center"><span class="m_td"><?php echo $rows[3];?></span></td>
<td align="center"><span class="m_td"><?php echo $rows[4];?></span></td>
<td align="center" class="m_td">
<a href =update.php?action=update&id=<?php echo $rows[0]?>>修改</a>/
<a href =delete.php?action=delete&id=<?php echo $rows[0]?>>删除</td>
</tr>
<?php
?>
</table>
</tr>
</tr>
</table>
</center>
</body>
</html>
十.修改图书(update.php)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>更改文档</title>
</head>
<body>
<?php
error_reporting(0);
include_once("conn.php");//连接数据库文件
if($_GET['action']=="update")
$sqlstr="select * from book52 where id =".$_GET['id']; //".$_GET['id'];没看懂
$result = mysqli_query($conn,$sqlstr);//承接结果集 一般来说结果集之后会被用在循环中例如index_ok.php ,或者遍历输出数据库中的值例如index1.php
$rows = mysqli_fetch_row($result); //枚举数组
?>
<form method="post" name="intForm" action="update_ok.php">
姓名 : <input type="text" name="name" value="<?php echo $rows[1]; ?>"></input><br/><br/>
价格 : <input type="text" name="price" value="<?php echo $rows[2]; ?>"></input><br/><br/>
日期 : <input type="text" name="data" value="<?php echo $rows[3]; ?>"></input><br/><br/>
类型 : <input type="text" name="type" value="<?php echo $rows[4]; ?>"></input><br/><br/>
<input type="hidden" name="action"value="update"></input>
<input type="hidden" name="id" value="<?php echo $rows[0] ?>"></input>
<input type="reset" name="Reset" value="重置">
<input type="submit" name="Submit" value="提交">
</form>
<?php
?>
</body>
</html>
十一.修改成功页面(update_ok.php)
这个项目的实现是 地址栏传参数,不会的同学可以去看下资料就差不多会了
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>更新数据</title>
</head>
<body>
<?php
header("Content-type:text/html; charest=UTF-8");//编码方式
include_once("conn.php");//连接数据库
$a=$_POST["id"];
$b=$_POST["name"];
$c=$_POST["price"];
$d=$_POST["data"];
$e=$_POST["type"];
if($_POST['action'] == "update")
if(!( $b and $c and $d and $e))
echo "输入不允许为空"; //返回上一页 或者使用alert
else
$sqlstr="update book52 set name='".$b."',price='".$c."',data='".$d."',type='".$e."' where id=".$a; //定义更新语句
//如果查询所有后面属性可以省略,一一对应
$result = mysqli_query($conn,$sqlstr);
if($result)
echo"修改成功,点击<a href='index1.php'>这里</a>查看";
else
echo"修改失败.<br>$sqlstr";
?>
</body>
</html>
</body>
</html>
十二.删除页面(delete.php)
包含了删除的功能
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<?php
header("Content-type:text/html; charest=UTF-8");//编码方式
// 处理删除操作的页面
include_once("conn.php");
if($_GET['action']=="delete")
$sqlstr1="delete from book52 where id =".$_GET['id'];
$result=mysqli_query($conn,$sqlstr1);
if($result)
echo"删除成功";
else
echo"删除失败";
?>
</body>
</html>
十三.退出系统(back.php)
这个代码就是清除session的值,并且返回到登陆页面
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<?php
session_start();
session_unset();
session_destroy();
echo"<script>alert('您已经退出系统,请重新登录');location='log.php'</script>";
?>
</body>
</html>
总结:由于仅仅是实现了该有的功能,所以页面不是太美观,有时间的同学可以仔细改一下,如果同学们有什么问题或者我写错了什么,可以在评论区发言,我看到会回复的,共同学习!勉励!!
以上是关于IDEA实现前端页面登录,注册增删改查操作-完整版的主要内容,如果未能解决你的问题,请参考以下文章
基于php的简单图书管理系统 ,登录,注册,退出登录,数据库增删改查 ,建立sessioon ,建立mysql数据库。
招新系统(jsp+servlet,实现简略前端网页注册登录+后台增删改查,分学生和管理员,Java语言,mysql数据库连接,tomcat服务器)
练习:WinForm--DataGridView增删改查完整版