`

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

    SingleJDBCBase 基于Spring Framework基础上搭建的一个Java基础开发套件

    SingleJDBCBase 是基于Spring Framework基础上搭建的一个Java基础开发套件,以Spring MVC为模型视图控制器,JDBC为数据访问层。 * 核心框架:Spring Framework 4.2.7 * 安全框架: * 视图框架:Spring MVC 4.2.7 * ...

    Getting.started.with.Spring.Framework.2nd.Edition1491011912.epub

    Getting started with Spring Framework is a hands-on guide to begin developing applications using Spring Framework. This book is meant for Java developers with little or no knowledge of Spring ...

    spring-framework-learning:Spring Framework从零开始学习

    您还将了解Spring框架功能,例如Spring Boot,Spring容器,控制和依赖注入的反转,百里香,MyBatis数据访问,RESTful Web服务,RESTFul客户端,Spring Security,Spring Schedule等。 目标 了解Java Spring框架以...

    spring-framework-reference 3.0

    全新的Spring 3.0提供了全面的RESTful Web服务支持,以及一个新的表达式语言。其tc服务器此次也提供了全新的开发者版本,可以免费供开发者下载,用于调试其Spring应用。 Spring 3.0中,新的表达式语言名叫Spring ...

    building restful web services with spring 5 2e

    Marrying the two technologies is therefore a very natural choice.This book takes you through the design of RESTful web services and leverages the Spring Framework to implement these services....

    SingleMyBatis 是基于Spring Framework基础上搭建的一个Java基础开发套件

    SingleMyBatis 是基于Spring Framework基础上搭建的一个Java基础开发套件,以Spring MVC为模型视图控制器,MyBatis为数据访问层。 * 核心框架:Spring Framework 4.2.7 * 安全框架: * 视图框架:Spring MVC 4.2.7 *...

    SingleHibernate 是基于Spring Framework基础上搭建的一个Java基础开发套件

    SingleHibernate 是基于Spring Framework基础上搭建的一个Java基础开发套件,以Spring MVC为模型视图控制器,Hibernate为数据访问层。 * 核心框架:Spring Framework 4.2.7 * 安全框架: * 视图框架:Spring MVC ...

    spring-boot-restful-crud-01.zip

    Java SpringBoot 课程 restful crud 实验资源 ...GitHub中有源码 https://github.com/kevinkda/MarkdownRepository/tree/master/Develop%20Demo/Java%20Framework/Spring/SpringBoot/spring-boot-restful-crud-01

    Pivotal Certified Spring Enterprise Integration Specialist Exam(Apress,2015)

    Exam topics covered include tasks and scheduling, remoting, the Spring Web Services framework, RESTful services with Spring MVC, the Spring JMS module, JMS and JTA transactions with Spring, batch ...

    Spring.Essentials.178398

    Build mission-critical enterprise applications using Spring Framework and Aspect Oriented Programming About This Book Step into more advanced features of aspect-oriented programming and API ...

    作品集--- SpringFramework:SpringFramework를이용한

    作品集--SpringFramework SpringFramework + oauth 2.0版本公园板개요 SpringFramework。 。람들과람들과。。。。。。 。로그인을가회원이누구나이누구나다。 기술&스택 客户...

    基于SSM+CXF构建的RESTFul webservice

    使用cxf、spring构建的rest风格webservice,其他相关技术springmvc、mybatis、druid等。代码中使用的数据库为sybase,请根据实际环境更改,需修改pom中引用的数据库驱动,依照entity类的属性建对应表,并修改config....

    精通Spring MVC 4

    Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。Spring MVC4是当前zuixin的版本,在众多特性上有了进一步的提升。, 在精通Spring...

    Spring.REST.1484208242

    Spring REST is a practical guide for designing and developing RESTful APIs using the Spring Framework. This book walks you through the process of designing and building a REST application while taking...

    Packt.Spring.5.0.Projects.rar

    Moving ahead, you'll build a RESTful web services application using Spring WebFlux framework. You'll be then taken through creating a Spring Boot-based simple blog management system, which uses ...

    restful restful所需要的jar包

    * Extensive integration with popular Spring IoC framework. * Deployment to Oracle 11g embedded JVM supported by special extension. Security * Supports HTTP Basic and Digest authentication (client ...

    Spring Security Third Edition.pdf英文版

    Architect solutions that leverage the full ... Java Web and/or RESTful webservice applications, XML, and the Spring Framework. You are not expected to have any previous experience with Spring Security.

Global site tag (gtag.js) - Google Analytics