背景
最近需要抽离出一个复用模块作为服务端代码供其他多个项目调用,选用的是作为restful风格的api。先写个demo做测试,直接贴代码吧,供自己以后回顾参考。
demo
- 开发工具:eclipse;
- 数据库:oracle。
项目结构
配置文件
testService-servlet.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"
>
<!-- initial bean -->
<context:component-scan base-package="test.*"></context:component-scan>
<!-- news config -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<!-- json convert -->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
<!-- spring MVC注解驱动 -->
<mvc:annotation-driven/>
</beans>
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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID"
version="3.0">
<display-name>testService</display-name>
<servlet>
<servlet-name>testService</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>testService</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>
实体类
package test.entity;
import java.io.Serializable;
public class Person implements Serializable{
private static final long serialVersionUID = -3727979363425652597L;
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
service接口类
package test.service;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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;
@Controller
public interface IAcctService {
@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="/getAcctString",params={"hkid","email"},method=RequestMethod.GET,produces="application/json;charset=UTF-8")
public @ResponseBody
String getAcctString(@RequestParam String hkid, @RequestParam String email);
@RequestMapping(value="/getAcctList",params={"hkid", "email"},method=RequestMethod.GET,produces="application/json;charset=UTF-8")
public @ResponseBody
List getAcctList(@RequestParam String hkid, @RequestParam String email);
@RequestMapping(value="/person/{id:\\d+}",method=RequestMethod.GET,produces="application/json;charset=UTF-8")
public @ResponseBody
String getPerson(@PathVariable("id") int id);
}
service实现类
package test.service.impl;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import test.dao.GetAccountDao;
import test.service.IAcctService;
import net.sf.json.JSONArray;
@Controller
public class AcctServiceImpl implements IAcctService{
/** 日志实例 */
private static final Logger logger = Logger.getLogger(AcctServiceImpl.class);
public @ResponseBody
String hello() {
return "hello";
}
public @ResponseBody
String say(@PathVariable(value="msg")String msg) {
return "{\"msg\":\"you say:'"+msg+"'\"}";
}
public @ResponseBody
String getAcctString(@RequestParam String hkid, @RequestParam String email) {
GetAccountDao gad = new GetAccountDao();
List<String> acctList = gad.getAccount(hkid, email);
JSONArray json = new JSONArray();
json = JSONArray.fromObject(acctList);
String acctStr = json.toString();
System.out.println(acctStr);
return acctStr;
}
public @ResponseBody
List getAcctList(@RequestParam String hkid, @RequestParam String email) {
GetAccountDao gad = new GetAccountDao();
List<String> acctList = gad.getAccount(hkid, email);
System.out.println(acctList);
return acctList;
}
public @ResponseBody
String getPerson(@PathVariable("id") int id) {
logger.info("获取人员信息id=" +id);
Person p = new Person();
p.setName("tom");
p.setAge(30);
p.setId(id);
JSONObject jo = JSONObject.fromObject(p);
logger.info(jo);
logger.info(jo.toString());
return jo.toString();
}
}
测试类
package test.client;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.web.client.RestTemplate;
public class AcctClientTest {
private static Logger logger = Logger.getLogger(AcctClientTest.class);
@Test
public void testHello(){
logger.info("enter hello Method start...");
System.out.println("enter hello Method start...");
String url = "http://localhost:8080/testService/hello";
RestTemplate restTemplate = new RestTemplate();
/**
* 第一个参数是restful接口请求路径
* 第二个参数是相应的类型String.class
*/
String result = restTemplate.getForObject(url, String.class);
logger.info("输出结果:"+result);
logger.info("enter hello Method end...");
System.out.println("enter hello Method end...");
}
@Test
public void testGetAcctString(){
logger.info("enter getAcctString Method start...");
System.out.println("enter getAcct Method start...");
String url="http://localhost:8080/testService/getAcctList?hkid={hkid}&email={email}";
RestTemplate restTemplate = new RestTemplate();
Map<String, Object> params = new HashMap<>();
params.put("hkid", "xxxxxxxx");
params.put("email", "xxxxxxxx");
try{
String result = restTemplate.getForObject(url, String.class, params);
logger.info("output:" + result);
System.out.println("output:" + result);
}catch(Exception e){
System.out.println("error :"+ e.getMessage());
}
logger.info("enter getAcctString Method end...");
System.out.println("enter getAcctString Method end...");
}
@Test
public void testGetAcctList(){
logger.info("enter getAcctList Method start...");
System.out.println("enter getAcct Method start...");
String url="http://localhost:8080/testService/getAcctList?hkid={hkid}&email={email}";
RestTemplate restTemplate = new RestTemplate();
Map<String, Object> params = new HashMap<>();
params.put("hkid", "xxxxxxxx");
params.put("email", "xxxxxxxx");
try{
ArrayList result = restTemplate.getForObject(url, ArrayList.class, params);
logger.info("output:" + result);
System.out.println("output:" + result);
}catch(Exception e){
System.out.println("error :"+ e.getMessage());
}
logger.info("enter getAcctList Method end...");
System.out.println("enter getAcctList Method end...");
}
@Test
public void testPerson(){
logger.info("enter testPerson Method start...");
String url = "http://localhost:8080/testService/person/100";
RestTemplate rt = new RestTemplate();
String person = rt.getForObject(url, String.class);
logger.info("person: "+person);
logger.info("enter testPerson Method end...");
}
}
返回结果
注意
Spring 3.x 和4.X处理JSON的一个类不一样,而这个东西又配置在xml文件中,所以编译时又无法发现,在运行时就会报无法找到合适转换类型的错误
spring3.x是org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
spring4.x是org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
在使用不同版本的spring包时,需要修改testService-servlet.xml
并且替换成高版本的fastjackson包。