SpringMVC——CRUD操作

目录

  • SpringMVC的CRUD操作
    在这里插入图片描述

一、SpringMVC完成CRUD

0、导入相关依赖
<dependency>
    <groupId>junitgroupId>
    <artifactId>junitartifactId>
    <version>4.12version>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webmvcartifactId>
    <version>5.1.9.RELEASEversion>
dependency>
<dependency>
    <groupId>javax.servletgroupId>
    <artifactId>servlet-apiartifactId>
    <version>2.5version>
dependency>
<dependency>
    <groupId>javax.servlet.jspgroupId>
    <artifactId>jsp-apiartifactId>
    <version>2.2version>
dependency>
<dependency>
    <groupId>javax.servletgroupId>
    <artifactId>jstlartifactId>
    <version>1.2version>
dependency>

<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <version>1.18.10version>
    <scope>providedscope>
dependency>

<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
    <version>2.9.10version>
dependency>
<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-coreartifactId>
    <version>2.9.10version>
dependency>
<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-annotationsartifactId>
    <version>2.9.10version>
dependency>


<dependency>
    <groupId>javax.servletgroupId>
    <artifactId>jstlartifactId>
    <version>1.2version>
dependency>


<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webmvcartifactId>
    <version>5.2.2.RELEASEversion>
dependency>

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-jdbcartifactId>
    <version>5.2.2.RELEASEversion>
dependency>


<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <version>1.18.8version>
dependency>


<dependency>
    <groupId>junitgroupId>
    <artifactId>junitartifactId>
    <version>4.12version>
    <scope>testscope>
dependency>


<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-testartifactId>
    <version>5.2.2.RELEASEversion>
dependency>


<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>5.1.4version>
dependency>


<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.1.5version>
dependency>


<dependency>
    <groupId>org.aspectjgroupId>
    <artifactId>aspectjweaverartifactId>
    <version>1.9.4version>
dependency>



<dependency>
    <groupId>org.hibernategroupId>
    <artifactId>hibernate-validatorartifactId>
    <version>6.1.0.Finalversion>
dependency>

<dependency>
    <groupId>com.fasterxmlgroupId>
    <artifactId>classmateartifactId>
    <version>1.3.1version>
dependency>

<dependency>
    <groupId>javax.validationgroupId>
    <artifactId>validation-apiartifactId>
    <version>2.0.1.Finalversion>
dependency>

<dependency>
    <groupId>org.jboss.logginggroupId>
    <artifactId>jboss-loggingartifactId>
    <version>3.3.0.Finalversion>
dependency>


<dependency>
    <groupId>commons-fileuploadgroupId>
    <artifactId>commons-fileuploadartifactId>
    <version>1.3.3version>
dependency>
<dependency>
    <groupId>commons-iogroupId>
    <artifactId>commons-ioartifactId>
    <version>2.4version>
dependency>

<dependency>
    <groupId>javax.servletgroupId>
    <artifactId>javax.servlet-apiartifactId>
    <version>4.0.1version>
dependency>

1、设计数据库表

CREATE TABLE `employee` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) DEFAULT NULL,
  `password` varchar(40) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `hiredate` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8;

配置文件

#key=value
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc
jdbc.username=root
jdbc.password=1111
jdbc.initialSize=2

实体类

package com.sunny.domain;

import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Date;

@Data
public class Employee {

	private Long id;

	@NotNull(message = "用户名不能为空")
	@Size(max = 10, min = 4, message = "用户名在4-10位之间")
	private String username;

	@NotNull(message = "密码不能为空")
	@Size(max = 10, min = 4, message = "密码在4-10位之间")
	private String password;

	@NotNull(message = "年龄不能为空")
	@Min(value = 18, message = "年龄最小值为18")
	@Max(value = 60, message = "年龄最大值为60")
	private Integer age;

	@DateTimeFormat(pattern = "yyyy-MM-dd")
	private Date hiredate;
}

2、控制层代码

LoginController

@Controller
public class LoginController {

    @Autowired
    private IEmployeeService service;

    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session){
        System.out.println("LoginController.login");
        Employee current = service.login(username, password);
        if (current == null){
            session.setAttribute("errorMsg", "账号或密码错误");
            return "redirect:/login.jsp";
        }
        session.setAttribute("user_in_session", current);
        return "redirect:/employee/list";
    }

/*    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session) {
        try {
            service.login(username, password);
        } catch (Exception e) {
            session.setAttribute("errorMsg", e.getMessage());
            return "redirect:/login.jsp";
        }
        return "redirect:/employee/list";
    }*/
}

EmployeeController

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/list")
    public String list(Model model) {
        //int a = 1 / 0;
        // 共享数据到list界面
        model.addAttribute("employees", employeeService.listAll());
        return "employee/list"; // 跳转到list界面
    }

    // 新增员工
    @RequestMapping("/input")
    public String input(Model model, Long id) {
        if (id != null) {
            model.addAttribute("employee", employeeService.get(id));
        } else {
            model.addAttribute("employee", new Employee());
        }
        return "employee/input";
    }

