Spring MVC风格的restful接口开发
程序员文章站
2024-02-16 10:37:34
...
项目的目录结构如下:
1.流程图
略。。
2.服务端代码
①实体类
package com.bjsxt.model;
import java.io.Serializable;
public class Person implements Serializable{
/**
*
*/
private static final long serialVersionUID = -3727979363425652597L;
private int id;
private String name;
private String sex;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
②接口编码IPersonService
package com.bjsxt.server;
import javax.ws.rs.core.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bjsxt.model.Person;
/**
* spring MVC风格的restful接口
*
* @author gaoweignag
* @since JDK1.7
*/
@RequestMapping("/test")
@Controller
public interface IPersonService {
@RequestMapping(value = "/hello", produces = "text/plain;charset=UTF-8")
public @ResponseBody
String hello();
@RequestMapping(value = "/say/{msg}", produces = "application/json;charset=UTF-8")
public @ResponseBody
String say(@PathVariable(value = "msg") String msg);
@RequestMapping(value = "/person/{id:\\d+}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public @ResponseBody
String getPerson(@PathVariable("id") int id);
@RequestMapping(value = "/person/{id:\\d+}", method = RequestMethod.DELETE)
public @ResponseBody Object deletePerson(@PathVariable("id") int id) ;
/**
* 推荐使用,这种可以解决绝大多数问题
* @param person
* @return
*/
@RequestMapping(value = "/person", method = RequestMethod.POST,
produces = {MediaType.APPLICATION_JSON,"application/json;charset=UTF-8"},
consumes = {MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public String addPerson(Person person);
@RequestMapping(value = "/person", method = RequestMethod.PUT)
public @ResponseBody Object updatePerson(@RequestBody Person person);
}
③接口实现类PersonService
package com.bjsxt.server.impl;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bjsxt.model.Person;
import com.bjsxt.server.IPersonService;
/**
* spring MVC风格的restful接口
*
* @author gaoweignag
* @since JDK1.7
*/
@Controller
public class PersonService implements IPersonService{
/** 日志实例 */
private static final Logger logger = Logger.getLogger(PersonService.class);
public @ResponseBody
String hello() {
logger.info("hello........");
return "你好!hello";
}
public @ResponseBody
String say(@PathVariable(value = "msg") String msg) {
return "{\"msg\":\"you say:'" + msg + "'\"}";
}
public @ResponseBody
String getPerson(@PathVariable("id") int id) {
logger.info("获取人员信息id=" + id);
Person person = new Person();
person.setName("张三");
person.setSex("男");
person.setAge(30);
person.setId(id);
JSONObject jsonObject = JSONObject.fromObject(person);
logger.info(jsonObject);
logger.info(jsonObject.toString());
return jsonObject.toString();
}
public Object deletePerson(@PathVariable("id") int id) {
logger.info("删除人员信息id=" + id);
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "删除人员信息成功");
return jsonObject;
}
public @ResponseBody String addPerson(@RequestBody Person person) {
logger.info("注册人员信息成功id=" + person.getId());
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "注册人员信息成功");
return jsonObject.toString();
}
public @ResponseBody Object updatePerson(@RequestBody Person person) {
logger.info("更新人员信息id=" + person.getId());
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "更新人员信息成功");
return jsonObject.toString();
}
}
④配置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> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <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进行单元测试
package com.bjsxt.client;
import org.apache.log4j.Logger;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import com.bjsxt.model.Person;
public class PersonClientTest {
private static Logger LOG = Logger.getLogger(PersonClientTest.class);
private static RestTemplate template = null;
@BeforeClass
public static void beforeClass(){
template = new RestTemplate();
}
@Test
public void testHello(){
LOG.info("进入hello Method start...");
String url = "http://localhost:8080/springMVCRestful/test/hello";
/**
* 第一个参数是restful接口请求路径
* 第二个参数是响应的类型 String.class
*/
String result = template.getForObject(url, String.class);
LOG.info("输出结果:"+result);
LOG.info("进入hello Method end...");
}
@Test
public void testSay(){
LOG.info("进入say Method start...");
String url = "http://localhost:8080/springMVCRestful/test/say/gaoweigang";
String result = template.getForObject(url, String.class);
LOG.info("输出结果:"+result);
LOG.info("进入say Method end...");
}
@Test
public void testGetPerson(){
LOG.info("进入getPerson Method start...");
/**
* restful参数类型是int,不能传String类型的参数,否则调用不到接口
*/
String url = "http://localhost:8080/springMVCRestful/test/person/101";
String result = template.getForObject(url, String.class);
LOG.info("输出结果:"+result);
LOG.info("进入getPerson Method end...");
}
@Test
public void testDeletePerson(){
LOG.info("进入deletePerson Method start...");
/**
* restful参数类型是int,不能传String类型的参数,否则调用不到接口
*/
String url = "http://localhost:8080/springMVCRestful/test/person/1234";
try {
template.delete(url);
} catch (RestClientException e) {
e.printStackTrace();
}
LOG.info("进入deletePerson Method end...");
}
@Test
public void testUpdatePerson(){
LOG.info("进入UpdatePerson Method start...");
/**
* restful参数类型是int,不能传String类型的参数,否则调用不到接口
*/
String url = "http://localhost:8080/springMVCRestful/test/person";
try {
Person person =new Person();
person.setId(1234);
person.setName("gaoweigang");
person.setAge(22);
person.setSex("男");
template.put(url, person);
} catch (RestClientException e) {
e.printStackTrace();
}
LOG.info("进入UpdatePerson Method end...");
}
@Test
public void testAddPerson(){
LOG.info("进入addPerson Method start...");
/**
* restful参数类型是int,不能传String类型的参数,否则调用不到接口
*/
String url = "http://localhost:8080/springMVCRestful/test/person";
Person person =new Person();
person.setId(1234);
person.setName("gaoweigang");
person.setAge(22);
person.setSex("男");
String result = template.postForObject(url, person, String.class);
LOG.info("输出结果为:"+result);
LOG.info("进入addPerson Method end...");
}
}
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"
上一篇: 字体图标的网站和使用
推荐阅读
-
Spring MVC风格的restful接口开发
-
SpringBoot Web开发——构建Restful风格接口
-
Spring MVC风格的restful接口开发
-
使用swagger生成restful风格的接口文档
-
Spring MVC 使用支付宝接口完成在线支付的示例代码
-
详解Spring框架之基于Restful风格实现的SpringMVC
-
Yii2 基于RESTful架构的 advanced版API接口开发 配置、实现、测试,yii2restful
-
spring MVC中接口参数解析的过程详解
-
Spring MVC集成springfox-swagger2构建restful API的方法详解
-
Spring MVC集成springfox-swagger2构建restful API的方法详解