SpringBoot+MyBatis+jsp综合项目实践
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>ems-springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ems-springboot</name>
<description>ems-springboot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--jsp-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.yml
spring:
mvc:
view:
suffix: .jsp
prefix: /
# 设置数据源
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mydata?useUnicode=true&characterEncodnig=UTF-8
username: root
password: 835081
# 设置mybatis
mybatis:
mapper-locations: classpath:/mapper/*.xml
type-aliases-package: com.hg.entity
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
server:
port: 8080
servlet:
context-path: /ems-jsp # 指定项目名称
jsp:
init-parameters:
development: true # 开启jsp模板开发模式
# 设置日志
logging:
level:
root: info
com.hg: debug
启动文件
@SpringBootApplication
@MapperScan("com.hg.dao")
public class EmsSpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(EmsSpringbootApplication.class, args);
}
}
用户注册
实体类
package com.hg.entity;
import lombok.Data;
@Data
public class User {
private Integer id;
private String username;
private String realname;
private String password;
private Boolean gender;
}
dao
package com.hg.dao;
import com.hg.entity.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserDao {
//注册用户,插入用户信息
public void save(User user);
//通过用户名查找用户
public User findByName(String username);
}
mapper
<?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.hg.dao.UserDao">
<insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into user
values (#{id}, #{username}, #{realname}, #{password}, #{gender})
</insert>
<select id="findByName" parameterType="String" resultType="User">
select id,username,realname,password,gender from user where username = #{username}
</select>
</mapper>
dao测试
package com.hg.dao;
import com.hg.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.DigestUtils;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class UserDaoTest {
@Autowired
UserDao userDao;
@Test
void saveTest(){
User user = new User(1, "zhangsan", "张三", "1234", true);
//对密码进行加密
String md5Password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
user.setPassword(md5Password);
userDao.save(user);
}
@Test
void findByNameTest(){
System.out.println(userDao.findByName("zhangsan"));
}
}
生成图形验证码
- 引入插件:VerifyCodeUtils,新建utils文件夹,并将插件放入此文件夹
- 在UserController中响应验证码请求
//生成图形验证码
@GetMapping("/generateImageCode")
public void GeneratorImageCode(HttpSession session, HttpServletResponse response){
//生成随机字符串
String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
//将随机字符串存入session
session.setAttribute("code",verifyCode);
//通过随机字符串生成图片
//通过response响应图片
response.setContentType("image/png"); //指定相应类型
try {
ServletOutputStream outputStream = response.getOutputStream();
VerifyCodeUtils.outputImage(220,80,outputStream,verifyCode);
} catch (IOException e) {
e.printStackTrace();
}
- 在regist.jsp文件中请求和显示验证码
<tr>
<td valign="middle" align="right">
验证码:
<img id="num" src="${pageContext.request.contextPath}/user/generateImageCode" />
<!--每次请求验证码都加一个时间戳,以便防止浏览器对相同的请求进行缓存,从而不发起请求-->
<a href="javascript:;" οnclick="document.getElementById('num').src = '${pageContext.request.contextPath}/user/generateImageCode?'+(new Date()).getTime()">换一张</a>
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="code" />
</td>
</tr>
- 在controller中创建register方法响应请求
private static final Logger log = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
... ...
//用户注册
@PostMapping("/register")
public String register(String code, User user, HttpSession session/*, HttpServletRequest request*/){
log.debug("验证码: {}",code);
log.debug("用户:{}",user);
try {
userService.register(code,user,session);
} catch (Exception e) {
e.printStackTrace();
// request.setAttribute("exception",e.getMessage());
// return "forward:/regist.jsp";
try {
return "redirect:/regist.jsp?error=" + URLEncoder.encode(e.getMessage(),"UTF-8");
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
}
return "redirect:/login.jsp";
}
- UserService
package com.hg.service;
import com.hg.entity.User;
import javax.servlet.http.HttpSession;
public interface UserService {
//注册用户
void register(String code, User user, HttpSession session);
}
- UserServiceImpl
package com.hg.service;
import com.hg.dao.UserDao;
import com.hg.entity.User;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
@Override
public void register(String code, User user, HttpSession session) {
//如果验证码相同
if (code.equalsIgnoreCase(session.getAttribute("code").toString())){
//查找用户名是否存在
if(!ObjectUtils.isEmpty(userDao.findByName(user.getUsername()))){
throw new RuntimeException("用户名已注册!");
}else{
user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));
userDao.save(user);
}
}else{
throw new RuntimeException("验证码错误!");
}
}
}
regist.jsp
<div id="content">
<p id="whereami">
</p>
<h1>
注册
</h1>
<%--<p><span style="color: red;">${requestScope.get("exception")}</span></p>--%>
<p><span style="color: red;">${param.error}</span></p>
<form action="${pageContext.request.contextPath}/user/register" method="post">
<table cellpadding="0" cellspacing="0" border="0"
class="form_table">
<tr>
<td valign="middle" align="right">
用户名:
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="username" />
</td>
</tr>
<tr>
<td valign="middle" align="right">
真实姓名:
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="realname" />
</td>
</tr>
<tr>
<td valign="middle" align="right">
密码:
</td>
<td valign="middle" align="left">
<input type="password" class="inputgri" name="password" />
</td>
</tr>
<tr>
<td valign="middle" align="right">
性别:
</td>
<td valign="middle" align="left">
男
<input type="radio" class="inputgri" name="gender" value="0" checked="checked"/>
女
<input type="radio" class="inputgri" name="gender" value="1"/>
</td>
</tr>
<tr>
<td valign="middle" align="right">
验证码:
<img id="num" src="${pageContext.request.contextPath}/user/generateImageCode" />
<a href="javascript:;" οnclick="document.getElementById('num').src = '${pageContext.request.contextPath}/user/generateImageCode?'+(new Date()).getTime()">换一张</a>
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="code" />
</td>
</tr>
</table>
<p>
<input type="submit" class="button" value="Submit »" />
</p>
</form>
</div>
用户登录
service
package com.hg.service;
import com.hg.entity.User;
import javax.servlet.http.HttpSession;
public interface UserService {
//注册用户
void register(String code, User user, HttpSession session);
//用户登录
User login(String username, String password);
}
serviceImpl
package com.hg.service;
import com.hg.dao.UserDao;
import com.hg.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
... ...
//用户登录
@Override
public User login(String username, String password) {
//判断用户名是否存在
User userDb = userDao.findByName(username);
if (ObjectUtils.isEmpty(userDb)) throw new RuntimeException("用户不存在!");
//校验加密后的密码
if (!userDb.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))){
throw new RuntimeException("密码输入错误!");
}
return userDb;
}
}
controller
package com.hg.controller;
import com.hg.entity.User;
import com.hg.service.UserService;
import com.hg.utils.VerifyCodeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@Controller
@RequestMapping("/user")
public class UserController {
private static final Logger log = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
... ...
//用户登录
@PostMapping("/login")
public String login(String username,String password,HttpSession session) throws UnsupportedEncodingException {
log.debug("username: {}",username);
log.debug("password: {}",password);
try {
User user = userService.login(username,password);
session.setAttribute("username",username);
} catch (Exception e) {
e.printStackTrace();
return "redirect:/login.jsp?error=" + URLEncoder.encode(e.getMessage(),"UTF-8");
}
return "redirect:/emp/list";
}
}
jsp
<div id="content">
<p id="whereami">
</p>
<h1>
login
</h1>
<p style="color: red;">${param.error}</p>
<form action="${pageContext.request.contextPath}/user/login" method="post">
<table cellpadding="0" cellspacing="0" border="0"
class="form_table">
<tr>
<td valign="middle" align="right">
username:
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="username" />
</td>
</tr>
<tr>
<td valign="middle" align="right">
password:
</td>
<td valign="middle" align="left">
<input type="password" class="inputgri" name="password" />
</td>
</tr>
</table>
<p>
<input type="submit" class="button" value="Submit »" />
<input type="button" class="button" οnclick="location.href='${pageContext.request.contextPath}/regist.jsp'" value="Regist »" />
</p>
</form>
</div>
员工列表
entity
package com.hg.entity;
import lombok.Data;
import java.util.Date;
@Data
public class Employee {
private Integer id;
private String name;
private Date birthday;
private Double salary;
private Boolean gender;
}
dao
package com.hg.dao;
import com.hg.entity.Employee;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface EmployeeDao {
//员工列表
List<Employee> findAll();
}
dao.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.hg.dao.EmployeeDao">
<select id="findAll" resultType="Employee">
select id, name, birthday, salary, gender
from employee
</select>
</mapper>
service
package com.hg.service;
import com.hg.entity.Employee;
import java.util.List;
public interface EmployeeService {
List<Employee> findAll();
}
serviceImpl
package com.hg.service;
import com.hg.dao.EmployeeDao;
import com.hg.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmployeeServiceImpl implements EmployeeService {
private EmployeeDao employeeDao;
@Autowired
public EmployeeServiceImpl(EmployeeDao employeeDao) {
this.employeeDao = employeeDao;
}
@Override
public List<Employee> findAll() {
return employeeDao.findAll();
}
}
controller
package com.hg.controller;
import com.hg.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/emp")
public class EmployeeController {
EmployeeService employeeService;
@Autowired
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
//列出所有员工信息
@GetMapping("/list")
public String list(Model model){
model.addAttribute("list",employeeService.findAll());
return "emplist";
}
}
jsp
<div id="content">
<p id="whereami">
</p>
<h1>
Welcome !
</h1>
<table class="table">
<tr class="table_header">
<td>
ID
</td>
<td>
Name
</td>
<td>
Salary
</td>
<td>
Bir
</td>
<td>
Sex
</td>
<td>
Operation
</td>
</tr>
<c:forEach items="${requestScope.list}" var="emp" varStatus="sta">
<tr
<c:if test="${sta.index%2 == 0}">class="row1"</c:if>
<c:if test="${sta.index%2 != 0}">class="row2"</c:if>
>
<td >${emp.id}</td>
<td >${emp.name}</td>
<td >${emp.salary}</td>
<td >
<fmt:formatDate value="${emp.birthday}" pattern="yyyy-MM-dd"></fmt:formatDate>
</td>
<td >${emp.gender == true? "男" : "女"}</td>
<td>
<a href="">删除</a>
<a href="${pageContext.request.contextPath}/emp/findById?id=${emp.id}">更新</a>
</td>
</tr>
</c:forEach>
</table>
<p>
<a href="${pageContext.request.contextPath}/addEmp.jsp">添加员工信息</a>
</p>
</div>
添加员工
dao
//添加员工
void add(Employee employee);
dao.xml
<insert id="add" parameterType="Employee" useGeneratedKeys="true" keyProperty="id">
insert into employee values (#{id},#{name},#{birthday},#{salary},#{gender})
</insert>
service
void save(Employee employee);
serviceImpl
@Override
public void save(Employee employee) {
employeeDao.add(employee);
}
controller
//添加员工信息
@PostMapping("/save")
public String save(Employee employee){
log.debug("employee_name: {}", employee.getName());
log.debug("employee_salary: {}", employee.getSalary());
log.debug("employee_birthday: {}", employee.getBirthday());
log.debug("employee_gender: {}", employee.getGender());
employeeService.save(employee);
return "redirect:/emp/list";
}
修改员工信息
dao
//通过ID查找员工
Employee findById(Integer id);
//更新员工信息
void update(Employee employee);
dao.xml
<select id="findById" resultType="Employee" parameterType="Integer">
select id, name, birthday, salary, gender from employee where id=#{id}
</select>
<update id="update" parameterType="Employee">
update employee set name=#{name},birthday=#{birthday},salary=#{salary},gender=#{gender} where id=#{id}
</update>
serivce&serviceImpl
Employee findById(Integer id);
void update(Employee employee);
@Override
public Employee findById(Integer id) {
return employeeDao.findById(id);
}
@Override
public void update(Employee employee) {
employeeDao.update(employee);
}
controller
//通过id查找员工信息,并返回修改页面
@GetMapping("/findById")
public String findById(Integer id, Model model){
log.debug("emp_id: {}",id);
model.addAttribute("employee",employeeService.findById(id));
return "updateEmp";
}
//更新员工数据
@PostMapping("/update")
public String update(Employee employee){
log.debug("employee: {}", employee);
employeeService.update(employee);
return "redirect:/emp/list";
}
jsp
<form action="${pageContext.request.contextPath}/emp/update" method="post">
<table cellpadding="0" cellspacing="0" border="0"
class="form_table">
<tr>
<td valign="middle" align="right">
id:
</td>
<td valign="middle" align="left" >
<input value="${employee.id}" name="id" readonly />
</td>
</tr>
<tr>
<td valign="middle" align="right">
name:
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="name" value="${employee.name}"/>
</td>
</tr>
<tr>
<td valign="middle" align="right">
salary:
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="salary" value="${employee.salary}"/>
</td>
</tr>
<tr>
<td valign="middle" align="right">
bir:
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="birthday"
value="<fmt:formatDate value="${employee.birthday}" pattern="yyyy/MM/dd"></fmt:formatDate>"/>
</td>
</tr>
<tr>
<td valign="middle" align="right">
sex:
</td>
<td valign="middle" align="left">
<select name="gender" >
<option value="true"
<c:if test="${employee.gender}">
selected
</c:if>
>男</option>
<option value="false"
<c:if test="${!employee.gender}">
selected
</c:if>
>女</option>
</select>
</td>
</tr>
</table>
<p>
<input type="submit" class="button" value="Confirm" />
</p>
</form>
删除员工信息
dao
//删除员工信息
void delete(Integer id);
mapper.xml
<delete id="delete" parameterType="Integer">
delete from employee where id = #{id}
</delete>
service
void delete(Integer id);
serviceImpl
@Override
public void delete(Integer id) {
employeeDao.delete(id);
}
controller
//删除员工数据
@GetMapping("/delete/{id}")
public String delete(@PathVariable("id") Integer id){
log.debug("id:{}",id);
employeeService.delete(id);
return "redirect:/emp/list";
}
jsp
<a href="javascript:;" οnclick="deleteEmployee(${emp.id})">删除</a>
<script>
function deleteEmployee(id) {
if (window.confirm('是否删除id为:'+id+'员工信息?')){
location.href='${pageContext.request.contextPath}/emp/delete/'+id
}
}
</script>