SpringMVC(六)处理请求9.0

(1)@ResponseBody
在这里插入图片描述
@ResponseBody是作用在方法上的,@ResponseBody 表示该方法的返回结果直接写入 HTTP response body 中,一般在异步获取数据时使用【也就是AJAX】,在使用 @RequestMapping后,返回值通常解析为跳转路径,但是加上 @ResponseBody 后返回结果不会被解析为跳转路径,而是直接写入 HTTP response body 中。 比如异步获取 json 数据,加上 @ResponseBody 后,会直接返回 json 数据。@RequestBody 将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。如下面的源代码所示,ResponseBody可以同时注解在方法与控制器上面:

/*
 * Copyright 2002-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotation that indicates a method return value should be bound to the web
 * response body. Supported for annotated handler methods in Servlet environments.
 *
 * <p>As of version 4.0 this annotation can also be added on the type level in
 * which case it is inherited and does not need to be added on the method level.
 *
 * @author Arjen Poutsma
 * @since 3.0
 * @see RequestBody
 * @see RestController
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ResponseBody {

}

如果注解在控制器上面将作用与每一个方法上,每个方法都将受到影响。
(2)@RestController
Spring 4 MVC中提供的@RestController,使用最少的代码来构建一个Restful Web Service,支持返回xml或json数据,这个可以让用户选择,通过URL后缀.xml或.json来完成。
REST即表述性状态传递(英文:Representational State Transfer,简称REST)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格。它是一种针对网络应用的设计和开发方式,可以降低开发的复杂性,提高系统的可伸缩性。
目前在三种主流的Web服务实现方案中,因为REST模式的Web服务与复杂的SOAP和XML-RPC对比来讲明显的更加简洁,越来越多的web服务开始采用REST风格设计和实现。例如,Amazon.com提供接近REST风格的Web服务进行图书查找;雅虎提供的Web服务也是REST风格的。
Rest风格的URL:

新增: http://www.zhangguo.com/order      POST 
修改: http://www.zhangguo.com/order/1   PUT update?id=1 
获取:http://www.zhangguo.com/order/1     GET get?id=1 
删除: http://www.zhangguo.com/order/1   DELETE delete?id=1

实现方法一:

@Controller
@RequestMapping(value="/restservice")
public class RestService {
    
    public final static String SUCCEEDD="show";
    
    
    /**
     * get请求
     * url:  http://localhost:8080/springmvc/restservice/testRestGet/12
     * @param id  
     *         查询的参数
     * @return
     */
    @RequestMapping(value="/testRestGet/{id}",method=RequestMethod.GET)
    public String testRestGet(@PathVariable("id") Integer id){
        System.out.println("rest 风格的GET请求..........id=" +id);
        return SUCCEEDD;
    }
    /**
     * post新增 
     * url:  http://localhost:8080/springmvc/restservice/testRestPost
     * @return
     */
    @RequestMapping(value="/testRestPost",method=RequestMethod.POST)
    public String testRestPost(){
        System.out.println("rest 风格的POST请求.......... ");
        return SUCCEEDD;
    }
    /**
     * PUT 修改操作
     * url:  http://localhost:8080/springmvc/restservice/testRestPut/put123
     * @param name
     * @return
     */
    @RequestMapping(value="/testRestPut/{name}",method=RequestMethod.PUT)
    public String testRestPut(@PathVariable("name") String name){
        System.out.println("rest 风格的PUT请求..........name="+name);
        return SUCCEEDD;
    }
    /**
     *   DELETE删除操作
     *   url: http://localhost:8080/springmvc/restservice/testRestDelete/11
     * @param id
     * @return
     */
    @RequestMapping(value="/testRestDelete/{id}",method=RequestMethod.DELETE)
    public String testRestDelete(@PathVariable Integer id){
        System.out.println("rest 风格的DELETE请求..........id="+id);
        return SUCCEEDD;
    }
    
       
}

不难发现@RestController是继承自@Controller与@ResponseBody的,所以它同时拥有他们的特性:

/*
 * Copyright 2002-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.stereotype.Controller;

/**
 * A convenience annotation that is itself annotated with
 * {@link Controller @Controller} and {@link ResponseBody @ResponseBody}.
 * <p>
 * Types that carry this annotation are treated as controllers where
 * {@link RequestMapping @RequestMapping} methods assume
 * {@link ResponseBody @ResponseBody} semantics by default.
 *
 * <p><b>NOTE:</b> {@code @RestController} is processed if an appropriate
 * {@code HandlerMapping}-{@code HandlerAdapter} pair is configured such as the
 * {@code RequestMappingHandlerMapping}-{@code RequestMappingHandlerAdapter}
 * pair which are the default in the MVC Java config and the MVC namespace.
 * In particular {@code @RestController} is not supported with the
 * {@code DefaultAnnotationHandlerMapping}-{@code AnnotationMethodHandlerAdapter}
 * pair both of which are also deprecated.
 *
 * @author Rossen Stoyanchev
 * @author Sam Brannen
 * @since 4.0
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any
     * @since 4.0.1
     */
    String value() default "";

}

可以轻松的将上面的代码修改为@RestController注解实现。

package com.zhangguo.springmvc01.controller;

import com.zhangguo.springmvc01.entities.Car;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/car")
public class CarController {
    
    @GetMapping("/{id}")
    public Car getCar(@PathVariable int id){
        return null;
    }

    @DeleteMapping("/{id}")
    public Car deleteCar(@PathVariable int id){
        return null;
    }
    
    @PostMapping
    public Car addCar(Car car){
        return null;
    }

    @PutMapping
    public Car updateCar(Car car){
        return null;
    }
    
}

使用 String 作为请求处理方法的返回值类型是比较通用的方法,这样返回的逻辑视图名不会和请求 URL 绑定,具有很高的灵活性,而模型数据又可以通过Model控制。

使用void,map,Model时,返回对应的逻辑视图名称真实url为:prefix前缀+控制器路径+方法名 +suffix后缀组成。

使用String,ModelAndView返回视图名称可以不受请求的url绑定,ModelAndView可以设置返回的视图名称。

另外在非MVC中使用的许多办法在Action也可以使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值