9. SpringMVC-RESTful案例

RESTful案例

  • 一、准备工作
    • 1. 搭建环境
    • 2. 准备实体类
  • 二、功能清单
  • 三、具体功能:访问首页
    • 1. 配置view-controller
    • 2. 创建页面
  • 四、具体功能:查询所有员工数据
    • 1. 控制器方法
    • 2. 创建employee_list.html
  • 五、具体功能:删除
    • 1. 创建处理delete请求方式的表单
    • 2. 删除超链接绑定点击事件
    • 3. 控制器方法
    • 4. 开放对静态资源的访问
  • 六、具体功能:跳转到添加数据页面
    • 1. 配置view-controller
    • 2. 创建employee_add.html
    • 3. 控制器方法-执行保存
  • 七、具体功能:跳转到更新数据页面
    • 1. 修改超链接
    • 2. 控制器方法
    • 3. 创建employee_update.html
    • 4. 执行更新

一、准备工作

1. 搭建环境

  1. 创建maven工程,
    9. SpringMVC-RESTful案例_第1张图片
  2. 配置依赖 pom.xml

<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.0modelVersion>

    <groupId>com.znb.mvcgroupId>
    <artifactId>SpringMvc_restartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>warpackaging>

    <properties>
        <maven.compiler.source>15maven.compiler.source>
        <maven.compiler.target>15maven.compiler.target>
    properties>

    <dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.3.1version>
        dependency>

        
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-classicartifactId>
            <version>1.2.3version>
        dependency>

        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.1.0version>
            <scope>providedscope>
        dependency>

        
        <dependency>
            <groupId>org.thymeleafgroupId>
            <artifactId>thymeleaf-spring5artifactId>
            <version>3.0.12.RELEASEversion>
        dependency>

         dependencies>

project>
  1. 添加webapp模块
    9. SpringMVC-RESTful案例_第2张图片
  2. 配置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>forceResponseEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>characterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>


    
    <filter>
        <filter-name>hiddenHttpMethodFilterfilter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>hiddenHttpMethodFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <servlet>
        <servlet-name>dispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:springMVC.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>
  1. 在resources中创建springMVC.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    
    <context:component-scan base-package="com.znb.rest">context:component-scan>

    
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">

                        
                        <property name="prefix" value="/WEB-INF/templates/"/>

                        
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8" />
                    bean>
                property>
            bean>
        property>
    bean>
beans>

2. 准备实体类

  1. 创建实体类Employee
package com.znb.rest.bean;

public class Employee {
    private Integer id;
    private String lastName;

    private String email;
    //1 male, 0 female
    private Integer gender;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public Employee(Integer id, String lastName, String email, Integer gender) {
        super();
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.gender = gender;
    }

    public Employee() {
    }
}

  1. 创建EmployeeDao
package com.znb.rest.dao;

import com.znb.rest.bean.Employee;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Repository
public class EmployeeDao {
    private static Map<Integer, Employee> employees = null;

    static{
        employees = new HashMap<Integer, Employee>();

        employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1));
        employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1));
        employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0));
        employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0));
        employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 1));
    }

    private static Integer initId = 1006;

    public void save(Employee employee){
        if(employee.getId() == null){
            employee.setId(initId++);
        }
        employees.put(employee.getId(), employee);
    }

    public Collection<Employee> getAll(){
        return employees.values();
    }

    public Employee get(Integer id){
        return employees.get(id);
    }

    public void delete(Integer id){
        employees.remove(id);
    }
}

二、功能清单

功能 URL 地址 请求方式
访问首页√ / GET
查询全部数据√ /employee GET
删除√ /employee/2 DELETE
跳转到添加数据页面√ /toAdd GET
执行保存√ /employee POST
跳转到更新数据页面√ /employee/2 GET
执行更新√ /employee PUT

三、具体功能:访问首页

1. 配置view-controller

在springMVC.xml中添加

 <mvc:view-controller path="/" view-name="index">mvc:view-controller>
 
 <mvc:annotation-driven>mvc:annotation-driven>

2. 创建页面

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页title>
head>
<body>
<h1>首页h1>
<a th:href="@{/employee}">查看员工信息a>
body>
html>