/*    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee emp){
        if (emp.getId() == null){
            employeeService.save(emp);
        } else {
            employeeService.update(emp);
        }
        return "redirect:/employee/list";
    }*/

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(@Valid Employee emp, BindingResult bindingResult, Model model) {

        List<ObjectError> errors = bindingResult.getAllErrors();
        if (errors.size() > 0) {
            model.addAttribute("errors", errors);
            return "employee/input";
        }

        if (emp.getId() == null) {
            employeeService.save(emp);
        } else {
            employeeService.update(emp);
        }
        return "redirect:/employee/list";
    }

    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            employeeService.delete(id);
        }
        return "redirect:/employee/list";
    }
}

拦截器代码:CheckLoginInterceptor

public class CheckLoginInterceptor implements HandlerInterceptor {
    // 在请求处理方法之前执行
    // 如果返回true,执行下一个拦截器
    // 如果返回false,就不执行下一个拦截器

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 没有登录的情况
        if (request.getSession().getAttribute("user_in_session") == null){
            System.out.println("----------------");
            response.sendRedirect("/login.jsp");
            return false; // 阻止往后放行
        }
        // 放行,给下一个拦截器或者最终的处理器
        return true;
    }

    // 在请求处理方法执行之后执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    // 在dispatcherServlet处理后执行,做清理工作
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

3、业务层代码

public interface IEmployeeService {
	void save(Employee emp);

	void update(Employee emp);

	void delete(Long id);

	Employee get(Long id);

	List<Employee> listAll();

	Employee login(String username, String password);

	/*void login(String username, String password);*/
}
@Service("employeeServiceImpl")
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {

	@Autowired
	private IEmployeeDAO dao;


	public void save(Employee emp) {
		dao.save(emp);
		//int a = 1/0;
	}

	public void update(Employee emp) {
		dao.update(emp);
	}

	public void delete(Long id) {
		dao.delete(id);
	}

	@Transactional(readOnly = true)
	public List<Employee> listAll() {
		return dao.listAll();
	}

	@Transactional(readOnly = true)
	public Employee get(Long id) {
		return dao.get(id);
	}

	@Transactional(readOnly = true)
	public Employee login(String username, String password) {
		return dao.login(username, password);
	}

/*	public void login(String username, String password){
		Employee current = dao.login(username, password);
		if (current == null){
			throw new RuntimeException("账号或密码错误!");
		}
		UserContext.setCurrentUser(current);
	}*/
}

4、持久层代码

public interface IEmployeeDAO {
	void save(Employee emp);

	void update(Employee emp);

	void delete(Long id);

	Employee get(Long id);

	List<Employee> listAll();

	Employee login(String username, String password);
}
public class EmployeeDAOImpl implements IEmployeeDAO {

    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource ds) {
        this.jdbcTemplate = new JdbcTemplate(ds);
    }

    public void save(Employee e) {
        jdbcTemplate.update("INSERT INTO employee (username,password,age,hiredate) VALUES (?,?,?,?)", e.getUsername(),
                e.getPassword(), e.getAge(), e.getHiredate());
    }

    public void update(Employee e) {
        jdbcTemplate.update("UPDATE employee SET username= ?,password=?,age = ?,hiredate=? WHERE id= ?",
                e.getUsername(), e.getPassword(), e.getAge(), e.getHiredate(), e.getId());
    }

    public void delete(Long id) {
        jdbcTemplate.update("DELETE FROM employee WHERE id = ?", id);
    }


    public Employee get(Long id) {
        String sql = "SELECT id,username,password,age,hiredate FROM employee WHERE id = ?";

        List<Employee> list = jdbcTemplate.query(sql, new Object[]{id}, new RowMapper<Employee>() {
            public Employee mapRow(ResultSet rs, int i) throws SQLException {
                Employee e = new Employee();
                e.setId(rs.getLong("id"));
                e.setUsername(rs.getString("username"));
                e.setPassword(rs.getString("password"));
                e.setAge(rs.getInt("age"));
                e.setHiredate(rs.getDate("hiredate"));
                return e;
            }
        });

        return list.size() == 1 ? list.get(0) : null;
    }


    public List<Employee> listAll() {
    	String sql = "SELECT id,username,password,age,hiredate FROM employee";
        List<Employee> listAll = jdbcTemplate.query(sql, new Object[]{}, new RowMapper<Employee>() {
                    public Employee mapRow(ResultSet rs, int i) throws SQLException {
                        Employee e = new Employee();
                        e.setId(rs.getLong("id"));
                        e.setUsername(rs.getString("username"));
                        e.setPassword(rs.getString("password"));
                        e.setAge(rs.getInt("age"));
                        e.setHiredate(rs.getDate("hiredate"));
                        return e;
                    }
                });

        return listAll;
    }

    public Employee login(String username, String password) {

        String sql = "SELECT id,username,password,age,hiredate FROM employee WHERE username = ? AND password = ?";

        List<Employee> list = jdbcTemplate.query(sql, new Object[]{username, password}, new RowMapper<Employee>() {
            public Employee mapRow(ResultSet rs, int i) throws SQLException {
                Employee e = new Employee();
                e.setId(rs.getLong("id"));
                e.setUsername(rs.getString("username"));
                e.setPassword(rs.getString("password"));
                e.setAge(rs.getInt("age"));
                e.setHiredate(rs.getDate("hiredate"));
                return e;
            }
        });
        return list.size() == 1 ? list.get(0) : null;
    }
}

