springMVC: RestFul案例3

主要用于展示最后的代码。项目结构如下:

1. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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">

    <!--配置springMVC的编码过滤器-->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!--配置请求处理方式put和delete的HiddenHttpMethodFilter-->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!-- 配置SpringMVC的前端控制器,对浏览器发送的请求统一进行处理 -->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 如果不设置springMVC,那么它的配置文件的默认位置为WEB-INF,默认名称为<servlet-name>的值/Servlet.xml
          解释一下:一般Servlet的配置文件在web.xml里,现在引入了springMVC框架,那么配置文件需要在spring的配置文件中。 -->
        <!-- 通过初始化参数指定SpringMVC配置文件的位置和名称 -->
        <init-param>
            <!-- contextConfigLocation为固定值 -->
            <param-name>contextConfigLocation</param-name>
            <!-- 使用classpath确定springMVC的配置文件,这里起名为springMVC.xml。和(5)②建立的spring的xml的配置文件名称保持一致 -->
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
        <!--
            作为框架的核心组件,在启动过程中有大量的初始化操作要做
            而这些操作放在第一次请求时才执行会严重影响访问速度
            因此需要通过此标签将启动控制DispatcherServlet的初始化时间提前到服务器启动时
        -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <!--这name和上面那个servlet-name保持一致 -->
        <!--设置springMVC的核心控制器所能处理的请求的请求路径
            /所匹配的请求可以是/login或.html或.js或.css方式的请求路径
            但是/不能匹配.jsp请求路径的请求
            /* 代表所有请求-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

2. springMVC.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 自动扫描包 -->
    <context:component-scan base-package="com.atguigu.rest"/>

    <!-- 配置Thymeleaf视图解析器 -->
    <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>

    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>
    <mvc:view-controller path="/toAdd" view-name="employee_add"></mvc:view-controller>
    <!-- 开放对静态资源的访问 -->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>
    <!-- 开启mvc注解驱动-->
    <mvc:annotation-driven/>
</beans>

3. com.atguigu.rest下的java类

(1) bean - Employee

package com.atguigu.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() {
    }
}

(2) control - EmployeeControl

package com.atguigu.rest.controller;

import com.atguigu.rest.bean.Employee;
import com.atguigu.rest.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Collection;

@Controller
public class EmployeeController {
    @Autowired
    //自动装配:默认根据ByType,其次ByName。在IOC容器的范围内找到一个Bean来赋值
    //通过注解 + 扫描,IOC容器中就包含了EmployeeDao这个Bean,从而进行自动装配
    private EmployeeDao employeeDao;

    @RequestMapping(value="/employee", method = RequestMethod.GET)
    public String getAllEmployee(Model model){
        Collection<Employee> employeeList = employeeDao.getAll();
        //利用model向request域对象共享数据
        model.addAttribute("employeeList", employeeList);
        return "employee_list";
    }

    //这里由于有传进来的参数,因此在/employee后面需要有占位符{}来存储
    //然后利用@PathVariable注解,将占位符所表示的值与控制器函数内的形参进行绑定
    @RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
    public String deleteEmployee(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        return "redirect:/employee";
        //在删除结束后,回到展示表单的页面。先进入上一个控制器方法获取全部的志愿信息,让它再去展示表单
        //这里不采用转发,而是重定向。因为删除成功后,和之前的请求就没有关系了。
        //如果用转发,则地址栏中的地址还是现在的地址:/employee/{id}
        //重定向之后,地址栏中就会显示:/employee。相当于咱们自己在地址栏中输入了个地址去访问,默认为get请求
    }

    @RequestMapping(value = "/employee", method = RequestMethod.POST)
    public String addEmployee(Employee employee){
        //存储得到的Employee对象
        employeeDao.save(employee);
        return  "redirect:/employee";
    }

    @RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
    //由于需要将查询出的数据在请求域中共享,因此参数中有个model
    public String getEmployeeById(@PathVariable("id") Integer id, Model model){
        Employee employee = employeeDao.get(id);
        model.addAttribute("employee",employee);
        return "employee_update";
    }

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

(3) dao - EmployeeDao

package com.atguigu.rest.dao;

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

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

// Dao: 数据访问接口
// @Repository持久层注解
@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", "aa@163.com", 1));
        employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1));
        employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0));
        employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0));
        employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 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);
    }
}

4. html

(1) employee_add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>add employee</title>
</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<br>
           <input type="radio" name="gender" value="0">fmale<br>
    <input type="submit" value="add"><br>
</form>
</body>
</html>

(2) employee_list.html

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Employee Info</title>
</head>
<body>
    <table id="dataTable" border="1" cellspacing="0" cellpadding="0" style="text-align: center">
        <tr>
            <!-- colspan为合并列 -->
            <th colspan="5">Employee Info</th>
        </tr>
        <tr>
            <th>id</th>
            <th>lastname</th>
            <th>email</th>
            <th>gender</th>
            <th>options(<a th:href="@{/toAdd}">add</a>)</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 @click="deleteEmployee" th:href="@{'/employee/' + ${employee.id}}">delete</a>
                <!-- 方式二:分开相加
                    /employee后面的/是参数,而不是路径
                    <a th:href="@{/employee/} + ${employee.id}">delete</a>
                -->
                <a th:href="@{'/employee/' + ${employee.id}}">update</a>
            </td>
        </tr>
    </table>

    <!-- 此表单的提交通过上面delete的超链接来控制,因此不需要submit按钮 -->
    <form id="deleteForm" method="post">
        <input type="hidden" name="_method" value="delete">
    </form>

    <script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
    <script type="text/javascript">
        var vue = new Vue({
            el:"#dataTable",
            methods:{
                deleteEmployee:function(event){
                    //根据id获取Form表单
                    var deleteForm = document.getElementById("deleteForm");
                    //event对应:超链接按钮的超链接的点击事件
                    //event.target对应:触发事件的元素(这里为超链接)
                    //event.target.href对应:超链接的href属性
                    //即将触发点击事件的超链接的href属性赋值给表单的action
                    //触发的事件为delete,得到th:href="@{|/employee/| + ${employee.id}}并赋值给action
                    deleteForm.action = event.target.href
                    deleteForm.submit();    //提交表单
                    event.preventDefault(); //取消超链接的默认行为
                    //因此现在点击超链接,会取消默认行为,并提交表单
                    //由于这个表单的请求方式是post,且包含参数:_method
                    //就可以将该请求方式转换为:delete
                }
            }
        });
    </script>
</body>
</html>

(3) employee_update.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>update employee</title>
</head>
<body>
<form th:action="@{/employee}" method="post">
    <!-- 将请求方式变为put -->
    <input type="hidden" name="_method" value="put">
    <!-- 设置回显 -->
    <input type="hidden" name="id" th:value="${employee.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<br>
    <input type="radio" name="gender" value="0" th:field="${employee.gender}">fmale<br>
    <input type="submit" value="update"><br>
</form>
</body>
</html>

(4) index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<!--首页:在templates目录下,由视图前缀决定-->
<h1>首页</h1>
<!--超链接发送的请求类型为get请求-->
<a th:href="@{/employee}">查看员工信息</a>

</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值