使用IDEA创建Maven项目,选择自己需要的JDK版本,进入下一步。我们这里推荐使用1.8版本的 JDK。
添加框架支持。需要将普通的 Maven 工程升级为 Web 工程。右键点击模块。选择 Add Framework Support 进行添加 web 框架。
配置项目
添加依赖代码
我们需要在 pom.xml 配置文件中添加依赖代码。我们需要引入 Juint、Spring MVC、Servlet、Jsp、MyBatis、JDBC、JSTL 等框架的依赖。
<dependencies>
<!--引入 Juint 单元测试的框架依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--引入 SpringMVC(Spring Web MVC) 的框架依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--引入 Servlet 框架依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--引入 JSP 框架依赖-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!--引入 JSTL 标签库的框架依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--引入 MySQL 数据库的 JDBC 依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!--引入 Mybatis 框架依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
</dependencies>
<!--在build中配置 resources ,来防止资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
配置 MyBatis
接下来我们通过 MyBatis 框架来连接 MySQL 数据库。我们先添加文件名为 mybatis-config.xml 的 MyBatis 的配置文件。我们需要在 resources 包下创建一个名为 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="config.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/kid/service/StudentServiceImpl.xml"/>
</mappers>
</configuration>
接下来我们需要在 resources 包下创建一个 config.properties 资源文件,用来存放连接数据库的信息。
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/task?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username=root
password=
配置 SpringMVC
我们需要在 web.xml 配置文件中,注册 SpringMVC 的 DispatcherServlet,即视图解析器。DispatcherServlet 本质上还是一个 Servlet。添加代码后可能会出现爆红,是因为我们没有创建 springmvc-servlet.xml 配置文件,这里先不需要处理爆红错误,我们后续会进行创建的对应的配置文件的。
<!--1.注册servlet-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!-- 启动顺序,数字越小,启动越早 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!--所有请求都会被springmvc拦截 -->
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
我们在 resources 包下创建 springmvc-servlet.xml 配置文件。自动扫描包即,自动扫描指定路径下的所有注解。视图解析器即,只需要提供文件名称,通过类似于字符串拼接的方式,拼接出来完整的路径信息。添加代码后可能会出现爆红,这是因为找不到 com.kid.controller 路径,我们还是后续会处理的。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
<context:component-scan base-package="com.kid.controller"/>
<!-- 让Spring MVC不处理静态资源 -->
<mvc:default-servlet-handler/>
<!--
支持mvc注解驱动
在spring中一般采用@RequestMapping注解来完成映射关系
要想使@RequestMapping注解生效
必须向上下文中注册DefaultAnnotationHandlerMapping
和一个AnnotationMethodHandlerAdapter实例
这两个实例分别在类级别和方法级别处理。
而annotation-driven配置帮助我们自动完成上述两个实例的注入。
-->
<mvc:annotation-driven/>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
编写项目
创建包结构
我们按照 MVC 规范进行创建包结构。在 Java 包下创建 com 包,在 com 包中创建 kid 包,在 kid 包中创建 controller、dao、pojo、service 四个后端的包存放 Java 代码。其中,dao包中存放的是数据库的工具类;service 包中存放的是实际可能需要的业务,比如说学生登录、删除学生等;controller 包中存放的是控制类,用来接受 jsp 页面传过来的值,调用 service 包中的业务;pojo 包中存放的是可能用到的对象实体类。还需要在 WEB-INF 包下创建一个 jsp 包用来存放前端页面。
编写后端代码
dao 包
dao 包中存放的是数据库访问对象,用于连接数据库、对数据库进行操作。我们在 dao 包中创建一个 MyBatisUtil 类。
package com.kid.dao;
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 MyBatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
//修改数据库中的数据(增删改)必须提交事务,否则数据不会保存到数据库
//openSession(true)中的参数,true自动提交事务
return sqlSessionFactory.openSession(true);
}
}
pojo 包
pojo 包中存放的是用到的实体类。这里我们需要创建两个实体类,Student 类和 StudentLogin 类。其中,Student 类是完整的学生类;StudentLogin 类是学生登录时使用的类,只是保存了学生的部分信息。
Student 类中的代码。
package com.kid.pojo;
public class Student {
private String sid;//UUID,唯一标识
private int id;//学生编号
private String name;//学生姓名
private String password;//登录密码
private int age;//年龄
private String sex;//性别
public Student(String sid, int id, String name, String password, int age, String sex) {
this.sid = sid;
this.id = id;
this.name = name;
this.password = password;
this.age = age;
this.sex = sex;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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;
}
@Override
public String toString() {
return "Student{" +
"sid='" + sid + '\'' +
", id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
StudentLogin 类中的代码。
package com.kid.pojo;
public class StudentLogin {
private String sid;//UUID,唯一标识
private int id;//学生编号
private String password;//登录密码
public StudentLogin() {
}
public StudentLogin(String sid, String password) {
this.sid = sid;
this.password = password;
}
public StudentLogin(int id, String password) {
this.id = id;
this.password = password;
}
public StudentLogin(String sid, int id, String password) {
new StudentLogin(sid, password);
this.id = id;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "StudentLogin{" +
"sid='" + sid + '\'' +
", id=" + id +
", password='" + password + '\'' +
'}';
}
}
service 包
service 包中存放的是实际所有的业务。我们这里使用 MyBatis 框架,需要先创建一个 StudentService 接口类,里面定义了业务相关的所有方法;需要在创建一个 StudentServiceImpl 配置文件,用来对 StudentService 接口进行映射。
StudentService 接口类中的代码。
package com.kid.service;
import com.kid.pojo.Student;
import com.kid.pojo.StudentLogin;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface StudentService {
//增加学生
int insertStudent(@Param("student") Student student);
//删除学生
int deleteStudentBySid(@Param("sid") String sid);
int deleteStudentById(@Param("id") int id);
int deleteStudentByName(@Param("name") String name);
int deleteStudentByAge(@Param("age") int age);
int deleteStudentBySex(@Param("sex") String sex);
//修改学生信息
int updateStudent(@Param("student") Student student);
//查找学生
List<Student> getStudentAll();
List<Student> getStudentBySid(@Param("sid") String sid);
List<Student> getStudentById(@Param("id") int id);
List<Student> getStudentByName(@Param("name") String name);
List<Student> getStudentByAge(@Param("age") int age);
List<Student> getStudentBySex(@Param("sex") String sex);
//学生登录
Student studentLogin(@Param("studentLogin") StudentLogin studentLogin);
}
StudentServiceImpl 配置文件中的代码。
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kid.service.StudentService">
<!--添加学生信息-->
<insert id="insertStudent" parameterType="com.kid.pojo.Student">
insert into task.student (sid, id, name, password, age, sex)
values (#{student.sid}, #{student.id}, #{student.name}, #{student.password}, #{student.age}, #{student.sex})
</insert>
<!--删除学生信息-->
<!--根据Sid删除学生-->
<delete id="deleteStudentBySid" parameterType="String">
delete
from task.student
where sid = #{sid}
</delete>
<!--根据id删除学生-->
<delete id="deleteStudentById" parameterType="int">
delete
from task.student
where id = #{id}
</delete>
<!--根据name删除学生-->
<delete id="deleteStudentByName" parameterType="String">
delete
from task.student
where name = #{name}
</delete>
<!--根据age删除学生-->
<delete id="deleteStudentByAge" parameterType="int">
delete
from task.student
where age = #{age}
</delete>
<!--根据sex删除学生-->
<delete id="deleteStudentBySex" parameterType="String">
delete
from task.student
where sex = #{sex}
</delete>
<!--修改学生信息-->
<update id="updateStudent" parameterType="com.kid.pojo.Student">
update task.student
set sid = #{student.sid},
id = #{student.id},
name = #{student.name},
password = #{student.password},
age = #{student.age},
sex = #{student.sex}
where sid = #{student.sid};
</update>
<!--查找学生信息-->
<!--查找所有学生-->
<select id="getStudentAll" resultType="com.kid.pojo.Student">
select *
from task.student
</select>
<!--根据sid查找学生-->
<select id="getStudentBySid" parameterType="String" resultType="com.kid.pojo.Student">
select *
from task.student
where sid = #{sid}
</select>
<!--根据id查找学生-->
<select id="getStudentById" parameterType="int" resultType="com.kid.pojo.Student">
select *
from task.student
where id = #{id}
</select>
<!--根据name查找学生-->
<select id="getStudentByName" parameterType="String" resultType="com.kid.pojo.Student">
select *
from task.student
where name = #{name}
</select>
<!--根据age查找学生-->
<select id="getStudentByAge" parameterType="int" resultType="com.kid.pojo.Student">
select *
from task.student
where age = #{age}
</select>
<!--根据sex查找学生-->
<select id="getStudentBySex" parameterType="String" resultType="com.kid.pojo.Student">
select *
from task.student
where sex = #{sex}
</select>
<select id="studentLogin" parameterType="com.kid.pojo.StudentLogin" resultType="com.kid.pojo.Student">
select *
from task.student
where (id = #{studentLogin.id} and password = #{studentLogin.password})
or (sid = #{studentLogin.sid} and password = #{studentLogin.password})
</select>
</mapper>
controller 包
controller 包中存放的就是控制类,接收前端页面传送过来的值,通过调用 service 包中的方法,对值进行处理,然后再指定到前端页面。我们需要再 controller 包中创建一个 StudentController 类。这里可能会爆红,是因为我们没有创建前端页面,我们下面就会创建对应的前端页面了。
package com.kid.controller;
import com.kid.dao.MyBatisUtil;
import com.kid.pojo.Student;
import com.kid.pojo.StudentLogin;
import com.kid.service.StudentService;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;
// 该类被Spring接管,类中所有方法的返回值都为 String 类型
// 类中的每个方法都会被视图解析器进行解析
@Controller
public class StudentController {
//学生登录
//路径为:/login
@RequestMapping("/login")
public String login(Model model) {
//获取request对象
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//接收值
String sidORId = request.getParameter("SidORId");
String password = request.getParameter("password");
SqlSession session = MyBatisUtil.getSqlSession();
StudentService studentService = session.getMapper(StudentService.class);
//根据Sid查找学生
Student student = studentService.studentLogin(new StudentLogin(sidORId, password));
//Sid查找失败
if (student == null) {
try {
//尝试将字符串转换为整形数字,再次进行查找
int id = Integer.parseInt(sidORId);
student = studentService.studentLogin(new StudentLogin(id, password));
} catch (Exception e) {
//字符串转整形失败
model.addAttribute("msg", "账号或密码错误!请重新尝试登录!");
}
}
session.close();
//学生登录成功
if (student != null) {
model.addAttribute("flag", true);
model.addAttribute("msg", "登录成功!");
model.addAttribute("student", student);
} else {
model.addAttribute("flag", false);
model.addAttribute("msg", "登录失败!");
}
return "hello";
}
//查看所有学生信息
//路径为:lookupAll
@RequestMapping("/lookupAll")
public String lookupAll(Model model) {
SqlSession session = MyBatisUtil.getSqlSession();
StudentService studentService = session.getMapper(StudentService.class);
List<Student> list = studentService.getStudentAll();
session.close();
model.addAttribute("list", list);
return "lookupAll";
}
//根据 Sid 删除学生信息
//路径为:deleteStudent
@RequestMapping("/deleteStudent")
public String deleteStudent(Model model) {
int flag = 0;//标记是否删除成功
//获取request对象
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//接收值
String sid = request.getParameter("sid");
SqlSession session = MyBatisUtil.getSqlSession();
StudentService studentService = session.getMapper(StudentService.class);
flag = studentService.deleteStudentBySid(sid);
if (flag > 0) {
model.addAttribute("delete", "删除成功!");
} else {
model.addAttribute("delete", "删除失败!");
}
//删除成功后,再查找一遍所有学生
List<Student> list = studentService.getStudentAll();
session.close();
model.addAttribute("list", list);
return "lookupAll";
}
//更新学生信息
//路径为:updateStudent
@RequestMapping("/updateStudent")
public String updateStudent(Model model) throws UnsupportedEncodingException {
int flag = 0;//是否修改成功
//获取request对象
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
request.setCharacterEncoding("utf-8");//解决乱码问题
//接收值
String sid = request.getParameter("sid");
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String password = request.getParameter("password");
int age = Integer.parseInt(request.getParameter("age"));
String sex = request.getParameter("sex");
Student student = new Student(sid, id, name, password, age, sex);
SqlSession session = MyBatisUtil.getSqlSession();
StudentService studentService = session.getMapper(StudentService.class);
flag = studentService.updateStudent(student);
if (flag > 0) {
model.addAttribute("delete", "修改成功!");
} else {
model.addAttribute("delete", "修改失败!");
}
List<Student> list = studentService.getStudentAll();
session.close();
model.addAttribute("list", list);
return "lookupAll";
}
//根据Sid查找学生信息
//路径为:/lookupOne
@RequestMapping("/lookupOne")
public String lookupOne(Model model) {
//获取request对象
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//接收值
String sid = request.getParameter("sid");
Student student = null;
SqlSession session = MyBatisUtil.getSqlSession();
StudentService studentService = session.getMapper(StudentService.class);
student = studentService.getStudentBySid(sid).get(0);
model.addAttribute("student", student);
return "updateStudent";
}
//注册学生信息
//路径:/logon
@RequestMapping("logon")
public String logonStudent(Model model) throws UnsupportedEncodingException {
int flag = 0;//是否修改成功
//获取request对象
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
request.setCharacterEncoding("utf-8");//解决乱码问题
//接收值
String sid = UUID.randomUUID().toString().replace("-", "");//SID使用UUID创建,然后使用""替换掉UUID中的"-"
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String password = request.getParameter("password");
int age = Integer.parseInt(request.getParameter("age"));
String sex = request.getParameter("sex");
Student student = new Student(sid, id, name, password, age, sex);
SqlSession session = MyBatisUtil.getSqlSession();
StudentService studentService = session.getMapper(StudentService.class);
flag = studentService.insertStudent(student);
session.close();
if (flag > 0) {
model.addAttribute("msg", "注册成功!");
model.addAttribute("flag", true);
model.addAttribute("student", student);
} else {
model.addAttribute("msg", "注册失败!");
model.addAttribute("flag", false);
}
return "hello";
}
}
编写前端代码
登录页面
首先,我们需要在 index.jsp 页面中添加登录页面的内容。
<%--
Created by IntelliJ IDEA.
User: 24484
Date: 2021/9/20
Time: 20:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<table border="1">
<form action="/login" method="post">
<tr align="center">
<td>账号:</td>
<td>
<input type="text" name="SidORId" placeholder="输入学生编号或唯一标识">
</td>
</tr>
<tr align="center">
<td>密码:</td>
<td>
<input type="password" name="password" placeholder="请输入密码">
</td>
</tr>
<tr align="center">
<td colspan="2">
<table border="1">
<tr align="center">
<td width="30%">
<input type="reset" value="清除">
</td>
<td width="30%">
<input type="submit" value="登录">
</td>
</tr>
</table>
</td>
</form>
</table>
<form action="logon.jsp" method="post">
<input type="submit" value="注册"/>
</form>
</body>
</html>
版权声明:本文为CSDN博主「白色魔术师」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/kid_0_kid/article/details/120379584