其他分享
首页 > 其他分享> > SpringMVC的类型转换器与RESTFUL集成

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(资源表现层状态转化)

优点:结构清晰,有统一的标准,扩展性好

基于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>
  1. 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已接受请求";
}

需求分析

代码实现

  1. 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

标签:return,String,SpringMVC,id,course,import,转换器,RESTFUL,public
来源: https://www.cnblogs.com/HJZ114152/p/16406807.html