【Spring集成】-SpringMVC创建REST API

1.REST简介

    近几年来,以信息为中心的表述性状态转移( Representational State Transfer , REST )已成为替换传统 SOAP Web 服务的流行方案。 SOAP 一般会关注行为和处理,而 REST 关注的是要处理的数据。 REST 就是将资源的状态以最适合客户端或服务端的形式从服务器端转移到客户端(或者反过来)。在 REST 中,资源通过 URL 进行识别和定位。至于 RESTful URL 的结构并没有严格的规则,但是URL 应该能够识别资源,而不是简单的发一条命令到服务器上。再次强调,关注的核心是事物,而不是行为。REST 中会有行为,它们是通过 HTTP 方法来定义的。具体来讲,也就是 GET 、 POST 、 PUT 、 DELETE 、 PATCH 以及其他的 HTTP 方法构成了 REST 中的动作。

2.SpringMVC创建REST

    第一步:创建实体类

package chapter16.domain;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "jinnang")
public class JinNang implements Serializable{
	private static final long serialVersionUID = 1L; 	
	private String jice;//计策
	private String people;//计策实施者
	
	public JinNang(){}
	
	public JinNang(String jice,String people){
		this.jice=jice;
		this.people=people;
	}

	@XmlElement
	public String getJice() {
		return jice;
	}

	public void setJice(String jice) {
		this.jice = jice;
	}

	@XmlElement
	public String getPeople() {
		return people;
	}

	public void setPeople(String people) {
		this.people = people;
	}
}

@XmlRootElement(name = "jinnang")注解是当客户端需要xml表述形式,Jaxb2RootElementHttpMessageConverter消息转化器进行构造根元素的依据。@XmlElement注解就是标识子元素。

第二步:构建接口和实现类

package chapter16.service.interfaces;

import chapter16.domain.JinNang;
public interface JinNangService {
	public abstract JinNang getJinNang();

}

接口实现类:

import org.springframework.stereotype.Service;

@Service
public class JinNangServiceImpl implements JinNangService{	 
	@Override
	public JinNang getJinNang() {
		JinNang j=new JinNang("百步穿杨","黄忠");
		return j;
	}

}

第三步:配置控制器

import static org.springframework.web.bind.annotation.RequestMethod.GET;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import chapter16.domain.JinNang;
import chapter16.service.interfaces.JinNangService;

@Controller
@RequestMapping("/JinNang")
public class JinNangController {
	private JinNangService jinNangService;

	  @Autowired
	  public JinNangController(JinNangService jinNangService) {
	    this.jinNangService = jinNangService;
	  }
	  
	  @RequestMapping(method=RequestMethod.GET)
	  public @ResponseBody JinNang getJinNang() {
		  JinNang j=jinNangService.getJinNang();
		  System.out.println(j.getPeople());
		  return j;
	  }
	  
	  @RequestMapping(value="/test", method=GET)
	  public String test() {
		  return "jinnang";
	  }
	  

}

正常情况下,当处理方法返回 Java 对象(除 String 外或 View 的实现以外)时,这个对象会放在模型中并在视图中渲染使用。但是,如果使用了消息转换功能的话,我们需要告诉 Spring 跳过正常的模型 / 视图流程,并使用消息转换器。有不少方式都能做到这一点,但是最简单的方法是为控制器方法添加 @ResponseBody 注解。@ResponseBody 注解会根据客户端请求的资源类型来自行调用相应的消息转换器。将对象表述成客户端想要的形式。

spring启动类:

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class<?>[] { };
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class<?>[] {WebConfig.class };
	}

	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}
}

配置类:

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfig extends WebMvcConfigurerAdapter {

}

第四步:配置测试类:

package chapter16.test;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

public class RestTemplateTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		RestTemplateTest.restGet();
	}
	
	public static void restGet(){	
		
		RestTemplate rest=new RestTemplate();
		
		String urlStr="http://localhost:8080/SpringTest/JinNang.json";
		HttpHeaders headers = new HttpHeaders();
		
	    HttpEntity<String> formEntity = new HttpEntity<String>("", headers);
	    Map<String, Object> parameterMap = new HashMap<String, Object>();
	    List<HttpMessageConverter<?>> list=new ArrayList<HttpMessageConverter<?>>();
	    list.add(new StringHttpMessageConverter(Charset.forName("utf-8")));
	    rest.setMessageConverters(list);
	    
	    ResponseEntity<String> result=rest.exchange(urlStr,HttpMethod.GET, formEntity, String.class, parameterMap);
		System.out.println("body="+result.getBody()+"\r\n status="+result.getStatusCode());
	}
}
 


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值