SpringMVC使用RESTful接口案例详解

目录
  • 一、准备工作
  • 二、功能清单
  • 三、具体功能-访问首页

一、准备工作

和传统 CRUD 一样,实现对员工信息的增删改查。

①搭建环境

添加相关依赖

web.xml

springmvc.xml

②准备实体类

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() {
    }
}

③准备dao模拟数据

@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);
    }
}

二、功能清单

功能                                     URL地址                       请求方式

访问首页√                             /                                    GET

查询全部数据√                      /                                   employee GET

删除√                                    /                                   employee/2 DELETE

跳转到添加数据页面√           /                                   toAdd GET

执行保存√                             /                                   employee POST

跳转到更新数据页面√           /                                  employee/2 GET

执行更新√                             /                                  employee PUT

三、具体功能-访问首页

查询所有员工信息-->/employee-->get

跳转到添加页面-->/to/add-->get

新增员工信息-->/employee-->post

跳转到修改页面-->/employee/1-->get

修改员工信息-->/employee-->put

删除员工信息-->/employee--delete

配置默认的servlet处理静态资源

当前工程的web.xml配置的前端控制器DispatcherServlet的url-pattern是/

tomcat的web.xml配置的DefaultServlet的url-pattern也是/

此时,浏览器发送的请求会优先被DispatcherServlet进行处理,但是DispatcherServlet无法处理静态资源

若配置了<mvc:default-servlet-handler/>,此时浏览器发送的所有请求都会被DefaultServlet处理

若配置了<mvc:default-servlet-handler/>和<mvc:annotation-driven />

浏览器发送的请求会先被DispatcherServlet处理,无法处理再交给DefaultServlet处理

web.xml

    <!--配置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>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 配置SpringMVC的前端控制器,对浏览器发送的请求统一进行处理 -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 通过初始化参数指定SpringMVC配置文件的位置和名称 -->
        <init-param>
            <!-- contextConfigLocation为固定值 -->
            <param-name>contextConfigLocation</param-name>
            <!-- 使用classpath:表示从类路径查找配置文件,例如maven工程中的
            src/main/resources -->
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!--
        作为框架的核心组件,在启动过程中有大量的初始化操作要做
        而这些操作放在第一次请求时才执行会严重影响访问速度
        因此需要通过此标签将启动控制DispatcherServlet的初始化时间提前到服务器启动时
        -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <!--
        设置springMVC的核心控制器所能处理的请求的请求路径
        /所匹配的请求可以是/login或.html或.js或.css方式的请求路径
        但是/不能匹配.jsp请求路径的请求
        -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <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.xml

<!-- 自动扫描包 -->
    <context:component-scan base-package="com.atguigu"/>
    <!-- 配置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>
    <!--
        配置默认的servlet处理静态资源
        当前工程的web.xml配置的前端控DispatcherServlet的url - pattern是/
        tomcat的web.xml配置的DefaultServlet的url-pattern也是/
        此时,浏时器发送的请求会优先DispatcherServlet进行处理,但是DispatcherServlet无法处理静态资源
        若配置了<mvc:default-servlet-handler />,此时浏览器发送的所有请求都会越DispatcherServlet处理
        若配置了<mvc:default-servlet-handler />和<mvc:annotation-driven />
        浏览器发送的请求会先被DispatcherServlet.处理,无法处理在交给DefaultServlet处理
    -->
<!--    <mvc:default-servlet-handler></mvc:default-servlet-handler>-->
    <mvc:default-servlet-handler />
    <mvc:annotation-driven />
    <!--
        path:设置处理的请求地址
        view-name:设置请求地址所对应的视图名称
    -->
    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>
    <mvc:view-controller path="/to/add" view-name="employee_add"></mvc:view-controller>

employee_add.html

<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" value="add"><br>
</form>

employee_list.html

