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);
    }

}

你可能感兴趣的:(Restful)