SpringMVC的类型转换器与RESTFUL集成
Spring Mvc自定义的数据类型转换器:
一:Date
1.创建DateConverter 类,并实现Converter接口:需要指定泛型<S,T>
package com.southwind.converter;
import lombok.SneakyThrows;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter implements Converter<String, Date> {
private String pattern;
public DateConverter(String pattern){
this.pattern=pattern;
}
@Override
public Date convert(String s) {
SimpleDateFormat simpleDateFormat =new SimpleDateFormat(this.pattern);
try {
return simpleDateFormat.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
2.配置springMvC
<mvc:annotation-driven conversion-service="conversionService">
<!-- 消息转换器-->
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=utf-8"></property>
</bean>
<!-- fastjson-->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 消息转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.southwind.converter.DateConverter">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg>
</bean>
</list>
</property>
</bean>
3.控制器:
package com.southwind.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.xml.crypto.Data;
import java.util.Date;
@Controller
public class ControverHandler {
@RequestMapping("/date")
@ResponseBody
public String date(Date date){
return date.toString();
}
}
二:实体类;
转换器:
package com.southwind.converter;
import com.southwind.entity.Student;
import org.springframework.core.convert.converter.Converter;
public class StudentConverter implements Converter<String, Student> {
@Override
public Student convert(String s) {
String[] args=s.split("-");
Student student =new Student();
student.setId(Integer.parseInt(args[0]));
student.setName(args[1]);
student.setAge(Integer.parseInt(args[2]));
return student;
}
}
配置:
<!-- 消息转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.southwind.converter.DateConverter">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg>
</bean>
<bean class="com.southwind.converter.StudentConverter">
</bean>
</list>
</property>
</bean>
控制器:
@RequestMapping("/student")
@ResponseBody
public String student(Student student, HttpServletResponse response){
response.setCharacterEncoding("utf-8");
return student.toString();
}
Spring mvc 的RESTful集成
RESTful是当前比较流行的互联网架构模型,通过统一的规范来完成不同端的数据访问和交互,RESTful(资源表现层状态转化)
优点:结构清晰,有统一的标准,扩展性好
Resources
资源是指网路中的某个具体文件,可以是文件、图片、视频、音频等,是网路中真实存在的一个实体。
获取它:可以通过统一资源定位负找到这个实体,URL,每个资源都有一个特定的URL,通过URL就可以找到一个具体的资源
Pepersentation
资源表现层,资源的具体表现层次,例如一段文字、可以用TXT、HTML、XML、JSON、等不同的形式来描述它。
State Transfer
状态转化是指客户端和服务器之间的数据交互,因为HTTP请求不能传输数据的状态,所有的状态都保存在服务器端,如果客户端希望访问到服务器的数据,就需要使其发生状态改变,同时这种状态的改变是建立在表现层上的。
RESTful的特点:
1.URL传递参数更加简洁
2.完成不同总端之间的资源共享,RESTful提供了一套规范,不同的终端之间只需要遵守规范,就可以实现数据的交互
RESTful四中表现类型,
HTTP中的:
- GET 获取资源
- POST创建资源
- PUT修改资源
- DELETE删除资源
基于RESTful的方式,增删改查分别操作使用不同的HTTP请求来访问。
传统的from表单只支持GET和POST
解决方法:
添加HiddenHttpMeethodFilter过滤器将POST转化为PUT或DELETE
HiddenHttpMeethodFilter实现原理:
HiddenHttpMeethodFilter检测请求的参数是否包含_method参数,如果包含则取出它的值,并且判断它的请求类型之后完成请求的类型的转换,然后继续传递。
实现步骤
1.在from表单中加入隐藏域的标签,name为_method,value为DELETE/PUT
<%--
Created by IntelliJ IDEA.
User: 郝泾钊
Date: 2022-04-07
Time: 14:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/update" method="post">
<input type="hidden" name="_method" value="PUT">
<input type="submit" value="提交">
</form>
<form action="/delete" method="post">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="DELETE提交">
</form>
</body>
</html>
web.xml配置
<filter>
<filter-name>HiddenHttpMthodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMthodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.控制器
@PutMapping("/update")
@ResponseBody
public String update(){
return "PUT已接受到请求";
}
@DeleteMapping("/delete")
public String delete(){
return "DELETE已接受请求";
}
需求分析
- 添加课程,成功返回全部课程信息
- 查询课程,通过id查找课程
- 修改课程,成功返回全部的课程信息
- 删除课程,成功返回删除之后的全部课程信息
代码实现
- JSP
- 添加课程
- 修改课程
- 课程展示
2.Course实体类
package com.southwind.entity;
import lombok.Data;
@Data
public class Course {
private Integer id;
private String name;
private Double prive;
}
3.CourseRepository
package com.southwind.respository;
import com.southwind.entity.Course;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@Repository
public class CourseRepository {
private Map<Integer, Course> courseMap;
public CourseRepository(){
courseMap=new HashMap<>();
courseMap.put(1,new Course(1,"java基础",Double.parseDouble("500")));
courseMap.put(2, new Course(2, "java高级", Double.parseDouble("500")));
courseMap.put(3, new Course(3, "企业级框架", Double.parseDouble("500")));
}
public Collection<Course> findAll(){
return courseMap.values();
}
public Course findById(Integer id){
return courseMap.get(id);
}
public void saveOrupdate(Course course){
courseMap.put(course.getId(),course);
}
public void delete (Integer id){
courseMap.remove(id);
}
}
4.CourseController:
package com.southwind.controller;
import com.southwind.entity.Course;
import com.southwind.respository.CourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/course")
public class CourseController {
@Autowired
private CourseRepository courseRepository;
@PostMapping("/save")
public String save(Course course){
courseRepository.saveOrupdate(course);
return "redirect:/course/findAll";
}
@GetMapping("/findAll")
public ModelAndView findAll(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
modelAndView.addObject("list",courseRepository.findAll());
return modelAndView;
}
@DeleteMapping("/delete/{id}")
public String deleteById(@PathVariable("id")Integer id){
courseRepository.delete(id);
return "redirect:/course/findAll";
}
@GetMapping("/findById/{id}")
public ModelAndView findById(@PathVariable("id") Integer id){
ModelAndView modelAndView =new ModelAndView();
modelAndView.setViewName("edit");
modelAndView.addObject("course",courseRepository.findById(id));
return modelAndView;
}
@PutMapping("/update")
public String update(Course course){
courseRepository.saveOrupdate(course);
return "redirect:/course/findAll";
}
}
4.jsp
首页(查询和删除修改)
<%--
Created by IntelliJ IDEA.
User: 郝泾钊
Date: 2022-04-07
Time: 10:50
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isELIgnored="false"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<table>
<tr>
<td>编号</td>
<td>名称</td>
<td>价格</td>
<td>删除</td>
</tr>
<c:forEach items="${list}" var="course">
<tr>
<td>${course.id}</td>
<td>${course.name}</td>
<td>${course.price}</td>
<td>
<form action="/course/delete/${course.id}" method="post">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="删除" >
</form>
<a href="/course/findById/${course.id}">修改</a>
</td> </tr>
</c:forEach>
</table>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: 郝泾钊
Date: 2022-04-07
Time: 15:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/course/update" method="post">
<input type="hidden" name="_method" value="PUT">
<table>
<tr>
<td>编号:</td>
<td><input type="text" name="id" readonly value="${course.id}"></td>
</tr>
<tr>
<td>名称:</td>
<td><input type="text" name="name" value="${course.name}"></td>
</tr>
<tr>
<td>价格:</td>
<td><input type="text" name="price" value="${course.price}"></td>
</tr>
<tr>
<td><input type="submit" value="修改"></td>
</tr>
</table>
</form>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: 郝泾钊
Date: 2022-04-07
Time: 15:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/course/save" method="post">
<table>
<tr>
<td>课程编号</td>
<td><input type="text" name="id"></td>
</tr>
<tr>
<td>课程名称</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>课程价格</td>
<td><input type="text" name="price"></td>
</tr>
<tr>
<td><input type="submit" value="提交"></td>
<td><input type="reset" value="重置"></td>
</tr>
</table>
</form>
</body>
</html>
SpringMVC的类型转换器与RESTFUL集成的更多相关文章
- SpringMVC自定义类型转换器
SpringMVC 自定义类型转换器 我们在使用SpringMVC时,常常需要把表单中的参数映射到我们对象的属性中,我们可以在默认的spring-servlet.xml加上如下的配置即可做到普通数据 ...
- 《SpringMVC从入门到放肆》十二、SpringMVC自定义类型转换器
之前的教程,我们都已经学会了如何使用Spring MVC来进行开发,掌握了基本的开发方法,返回不同类型的结果也有了一定的了解,包括返回ModelAndView.返回List.Map等等,这里就包含了传 ...
- 14.SpringMVC核心技术-类型转换器
类型转换器 在前面的程序中,表单提交的无论是 int 还是 double 类型的请求参数,用于处理该请求 的处理器方法的形参, 均可直接接收到相应类型的相应数据,而非接收到 String 再手工转换. ...
- springmvc——自定义类型转换器
一.什么是springmvc类型转换器? 在我们的ssm框架中,前端传递过来的参数都是字符串,在controller层接收参数的时候springmvc能够帮我们将大部分字符串类型的参数自动转换为我们指 ...
- SpringMVC 自定义类型转换器
先准备一个JavaBean(Employee) 一个Handler(SpringMVCTest) 一个converters(EmployeeConverter) 要实现的输入一个字符串转换成一个emp ...
- springmvc的类型转换器converter
这个convter类型转换是器做什么用的? 他是做类型转换的,或者数据格式化处理.可以把数据在送到controller之前做处理.变成你想要的格式或者类型.方便我们更好的使用. 比如说你从前台传过来一 ...
- SpringMVC类型转换器、属性编辑器
对于MVC框架,参数绑定一直觉得是很神奇很方便的一个东西,在参数绑定的过程中利用了属性编辑器.类型转换器 参数绑定流程 参数绑定:把请求中的数据,转化成指定类型的对象,交给处理请求的方法 请求进入到D ...
- SSM-SpringMVC-28:SpringMVC类型转换之自定义日期类型转换器
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 例子很简易,要明白的是思路,话不多说,开讲 上篇博客不是说springmvc默认的日期转换格式是yyyy/M ...
- springmvc中的类型转换器
在使用springmvc时可能使用@RequestParam注解或者@RequestBody注解,他们的作用是把请求体中的参数取出来,给方法的参数绑定值. 假如方法的参数是自定义类型,就要用到类型转换 ...
- springmvc 类型转换器 数据回显及提示信息
处理器的写法: 类型转换器的写法: 类型转换器在springmvc.xml中的配置如下: index.jsp的写法:
随机推荐
- 【Java并发011】原理层面:CAS操作全解析
一.前言 volatile关键字是Java51个关键字中用的比较少的一个,它是一个与多线程并发的关键字,但是实际开发中,一般不会用到,使用synchronize+wait()+notify()/not ...
- PDF、视频格式缩略图获取(pdf2img)
PDF.视频格式缩略图获取(pdf2img) 获取pdf缩略图 导入依赖: <dependency> <groupId>org.apache.pdfbox</groupI ...
- javaSE--核心之一:IO流
Java IO流框架结构: IO的主要内容包括输入.输出两种IO流,这两种流中又分为字节流和字符流,字节流是以字节为单位来处理输入.输出流,而字符流是以字符为单位来处理输入.输出流. InputStr ...
- Clickhouse表引擎之MergeTree
1.概述 在Clickhouse中有多种表引擎,不同的表引擎拥有不同的功能,它直接决定了数据如何读写.是否能够并发读写.是否支持索引.数据是否可备份等等.本篇博客笔者将为大家介绍Clickhouse中 ...
- JDBC Request 中 Variable names 以及 Result variable name 的使用方法
1.Variable name 的使用方法 设置好JDBC Connection Configuration.JDBC Request 具体配置百度 如果数据库查询的结果不止一列那就在Variabl ...
- 推荐一款采用 .NET 编写的 反编译到源码工具 Reko
今天给大家介绍的是一款名叫Reko的开源反编译工具,该工具采用C#开发,广大研究人员可利用Reko来对机器码进行反编译处理.我们知道.NET 7 有了NativeAOT 的支持,采用NativeAOT ...
- 【Zookeeper】结构、应用、安装部署与参数、客户端命令行操作、API应用、内部原理(选举机制、写数据、监听器)
一.Zookeeper入门 1.概述 分布式服务管理框架(存储和管理数据) Zookeeper=文件系统+通知机制 2.特点 主从集群 半数以上,正常工作 请求顺序执行 数据更新具有原子性 3.数据结 ...
- 【大数据面试】Hbase:数据、模型结构、操作、读写数据流程、集成、优化
一.概述 1.概念 分布式.可扩展.海量数据存储的NoSQL数据库 2.模型结构 (1)逻辑结构 store相当于某张表中的某个列族 (2)存储结构 (3)模型介绍 Name Space:相当于数据库 ...
- GitHub 开源了多款字体「GitHub 热点速览 v.22.48」
本期 News 快读有 GitHub 官方大动作一下子开源了两款字体,同样大动作的还有 OpenAI 发布的对话模型 ChatGPT,引燃了一波人机对话. 项目这块,也许会成为新的 Web 开发生产力 ...
- layui table 表头抖动
原本table超出页面宽度(即table有横向滚动条)的情况下,缩放页面然后再设置定时器定时更新表单,会发现数据不变的时候table头部会左右抖动 而且th td比设置的minWidth 或者cell ...