`

Spring Framework研究 RESTFUL

阅读更多
前言

参考文档 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
1  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);
    }

}
分享到:
评论

相关推荐

    Getting started with Spring Framework: covers Spring 5(epub)

    Getting started with Spring Framework (4th Edition) is a hands-on guide to begin developing applications using Spring Framework 5. The examples (consisting of 88 sample projects) that accompany this ...

    Apress.Introducing.Spring.Framework.A.Primer.

    This book is an introduction to the well-known Spring Framework that offers an inversion of control container for the Java platform. The Spring Framework is an open source application framework that ...

    org.springframework.web.jar

    在Java的Web开发领域,Spring框架是不可或缺的重要工具,其中`org.springframework.web.jar`文件是Spring框架的核心组成部分,主要用于处理Web应用程序的相关功能。这个JAR(Java Archive)文件包含了Spring Web模块...

    Spring Framework 4.1.3 API Documentation参考文档CHM版

    4.1.3版本中,Spring MVC加强了对RESTful风格的支持,增强了模板引擎的集成,以及提供了更灵活的模型绑定和验证机制。 4. **数据访问**:Spring提供了JDBC抽象层,简化了数据库操作,同时支持ORM(Object-...

    spring framework4.3.5所有lib文件

    Spring Framework是Java开发中不可或缺的一部分,它为构建高效、可测试和可维护的Java应用程序提供了强大的支持。在4.3.5版本中,这个框架继续提供了稳定性和性能的改进,同时也兼容了当时主流的Java环境和其他相关...

    官方源码 spring-framework-5.3.4.zip

    Spring的Web MVC框架为构建RESTful Web服务提供了强大支持。在5.3.4版本中,它增强了控制器的注解处理,改进了模型视图的交互,同时提供了更丰富的响应式编程功能,适应现代Web应用的需求。 6. **Spring Boot集成*...

    spring-framework-1.0-m2.zip

    《Spring Framework 1.0-m2深度解析》 Spring Framework,作为Java开发中不可或缺的开源框架,自其诞生以来...无论你是初学者还是经验丰富的开发者,深入研究Spring的历史都能帮助你更好地掌握这一工具,并从中受益。

    spring-framework-5.3.8

    5. **Web 模块**:Spring MVC 是 Spring 框架中的 Web 开发组件,提供了一个优雅的方式来构建 RESTful 风格的 Web 应用。5.3.8 版本可能包含了对 HTTP/2 和 WebSocket 的更全面支持,同时在处理请求和响应上进行了...

    spring-framework-5.3.20

    - **RESTful API**:Spring MVC提供了一套完整的解决方案,用于构建RESTful风格的Web服务。 - **数据库操作**:Spring Data支持多种持久层技术,简化了数据库操作。 - **分布式事务**:Spring的事务管理功能,确保跨...

    spring-framework-5.3.23 源码

    此外,Spring还提供了对WebSocket、RESTful API、JSON序列化和反序列化的支持,以满足现代Web应用程序的需求。Spring Boot简化了Spring应用程序的启动和配置,而Spring Cloud则为微服务架构提供了工具和服务发现、...

    spring-framework-3.2.4-RELEASE Maven Source Code

    - **IoC容器**:深入研究`org.springframework.beans`和`org.springframework.context`包,可以理解Spring如何通过XML或注解实现依赖注入。 - **AOP实现**:在`org.springframework.aop`包中,可以看到Spring如何...

    spring framework离线文档

    3. **Spring MVC**:Spring的Web MVC框架提供了一种用于构建RESTful Web服务和Web应用的模型-视图-控制器架构。它支持多种视图技术,如JSP、Thymeleaf等。 4. **数据访问**:Spring支持多种数据存取技术,包括JDBC...

    springframework2.5源代码

    以上这些知识点都是Spring Framework 2.5源代码中涉及的关键领域,通过深入研究源码,开发者不仅可以理解Spring的工作原理,还能学习到优秀的设计模式和编程实践。对于想要深入了解Spring框架的人来说,分析这些源...

    Spring Framework 概述 + Spring从入门到精通

    例如,你可以从创建一个简单的Spring Boot应用开始,配置一个RESTful API,然后逐渐引入Spring MVC和Spring Data,实现数据库操作。随着深入,可以学习如何使用AOP来编写拦截器,或者利用Spring Security实现权限...

    官方原版源码spring-framework-5.1.4.RELEASE.zip

    《Spring Framework 5.1.4源码深度解析》 Spring Framework是Java开发中的核心框架,它为构建高质量的企业级应用提供了全面的支持。5.1.4版本是Spring的重要里程碑,引入了诸多新特性和改进,旨在提升性能、增强可...

    spring-framework-4-reference_spring-framework-4_中文翻译_

    3. **Spring MVC**:Spring的Model-View-Controller(MVC)框架提供了构建Web应用程序的完整解决方案,支持RESTful风格的URL设计,便于构建高性能、灵活的应用。 4. **数据访问集成**:Spring提供了对各种数据库的...

    官方原版完整包 spring-framework-5.3.1.RELEASE.zip

    借助Spring MVC开发RESTful API,构建健壮的Web服务;还可以通过Spring Boot简化配置,快速启动项目。 总之,Spring Framework 5.3.1 是一个全面且强大的框架,旨在提高开发效率,促进代码的可维护性和可测试性。...

    spring-framework-4.1.6.RELEASE

    Spring Framework 4.1.6.RELEASE 是一个重要的版本,它是Spring框架发展史上的一个重要里程碑。这个版本在2015年发布,为开发者提供了稳定、高性能和丰富的特性集,以便构建高质量的企业级Java应用程序。以下是对这...

    官方原版完整包 spring-framework-5.3.3.RELEASE.zip

    Spring MVC是Spring框架的一部分,提供了一种用于构建Web应用的MVC(Model-View-Controller)模式实现,支持RESTful风格的URL设计和数据绑定。 **spring-5.3.3-docs.zip** 包含了Spring框架的官方文档,这对于学习...

    SpringFrameWork_file

    Spring Framework还包含了许多其他模块,如Spring Batch用于批处理操作,Spring Integration支持企业服务总线(ESB)和企业应用集成,Spring Web Services提供SOAP和RESTful服务的支持。 总的来说,Spring ...

Global site tag (gtag.js) - Google Analytics