<table border="1" cellpadding="0" cellspacing="0" style="text-align:
center;" id="dataTable">
    <tr>
        <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="@{/to/add}" rel="external nofollow" >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 class="deleteA" @click="deleteEmployee"
               th:href="@{'/employee/'+${employee.id}}" rel="external nofollow"  rel="external nofollow" >delete</a>
            <a th:href="@{'/employee/'+${employee.id}}" rel="external nofollow"  rel="external nofollow" >update</a>
        </td>
    </tr>
</table>
<!-- 作用:通过超链接控制表单的提交,将post请求转换为delete请求 -->
<form id="delete_form" method="post">
    <!-- HiddenHttpMethodFilter要求:必须传输_method请求参数,并且值为最终的请求方式 -->
    <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: {
            //event表示当前事件
            deleteEmployee: function (event) {
                //通过id获取表单标签
                var delete_form = document.getElementById("delete_form");
                //将触发事件的超链接的href属性为表单的action属性赋值
                delete_form.action = event.target.href;
                //提交表单
                delete_form.submit();
                //阻止超链接的默认跳转行为
                event.preventDefault();
            }
        }
    });
</script>

employee_update.html

<form th:action="@{/employee}" method="post">
    <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>
    <!--
        th:field="${employee.gender}"可用于单选框或复选框的回显
        </body>
        </html>
        若单选框的value和employee.gender的值一致,则添加checked="checked"属性
    -->
    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"><br>

index.html

<h1>index.html</h1>
<a th:href="@{/user}" rel="external nofollow" >查询所有的用户信息</a><br>
<a th:href="@{/user/1}" rel="external nofollow" >查询用户id为1的信息</a><br>
<form th:action="@{/user}" method="post">
    <input type="submit" value="添加用户信息">
</form>
<form th:action="@{/user}" method="post">
    <input type="hidden" name="_method" value="put">
    <input type="submit" value="修改用户信息">
</form>
<form th:action="@{/user/5}" method="post">
    <input type="hidden" name="_method" value="delete">
    <input type="submit" value="删除用户信息">
</form>
<hr>
<a th:href="@{/employee}" rel="external nofollow" >查询所有的员工信息</a><br>

控制器方法

@Controller
public class EmployeeController {
    @Autowired
    private EmployeeDao employeeDao;
    @RequestMapping(value = "/employee", method = RequestMethod.GET)
    public String getAllEmployee(Model model) {
        Collection<Employee> employeeList = employeeDao.getAll();
        model.addAttribute("employeeList", employeeList);
        return "employee_list";
    }
    @RequestMapping(value = "/employee", method = RequestMethod.POST)
    public String addEmployee(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/employee";
    }
    @RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
    public String toUpdate(@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";
    }
    @RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
    public String deleteEmployee(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/employee";
    }
}

