Spring Framework研究(一)RESTFUL

2023-11-04

前言

参考文档 Spring Framework Reference Documentation

   http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/

   spring.io/guides/gs/rest-service/

   http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch18s02.html

Spring Framework研究(一)RESTFUL

注:本文仅限于Spring MVC & RESTFUL于实际应用,如果想学习 RESTFUL,请参考书籍:RESTful+Web+Services+Cookbook-cn.pdf、RESTFUL WEB SERVICES 中文版.pdf

RESTFUL  HTTP服务发送地址标准

/user/     HTTP GET  => 查询所有的用户信息列表 

/user/1   HTTP GET  => 查询ID = 1 的用户信息

/user      HTTP  POST => 新增用户信息

/user/1   HTTP  PUT => 更新ID = 1 用户

/user/1  HTTP  DELETE  =>删除ID = 1 用户

/user/    HTTP  DELETE  =>删除数组IDS系列用户


JAVA 控制层Action:

@Controller
@RequestMapping(value = "/user")
public class UserController {

   @ResponseBody
    @RequestMapping(method = RequestMethod.GET)
    public Map<String, Object> list(
            @RequestParam(value = "start", defaultValue = "0", required = true) Integer start,
            @RequestParam(value = "limit", defaultValue = "0", required = true) Integer limit,
            @RequestParam(value = "name", defaultValue = "", required = false) String name){
        return null;
    }
    
    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Map<String, Object> list(
            @PathVariable("id") Integer id ){
        return null;
    }


    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public Map<String, Object> add(
            @Valid @RequestBody  UserVO vo){
        return null;
    }

 

    @ResponseBody
    @RequestMapping( value = "/{id}",  method = RequestMethod.PUT)
    public Map<String, Object> updateUser(
            @PathVariable("id") Integer id,
            @Valid @RequestBody UserVO vo){
        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Map<String, Object> delete(@PathVariable("id") Integer id){
        return ModelMapper.success();
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE)
    public Map<String, Object> delete(@RequestBody String[] ids){
        return null;
    }

}//end  class UserController