四、具体功能:查询所有员工数据

1. 控制器方法

	@RequestMapping(value = "/employee" ,method = RequestMethod.GET)
    public String getEmployee(Model model){
        Collection<Employee> employeeList = employeeDao.getAll();
        model.addAttribute("employeeList",employeeList);
        return "employee_list";

    }

2. 创建employee_list.html

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>员工表title>
head>
<body>
<table id="dataTable" border="1" cellspacing="0" cellpadding="0" style="text-align: center">
    <tr>
        <th colspan="5">Employee Infoth>
    tr>
    <tr>
        <th>idth>
        <th>lastnameth>
        <th>emailth>
        <th>genderth>
        <th>options(<a th:href="@{/toAdd}">adda>)th>
    tr>
    <tr th:each="employee : ${employeeList}">
        <td th:text="${employee.id}">td>
        <td th:text="${employee.lastName}">td>
        <td th:text="${employee.email}">td>
        <td th:text="${employee.gender}">td>
        <td>
            <a href="">deletea>
            <a href="">updatea>
        td>
    tr>
table>

body>
html>

五、具体功能:删除

1. 创建处理delete请求方式的表单

<form id="deleteForm" method="post">
    <input type="hidden" name="_method" value="delete">
form>

2. 删除超链接绑定点击事件

  1. 引入vue.js
<script th:src="@{static/js/vue.js}">script>
  1. 删除方法的超链接
<a @click="deleteEmployee" th:href="@{/employee/} + ${employee.id}">deletea>
  1. 通过vue处理点击事件
<script>
    let vue = new Vue({
        el:"#dataTable",
        methods:{
            deleteEmployee:function (event){
                //根据id获取表单元素
                let deleteform = document.getElementById("deleteForm");
                deleteform.action = event.target.href
                //提交表单
                deleteform.submit();
                //取消超链接的默认行为
                event.preventDefault();
            }
        }
    });

script>

3. 控制器方法

	@RequestMapping(value = "/employee/{id}",method = RequestMethod.DELETE)
    public String deleteEmployee(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        //重定向
        return "redirect:/employee";
    }

4. 开放对静态资源的访问

在springMVC中添加-开放对静态资源的访问

	
    <mvc:default-servlet-handler>mvc:default-servlet-handler>

六、具体功能:跳转到添加数据页面

1. 配置view-controller

<mvc:view-controller path="/toAdd" view-name="employee_add">mvc:view-controller>

2. 创建employee_add.html

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>add employeetitle>
head>
<body>
<form th:action="@{/employee}" method="post">
  lastname: <input type="text" name="lastName"><br>
  email: <input type="text" name="email"><br>
  gender: <input type="radio" name="gender" value="1">male <input type="radio" name="gender" value="0">female<br>
  <input type="submit">
form>
body>
html>

3. 控制器方法-执行保存

	@RequestMapping(value = "/employee",method = RequestMethod.POST)
    public String addEmployee(Employee employee){
        employeeDao.save(employee);
        return "redirect:/employee";
    }

七、具体功能:跳转到更新数据页面

1. 修改超链接

<a th:href="@{/employee/}+${employee.id}">updatea>

2. 控制器方法

根据id查询信息的方法

@RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
public String getEmployeeById(@PathVariable("id") Integer id, Model model){
    Employee employee = employeeDao.get(id);
    model.addAttribute("employee", employee);
    return "employee_update";
}

3. 创建employee_update.html

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>update employeetitle>
head>
<body>
<form th:action="@{/employee}" method="post">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" th:value="${employee.id}" name="id">
  lastname: <input type="text" name="lastName" th:value="${employee.lastName}"><br>
  email: <input type="text" name="email" th:value="${employee.email}"><br>
  gender: <input type="radio" name="gender" value="1" th:field="${employee.gender}">male<input type="radio" name="gender" value="0" th:field="${employee.gender}">female<br>
    <input type="submit" value="update">
form>
body>
html>

4. 执行更新

	@RequestMapping(value = "/employee" ,method = RequestMethod.PUT)
    public String updateEmployee(Employee employee){
        employeeDao.save(employee);
        return "redirect:/employee";
    }

你可能感兴趣的:(#,spring-mvc,restful,java,spring)