到此这篇关于SpringMVC使用RESTful接口案例详解的文章就介绍到这了,更多相关SpringMVC RESTful内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • SpringMVC RESTFul实战案例删除功能实现

    目录 SpringMVC RESTFul实现删除功能 一.修改列表前端代码 1. 修改删除的请求地址 2. 添加删除用的 form 表单 3. 删除超链接绑定点击事件 二.增加后端控制器 三.测试效果 SpringMVC RESTFul实现删除功能 删除相对麻烦一点,因为 Rest 中得用 delete 方法请求. 在前面已经提到如何实现 delete 和 put 方法请求了,这里同样借助表单来提交 post 请求,然后转成 delete 请求方法. 一.修改列表前端代码 1. 修改删除的请求地

  • SpringMVC通过RESTful结构实现页面数据交互

    目录 需求分析 环境准备 后台接口开发 页面访问处理 需求分析 需求一:图片列表查询,从后台返回数据,将数据展示在页面上 需求二:新增图片,将新增图书的数据传递到后台,并在控制台打印 说明:此次案例的重点是在SpringMVC中如何使用RESTful实现前后台交互,所以本案例并没有和数据库进行交互,所有数据使用假数据来完成开发. 我们的基本步骤: 搭建项目导入jar包 编写Controller类,提供两个方法,一个用来做列表查询,一个用来做新增 在方法上使用RESTful进行路径设置 完成请求.

  • SpringMVC RESTFul实战案例访问首页

    目录 SpringMVC RESTFul访问首页实现 一.新建 index.html 二.配置视图控制器 三.Idea 部署配置 SpringMVC RESTFul访问首页实现 一.新建 index.html 在 webapp\WEB-INF\templates 下新建首页 index.html. <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <

  • SpringMVC RESTFul实体类创建及环境搭建

    目录 一.搭建 mvc 环境 二.创建实体类 三.准备 dao 模拟数据 四.准备控制器 一.搭建 mvc 环境 新建一个 module 模块,创建 maven 工程,步骤跟以前一样,各种配置文件内容也可以拷贝修改一下即可. 二.创建实体类 新建个 bean 包,创建实体类 Employee: package com.pingguo.rest.bean; public class Employee { private Integer id; private String lastName; pr

  • SpringMVC RESTFul实现列表功能

    目录 SpringMVC RESTFul列表功能实现 一.增加控制器方法 二.编写列表页 employee_list.html 三.访问列表页 SpringMVC RESTFul列表功能实现 一.增加控制器方法 在控制器类 EmployeeController 中,添加访问列表方法. @Controller public class EmployeeController { @Autowired private EmployeeDao employeeDao; @RequestMapping(v

  • SpringMVC Restful风格与中文乱码问题解决方案介绍

    目录 基本要点 1.定义 2.传统方式与Restful风格的区别 3.如何使用Restful风格 4.为什么要用restful 5.乱码问题 基本要点 1.定义 根据百度百科的定义,RESTFUL是一种网络应用程序的设计风格和开发方式 2.传统方式与Restful风格的区别 在我们学习restful风格之前,我们请求接口,都是使用http://localhost:8080/controller?method=add这种方式携带接口所需要的参数 而调用restful风格的接口时,我们可以改成htt

  • SpringMVC RESTFul及REST架构风格介绍

    目录 一.RESTful 简介 二.RESTful 的实现 实践一下 1. get 和 post 请求 2. put 和 delete 请求 一.RESTful 简介 REST 是一种软件架构风格. REST:Representational State Transfer,表现层资源状态转移. 对此,有几个名字需要理解一下: 表现层:实际上就是前端的页面到后端的控制层. 资源:当应用部署到服务器上之后,万物皆资源,比如一个类.一个html页面等等. 1-资源是一种看待服务器的方式,即将服务器看作

  • SpringMVC使用RESTful接口案例详解

    目录 一.准备工作 二.功能清单 三.具体功能-访问首页 一.准备工作 和传统 CRUD 一样,实现对员工信息的增删改查. ①搭建环境 添加相关依赖 web.xml springmvc.xml ②准备实体类 public class Employee { private Integer id; private String lastName; private String email; //1 male, 0 female private Integer gender; public Integ

  • Spring Boot构建优雅的RESTful接口过程详解

    RESTful 相信在座的各位对于RESTful都是略有耳闻,那么RESTful到底是什么呢? REST(Representational State Transfer)表述性状态转移是一组架构约束条件和原则.满足这些约束条件和原则的应用程序或设计就是RESTful.需要注意的是,REST是设计风格而不是标准.REST通常基于使用HTTP,URI,和XML(标准通用标记语言下的一个子集)以及HTML(标准通用标记语言下的一个应用)这些现有的广泛流行的协议和标准. 也许这段话有些晦涩难懂,换个角度

  • SpringMVC框架整合Junit进行单元测试(案例详解)

    本文主要介绍在SpringMVC框架整合Junit框架进行单元测试.闲话少述,让我们直入主题. 系统环境 软件 版本 spring-webmvc 4.3.6.RELEASE spring-test 4.3.6.RELEASE junit 4.12 引入依赖 <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</ver

  • SpringMVC加载控制与Postmand的使用和Rest风格的引入及RestFul开发全面详解

    目录 前言 一.bean的加载控制 二.容器加载 1.createServletApplicationContext()方法 2.createRootApplicationContext()方法 3.getServletMappings()方法 三.PostMan的引入 1.发送GET请求 2.发送POST请求 3.中文乱码问题解决 四.Rest风格 1.REST简介 2.RESTful传参 3.RESTful简便形式(快速开发) 4.放行静态资源 前言 从繁到简是贯彻SSM学习过程的原始真解

  • 使用python flask框架开发图片上传接口的案例详解

    python版本:3.6+ 需要模块:flask,pillow 需求:开发一个支持多格式图片上传的接口,并且将图片压缩,支持在线预览图片. 目录结构: app.py编辑内容: from flask import Flask, request, Response, render_template from werkzeug.utils import secure_filename import os import uuid from PIL import Image, ExifTags app =

  • jQuery 跨域访问解决原理案例详解

    浏览器端跨域访问一直是个问题,多数研发人员对待js的态度都是好了伤疤忘了疼,所以病发的时候,时不时地都要疼上一疼.记得很久以前使用iframe 加script domain 声明.yahoo js util 的方式解决二级域名跨域访问的问题. 时间过得好快,又被拉回js战场时, 跨域问题这个伤疤又开疼了.好在,有jQuery帮忙,跨域问题似乎没那么难缠了.这次也借此机会对跨域问题来给刨根问底,结合实际的开发项目,查阅了相关资料,算是解决了跨域问题...有必要记下来备忘, 跨域的安全限制都是指浏览

  • Java Spring拦截器案例详解

    springmvc提供了拦截器,类似于过滤器,他将在我们的请求具体出来之前先做检查,有权决定接下来是否继续,对我们的请求进行加工. 拦截器,可以设计多个. 通过实现handlerunterceptor,这是个接口 定义了非常重要的三个方法: 后置处理 前置处理 完成处理 案例一: 通过拦截器实现方法耗时统计与警告 package com.xy.interceptors; import org.springframework.web.servlet.HandlerInterceptor; impo

  • SpringBoot实战之实现结果的优雅响应案例详解

    今天说一下 Spring Boot 如何实现优雅的数据响应:统一的结果响应格式.简单的数据封装. 前提 无论系统规模大小,大部分 Spring Boot 项目是提供 Restful + json 接口,供前端或其他服务调用,格式统一规范,是程序猿彼此善待彼此的象征,也是减少联调挨骂的基本保障. 通常响应结果中需要包含业务状态码.响应描述.响应时间戳.响应内容,比如: { "code": 200, "desc": "查询成功", "tim

  • SpringBoot实战之处理异常案例详解

    前段时间写了一篇关于实现统一响应信息的博文,根据文中实战操作,能够解决正常响应的一致性,但想要实现优雅响应,还需要优雅的处理异常响应,所以有了这篇内容. 作为后台服务,能够正确的处理程序抛出的异常,并返回友好的异常信息是非常重要的,毕竟我们大部分代码都是为了 处理异常情况.而且,统一的异常响应,有助于客户端理解服务端响应,并作出正确处理,而且能够提升接口的服务质量. SpringBoot提供了异常的响应,可以通过/error请求查看效果: 这是从浏览器打开的场景,也就是请求头不包括content

  • Spring集成Web环境与SpringMVC组件的扩展使用详解

    目录 一.Spring集成Web环境(解耦) 二.SpringMVC快速入门 三.SpringMVC的执行流程 四.SpringMVC组件解析 五.SpringMVC注解解析 六.SpringMVC组件扫描的扩展 七.SpringMVC的XML配置解析之视图解析器 一.Spring集成Web环境(解耦) 实际开发中,我们通常需要编写多个Web相关的Servlet的时候,如下 package com.kang.service; import org.springframework.context.

随机推荐