   注:删除系列用户时,前台IDS JSON格式:

var  ids = [];

for ( var i = 0; i < 5; i++) {

ids.push(i);
}

AJAX:

$.ajax({

  type : 'DELETE',

 url : 'user/',
 contentType : "application/json; charset=utf-8",
  data:JSON.stringify(ids),
  dataType : "json"

}

2    SPring 3.2 RESTFUL  Annotation introduce


package hello;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


@ComponentScan:The @ComponentScan annotation tells Spring to search recursively through the hello package and its children for classes marked 
directly or indirectly with Spring's @Component annotation.This directive ensures that Spring finds and registers the GreetingController, 
because it is marked with @Controller, which in turn is a kind of @Component annotation. 

@Controller
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @ResponseBody
    @RequestMapping("/greeting")
    public Greeting greeting(
            @RequestParam(value="name", required=false, defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}


@Controller:In Spring's approach(Method) to building RESTful web services, HTTP requests are handled by a controller. These components are 
easily identified  by the @Controller annotation

@ResponseBody:To accomplish this, the @ResponseBody annotation on the greeting() method tells Spring MVC that it does not need to render 
the greeting object through a server-side view layer, but that instead that the greeting object returned is the response body, and should 
be written out directly.

@RequestMapping:The @RequestMapping annotation ensures that HTTP (specify GET vs. PUT, POST)requests to /greeting are mapped to the
greeting() method.@RequestMapping maps all HTTP operations by default. Use @RequestMapping(method=GET) to narrow(精密的) this mapping(映像)

@RequestBody:The @RequestBody method parameter  annotation is used to indicate that a method parameter should be bound  to the value of the 
HTTP request body. For example,
@RequestMapping(value = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
  writer.write(body);
}

@PathVariable:Spring uses the @RequestMapping method annotation to define the URI Template for the request. The @PathVariable annotation
is used to extract the value of the template variables and assign their value to a method variable. A Spring controller method to
process above example is shown below;
@RequestMapping("/users/{userid}", method=RequestMethod.GET)
public String getUser(@PathVariable String userId) {
  // implementation omitted...
}

@RequestParam:it binds the value of the query string parameter name into the name parameter of the greeting() method. This query string
parameter is not required; if it is absent(缺少) in the request, the defaultValue of "World" is used.

Note:A key difference between a traditional MVC controller and the RESTful web service controller above is the way that the HTTP response
body is created
. Rather than relying on a view technology to perform server-side rendering渲染 of the greeting data to HTML, this RESTful web
service controller simply populates and returns a Greeting object. The object data will be written directly to the HTTP response as JSON.

And The Greeting object must be converted to JSON. Thanks to Spring's HTTP message converter support, you don't need to do this conversion
manually. Because Jackson 2 is on the classpath, Spring's MappingJackson2HttpMessageConverter is automatically chosen to convert the Greeting
instance to JSON. configuration The Spring Json Convert Auto Like :/项目/WebContent/WEB-INF/spring/app-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    <context:component-scan base-package="com.test.company.web" />
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="objectMapper">
                        <bean class="com.test.security.MyObjectMapper">                            <property name="dateFormat">                                <bean class="java.text.SimpleDateFormat">                                    <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />                                </bean>                            </property>                        </bean>                    </property>                </bean>        </mvc:message-converters>    </mvc:annotation-driven>    <mvc:default-servlet-handler/></beans>

com.test.security.MyObjectMapper:
public class MyObjectMapper extends ObjectMapper {

    private static final long serialVersionUID = 1L;

    public MyObjectMapper() {

        SimpleModule sm = new SimpleModule("sm");
        sm.addSerializer(String.class, new JsonSerializer<String>() {
            @Override
            public void serialize(String value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
                // 防止XSS
                jgen.writeString(HtmlUtils.htmlEscape(value));
            }
        });
        // 当JSON转Java对象时忽略JSON中存在而Java对象中未定义的属性
        configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        registerModule(sm);
    }

}



本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Framework研究(一)RESTFUL 的相关文章

随机推荐

  • 关于Qt下中静态变量的使用

    需求是这样的 在主窗口类Widget中启动一个子线程去执行录音操作 然后使用共享的静态变量来结束录音 在Widget类中发出停止命令 MyThread类则停止录音操作 status定义 class MyThread public QObje
  • SparkStreaming从kafka消费数据

    val spark SparkSession builder master local appName myKafka getOrCreate 5秒一个窗口 val ssc new StreamingContext spark sparkC
  • ES6中数组首尾两端和中间添加/移除数据方法

    1 push 尾端插入 返回数组长度 let arr 1 hello true console log arr push 22 4 console log arr arr 1 hello true 22 console log arr pu
  • C++11中头文件atomic的使用

    原子库为细粒度的原子操作提供组件 允许无锁并发编程 涉及同一对象的每个原子操作 相对于任何其他原子操作是不可分的 原子对象不具有数据竞争 data race 原子类型对象的主要特点就是从不同线程访问不会导致数据竞争 因此从不同线程访问某个原
  • 结构体内存对齐及结构体大小计算,位域计算

    1 什么是结构体内存对齐 结构体内存对齐是指在编程语言中 为了提高内存访问效率和性能 将结构体的成员按照特定规则进行排列 保证每个成员在内存中的起始地址符合特定的对齐要求 2 为什么要结构体内存对齐 网上的文章都是说这两个原因 1 平台原因
  • C++——指针作为参数传递

    C 指针作为参数传递 在写这一篇之前 受到了两个博主两篇博文 博文1 博文2 的启发 对指针作为参数传递时 有了很大的启发 所以在看完之后并把自己的感悟写出来 对于指针的变化作了更详细的讲解 1 指针作为参数传递时 是值传递不是引用传递 2
  • 设置ipv4固定ip

    选择 打开 网络和Intemet 设置 点击进入之后 选择 更改适配器选项 选择需要设置的网络 右击选择 属性 选择 Interent协议版本4 TCP IPv4 选择 属性 cmd输入ipconfig查看当前的IP信息 选择 使用下面IP
  • shinblink HX711称重/形变/压力测量

    HX711称重 形变 压力测量 一 本例程实现功能 二 基本概念 三 接线图 五 完整代码 六 代码运行结果 一 本例程实现功能 Core通过HX711差分电压采集模块测量电桥式传感器输出的差分电压AD值 并通过print 函数在电脑串口调
  • SQLi LABS Less 26a 联合注入+布尔盲注

    第26a关是单引号 括号的字符型注入 后台过滤了关键字 and or 注释 空格 这篇文章提供联合注入 布尔盲注 两种解题方式 SQLi LABS其他关卡可以参考 SQLi LABS 靶场通关教程 一 功能分析 这关是一个查询功能 地址栏输
  • 多播路由技术

    什么是多播转发树 用图论术语描述从特定源节点到多播组的所有成员的一组路径 这些路径定义了图论中的树 tree 是不含任何回路的图 即一个路由器不会在一条路径上出现两次或两次以上 有时也称为转发树 每个多播路由器对应于树中的一个结点 连接两个
  • LeetCode 1603. 设计停车系统

    题目链接 1603 设计停车系统 class ParkingSystem public vector
  • 九、UI系统

    目录 血条 Health Bar 的预制设计 设计过程 1 使用 IMGUI 2 使用 UGUI 两种实现的优缺点 IMGUI UGUI 效果展示 血条 Health Bar 的预制设计 血条 Health Bar 的预制设计 具体要求如下
  • Azure RTOS定价(ThreadX 等)

    Azure RTOS定价 Azure RTOS定价 https azure microsoft com zh cn pricing details rtos 使嵌入式 IoT 开发和连接变得轻松 Azure RTOS 是一种易于使用 经过市
  • 史上最简单详细的Hadoop完全分布式集群搭建

    一 安装虚拟机环境 Vmware12中文官方版 链接 https pan baidu com s 1IGKVfaOtcFMFXNLHUQp41w 提取码 6rep 激活秘钥 MA491 6NL5Q AZAM0 ZH0N2 AAJ5A 这个安
  • Kettle实例-数据检验-数据规范化处理

    1 使用Kettle工具 创建一个转换data validation 并添加 自定义常量数据 控件 计算器 控件 数据检验 控件 空操作 控件以及Hop跳连接线 2 双击 自定义常量数据 控件 进入 自定义常量数据 界面配置实验用数据 单击
  • Ubuntu-安装JDK

    1 检查安装JDK没有 java version 如果你看到像下面的输出 这就意味着你并没有安装过Java The program java can be found in the following packages default jr
  • centos7开启ssh 22端口

    查看是否安装ssh rpm qa grep ssh yum install openssh server 安装ssh 开启ssh service sshd start netstat ntpl grep 22 查看端口是否打开 设置自动开启
  • CSS样式--盒模型(四)

    CSS样式 盒模型 四 前言 css盒模型是创建css布局基础 其中最主要的就是padding和margin了 盒模型图解如下 可通过谷歌浏览器的调试工具查看元素的盒模型 鼠标悬浮上去可查看对应的padding border等值 框属性 1
  • 质数判断程序

    include
  • Spring Framework研究(一)RESTFUL

    前言 参考文档 Spring Framework Reference Documentation http docs spring io spring docs 3 2 x spring framework reference html s