全局异常控制

/**
 * Description: 处理全局的异常,当发现异常,自动跳转到error.jsp
 *
 * @author zygui
 * @date 2020/3/7 10:21
 */

@ControllerAdvice
public class HandleExceptionAdviceController {

    //@ExceptionHandler(XxxException.class) // 对XxxException异常做处理
    @ExceptionHandler // 默认就是对Exception做处理
    public String error(Model model, Exception ex){
        model.addAttribute("errorMsg", ex.getMessage());
        return "/commons/error";
    }
}

5、web.xml


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    
    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>utf-8param-value>
        init-param>
        
        <init-param>
            <param-name>forceRequestEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
        <init-param>
            <param-name>forceResponseEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    
    <servlet>
        <servlet-name>springMVCservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        
        
        
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:springmvc-servlet.xmlparam-value>
        init-param>
        
        <load-on-startup>1load-on-startup>
    servlet>

    
    
    <servlet-mapping>
        <servlet-name>springMVCservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>

6、applicationContext.xml


<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:tx="http://www.springframework.org/schema/tx"

	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

	<context:annotation-config/>

	
	<context:property-placeholder location="classpath:db.properties" system-properties-mode="NEVER" />

	
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="initialSize" value="${jdbc.initialSize}" />
	bean>

	
	<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	bean>

	<tx:annotation-driven transaction-manager="txManager"/>

beans>

7、springmvc-servlet.xml


<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">

    <import resource="classpath:applicationContext.xml"/>

    
    <context:component-scan base-package="com.sunny"/>

    
    <mvc:default-servlet-handler />

    
    <mvc:annotation-driven/>

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/views/"/>
        
        <property name="suffix" value=".jsp"/>
    bean>
beans>

8、相关jsp页面

SpringMVC——CRUD操作_第1张图片
login.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录界面title>
head>
<body>
    <h3>登录界面h3>
    <form action="/login" method="post">
        账号:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        <input type="submit" value="登录"><br>
    form>

    <span style="color: red">${errorMsg}span>
    
    <%
        session.invalidate();
    %>
body>
html>

list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
    <span>恭喜${user_in_session.username}:登录成功span>
    <span style="color: blue"><a href="/login">注销a>span>
    <h3>员工列表h3>
    
    <a href="/employee/input">新增a>
    <table border="1" cellpadding="0" cellspacing="0" width="500">
        <tr>
            <th>IDth>
            <th>用户名th>
            <th>密码th>
            <th>入职时期th>
            <th>操作th>
        tr>

        <c:forEach items="${employees}" var="e">
            <tr>
                <td>${e.id}td>
                <td>${e.username}td>
                <td>${e.password}td>
                <td>${e.hiredate}td>
                <td>
                    <a href="/employee/delete?id=${e.id}">删除a>
                    <a href="/employee/input?id=${e.id}">编辑a>
                td>
            tr>
        c:forEach>
    table>
body>
html>

input.jsp(新增联系人)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<html>
<head>
    <title>Titletitle>
head>

<body>

    

    
	<h3>编辑员工h3>
    <form:form action="/employee/saveOrUpdate" modelAttribute="employee">
        <form:hidden path="id"/><br>
        账号:<form:input path="username"/>							<form:errors path="username" cssStyle="color: red"/><br>
        密码:<form:password path="password" showPassword="true"/> 	<form:errors path="password"
																				cssStyle="color: red"/> <br>
        年龄:<form:input path="age"/>								<form:errors path="age" cssStyle="color: red"/> <br>
        入职:<form:input path="hiredate"/><br>
        <input type="submit" value="保存"><br>
    form:form>
    
    <hr>

<%-- <c:forEach items="${errors}" var="error">
		<div style="color: red">${error.defaultMessage}div>
	c:forEach>
	<h3>编辑员工h3>
	<form action="/employee/saveOrUpdate" method="post">
		<input type="hidden" name="id" value="${employee.id}">
		账号:<input type="text" name="username" value="${employee.username}"><br>
		密码:<input type="password" name="password" value="${employee.password}"><br>
		年龄:<input type="text" name="age" value="${employee.age}"><br>
		入职:<input type="text" name="hiredate" value="${employee.hiredate}"><br>
		<input type="submit" value="保存">
	form>--%>
body>
html>

error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %>
<html>
<head>
    <title>错误页面title>
head>
<body>
    出错了:<%= exception%> <br>

    ${ex}<br>

    ${errorMsg}<br>

body>
html>

你可能感兴趣的:(SpringMVC)