Spring MVC风格的restful接口开发

项目的目录结构如下:


1.流程图

略。。

 

2.服务端代码

①实体类


   
   
  1. package com.bjsxt.model;
  2. import java.io.Serializable;
  3. public class Person implements Serializable{
  4. /**
  5. *
  6. */
  7. private static final long serialVersionUID = - 3727979363425652597L;
  8. private int id;
  9. private String name;
  10. private String sex;
  11. private int age;
  12. public int getId() {
  13. return id;
  14. }
  15. public void setId(int id) {
  16. this.id = id;
  17. }
  18. public String getName() {
  19. return name;
  20. }
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24. public String getSex() {
  25. return sex;
  26. }
  27. public void setSex(String sex) {
  28. this.sex = sex;
  29. }
  30. public int getAge() {
  31. return age;
  32. }
  33. public void setAge(int age) {
  34. this.age = age;
  35. }
  36. }

 

②接口编码IPersonService


   
   
  1. package com.bjsxt.server;
  2. import javax.ws.rs.core.MediaType;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.PathVariable;
  5. import org.springframework.web.bind.annotation.RequestBody;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. import com.bjsxt.model.Person;
  10. /**
  11. * spring MVC风格的restful接口
  12. *
  13. * @author gaoweignag
  14. * @since JDK1.7
  15. */
  16. @RequestMapping( "/test")
  17. @Controller
  18. public interface IPersonService {
  19. @RequestMapping(value = "/hello", produces = "text/plain;charset=UTF-8")
  20. public @ResponseBody
  21. String hello();
  22. @RequestMapping(value = "/say/{msg}", produces = "application/json;charset=UTF-8")
  23. public @ResponseBody
  24. String say(@PathVariable(value = "msg") String msg);
  25. @RequestMapping(value = "/person/{id:\\d+}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
  26. public @ResponseBody
  27. String getPerson(@PathVariable("id") int id);
  28. @RequestMapping(value = "/person/{id:\\d+}", method = RequestMethod.DELETE)
  29. public @ResponseBody Object deletePerson(@PathVariable("id") int id) ;
  30. /**
  31. * 推荐使用,这种可以解决绝大多数问题
  32. * @param person
  33. * @return
  34. */
  35. @RequestMapping(value = "/person", method = RequestMethod.POST,
  36. produces = {MediaType.APPLICATION_JSON, "application/json;charset=UTF-8"},
  37. consumes = {MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
  38. public String addPerson(Person person);
  39. @RequestMapping(value = "/person", method = RequestMethod.PUT)
  40. public @ResponseBody Object updatePerson(@RequestBody Person person);
  41. }

 

③接口实现类PersonService


   
   
  1. package com.bjsxt.server.impl;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import javax.ws.rs.core.MediaType;
  5. import net.sf.json.JSONObject;
  6. import org.apache.log4j.Logger;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.web.bind.annotation.PathVariable;
  9. import org.springframework.web.bind.annotation.RequestBody;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RequestMethod;
  12. import org.springframework.web.bind.annotation.RequestParam;
  13. import org.springframework.web.bind.annotation.ResponseBody;
  14. import com.bjsxt.model.Person;
  15. import com.bjsxt.server.IPersonService;
  16. /**
  17. * spring MVC风格的restful接口
  18. *
  19. * @author gaoweignag
  20. * @since JDK1.7
  21. */
  22. @Controller
  23. public class PersonService implements IPersonService{
  24. /** 日志实例 */
  25. private static final Logger logger = Logger.getLogger(PersonService.class);
  26. public @ResponseBody
  27. String hello() {
  28. logger.info( "hello........");
  29. return "你好!hello";
  30. }
  31. public @ResponseBody
  32. String say(@PathVariable(value = "msg") String msg) {
  33. return "{\"msg\":\"you say:'" + msg + "'\"}";
  34. }
  35. public @ResponseBody
  36. String getPerson(@PathVariable("id") int id) {
  37. logger.info( "获取人员信息id=" + id);
  38. Person person = new Person();
  39. person.setName( "张三");
  40. person.setSex( "男");
  41. person.setAge( 30);
  42. person.setId(id);
  43. JSONObject jsonObject = JSONObject.fromObject(person);
  44. logger.info(jsonObject);
  45. logger.info(jsonObject.toString());
  46. return jsonObject.toString();
  47. }
  48. public Object deletePerson(@PathVariable("id") int id) {
  49. logger.info( "删除人员信息id=" + id);
  50. JSONObject jsonObject = new JSONObject();
  51. jsonObject.put( "msg", "删除人员信息成功");
  52. return jsonObject;
  53. }
  54. public @ResponseBody String addPerson(@RequestBody Person person) {
  55. logger.info( "注册人员信息成功id=" + person.getId());
  56. JSONObject jsonObject = new JSONObject();
  57. jsonObject.put( "msg", "注册人员信息成功");
  58. return jsonObject.toString();
  59. }
  60. public @ResponseBody Object updatePerson(@RequestBody Person person) {
  61. logger.info( "更新人员信息id=" + person.getId());
  62. JSONObject jsonObject = new JSONObject();
  63. jsonObject.put( "msg", "更新人员信息成功");
  64. return jsonObject.toString();
  65. }
  66. }

 

④配置web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>springMVCRestful</display-name>
  <servlet>
    <servlet-name>springMVCRestful</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>    
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVCRestful</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- 如果有乱码我们则需要配置字符编码集的过滤器来防止乱码问题 -->
    <filter>
      <filter-name>encodingFilter</filter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
      </init-param>
      <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
      </init-param>
    </filter>
&lt;filter-mapping&gt;
  &lt;filter-name&gt;encodingFilter&lt;/filter-name&gt;
  &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;    

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

 

⑤配置spring mvc文件springMVCRestful-servlete.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:context="http://www.springframework.org/schema/context"
             xmlns:aop="http://www.springframework.org/schema/aop"
             xmlns:tx="http://www.springframework.org/schema/tx"
             xmlns:mvc="http://www.springframework.org/schema/mvc"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
                     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                     http://www.springframework.org/schema/context
                     http://www.springframework.org/schema/context/spring-context-3.0.xsd
                     http://www.springframework.org/schema/aop
                     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                     http://www.springframework.org/schema/tx
                     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                     http://www.springframework.org/schema/mvc 
                     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
                     default-autowire="byName"
                     >
   <!-- 初始化com.bjsxt目录下面的bean  -->
   <context:component-scan base-package="com.bjsxt"></context:component-scan>

<!-- 消息适配器 -->
<bean class=“org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter”>
<property name=“messageConverters”>
<list>
<!-- json转换器 -->
<bean class=“org.springframework.http.converter.json.MappingJacksonHttpMessageConverter” />
</list>
</property>
</bean>

<!–配置spring MVC的注解 驱动 -->
<mvc:annotation-driven/>
</beans>

 

3.客户端代码PersonClientTest,使用junit进行单元测试


 
 
  1. package com.bjsxt.client;
  2. import org.apache.log4j.Logger;
  3. import org.junit.BeforeClass;
  4. import org.junit.Test;
  5. import org.springframework.web.client.RestClientException;
  6. import org.springframework.web.client.RestTemplate;
  7. import com.bjsxt.model.Person;
  8. public class PersonClientTest {
  9. private static Logger LOG = Logger.getLogger(PersonClientTest.class);
  10. private static RestTemplate template = null;
  11. @BeforeClass
  12. public static void beforeClass(){
  13. template = new RestTemplate();
  14. }
  15. @Test
  16. public void testHello(){
  17. LOG.info( "进入hello Method start...");
  18. String url = "http://localhost:8080/springMVCRestful/test/hello";
  19. /**
  20. * 第一个参数是restful接口请求路径
  21. * 第二个参数是响应的类型 String.class
  22. */
  23. String result = template.getForObject(url, String.class);
  24. LOG.info( "输出结果:"+result);
  25. LOG.info( "进入hello Method end...");
  26. }
  27. @Test
  28. public void testSay(){
  29. LOG.info( "进入say Method start...");
  30. String url = "http://localhost:8080/springMVCRestful/test/say/gaoweigang";
  31. String result = template.getForObject(url, String.class);
  32. LOG.info( "输出结果:"+result);
  33. LOG.info( "进入say Method end...");
  34. }
  35. @Test
  36. public void testGetPerson(){
  37. LOG.info( "进入getPerson Method start...");
  38. /**
  39. * restful参数类型是int,不能传String类型的参数,否则调用不到接口
  40. */
  41. String url = "http://localhost:8080/springMVCRestful/test/person/101";
  42. String result = template.getForObject(url, String.class);
  43. LOG.info( "输出结果:"+result);
  44. LOG.info( "进入getPerson Method end...");
  45. }
  46. @Test
  47. public void testDeletePerson(){
  48. LOG.info( "进入deletePerson Method start...");
  49. /**
  50. * restful参数类型是int,不能传String类型的参数,否则调用不到接口
  51. */
  52. String url = "http://localhost:8080/springMVCRestful/test/person/1234";
  53. try {
  54. template.delete(url);
  55. } catch (RestClientException e) {
  56. e.printStackTrace();
  57. }
  58. LOG.info( "进入deletePerson Method end...");
  59. }
  60. @Test
  61. public void testUpdatePerson(){
  62. LOG.info( "进入UpdatePerson Method start...");
  63. /**
  64. * restful参数类型是int,不能传String类型的参数,否则调用不到接口
  65. */
  66. String url = "http://localhost:8080/springMVCRestful/test/person";
  67. try {
  68. Person person = new Person();
  69. person.setId( 1234);
  70. person.setName( "gaoweigang");
  71. person.setAge( 22);
  72. person.setSex( "男");
  73. template.put(url, person);
  74. } catch (RestClientException e) {
  75. e.printStackTrace();
  76. }
  77. LOG.info( "进入UpdatePerson Method end...");
  78. }
  79. @Test
  80. public void testAddPerson(){
  81. LOG.info( "进入addPerson Method start...");
  82. /**
  83. * restful参数类型是int,不能传String类型的参数,否则调用不到接口
  84. */
  85. String url = "http://localhost:8080/springMVCRestful/test/person";
  86. Person person = new Person();
  87. person.setId( 1234);
  88. person.setName( "gaoweigang");
  89. person.setAge( 22);
  90. person.setSex( "男");
  91. String result = template.postForObject(url, person, String.class);
  92. LOG.info( "输出结果为:"+result);
  93. LOG.info( "进入addPerson Method end...");
  94. }
  95. }

 

4.启动tomcat服务后,就可以对PersonClientTest进行单元测试了

 

可能遇到的问题:

1.The prefix "mvc" for element "mvc:annotation-driven" is not bound 的解决方法

在spring mvc在配置文件中添加namespace

xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
来源:https://blog.csdn.net/iteye_7017/article/details/82653613
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值