SpringMVC的类型转换器与RESTFUL集成
作者:互联网
pring 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配置
HiddenHttpMthodFilter
org.springframework.web.filter.HiddenHttpMethodFilter
HiddenHttpMthodFilter
/*
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"%>
Title
<c:forEach items="${list}" var="course"></tr> </c:forEach> </table> </body> </html>
编号 名称 价格 删除 ${course.id} ${course.name} ${course.price}
修改
-
<%-- 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>
标签:return,String,SpringMVC,id,course,import,转换器,RESTFUL,public 来源: https://www.cnblogs.com/HJZ114152/p/16406807.html