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的写法:
随机推荐
- HDLBits答案——Verification: Writing Testbenches
1 clock module top_module ( ); reg clk; dut U1(.clk(clk)); initial begin clk = 0; end always begin # ...
- 基于k8s的CI/CD的实现
综述 首先,本篇文章所介绍的内容,已经有完整的实现,可以参考这里. 在微服务.DevOps和云平台流行的当下,使用一个高效的持续集成工具也是一个非常重要的事情.虽然市面上目前已经存在了比较成熟的自动化 ...
- php7怎么安装memcache扩展
php7安装memcache扩展 1.下载文件,解压缩 memcache windows php7下载地址: https://github.com/nono303/PHP7-memcache-dll ...
- JavaScript入门③-函数(2)原理{深入}执行上下文
00.头痛的JS闭包.词法作用域? 被JavaScript的闭包.上下文.嵌套函数.this搞得很头痛,这语言设计的,感觉比较混乱,先勉强理解总结一下. 为什么有闭包这么个东西?闭包包的是什么? 什么 ...
- Qwt开发笔记(一):Qwt简介、下载以及基础demo工程模板
前言 QWT开发笔记系列整理集合,这是目前使用最为广泛的Qt图表类(Qt的QWidget代码方向只有QtCharts,Qwt,QCustomPlot),使用多年,系统性的整理,本系列旨在系统解说并 ...
- Ubuntu20.04创建快捷方式(CLion)
打开命令行,创建在桌面上xxx.desktop文件 touch ~/Desktop/Clion.desktop 编辑desktop文件 [Desktop Entry] Encoding=UTF-8 N ...
- 配置 DosBox
配置 DosBox DosBox 在高分辨的屏幕上窗口很小. 修改分辨率 Win7 及以上配置文件位于{system drive}:\Users\{username}\AppData\Local\DO ...
- Pytorch 基本操作
Pytorch 基础操作 主要是在读深度学习入门之PyTorch这本书记的笔记.强烈推荐这本书 1. 常用类numpy操作 torch.Tensor(numpy_tensor) torch.from_ ...
- 聊一聊 SQLSERVER 的行不能跨页
一:背景 1. 讲故事 相信有很多朋友在学习 SQLSERVER 的时候都听说过这句话,但大多都是记忆为主,最近在研究 SQLSERVER,所以我们从 底层存储 的角度来深入理解下. 二:理解数据页 ...
- [OpenCV实战]14 使用OpenCV实现单目标跟踪
目录 1 背景 1.1 什么是目标跟踪 1.2 跟踪与检测 2 OpenCV的目标跟踪函数 2.1 函数调用 2.2 函数详解 2.3 综合评价 3 参考 在本教程中,我们将了解OpenCV 3中引入 ...