创建web service project
添加代码
RestFul.java:
package com.webservice;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
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
@RequestMapping(value = "/getData")
public class RestFul {
// http://localhost:8080/RestWebService/getData?userName=sun 方式的调用
@RequestMapping
public void printData1(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value="userName", defaultValue="User") String name) {
List<UserInfo> uiList = new ArrayList<UserInfo>();
for (int i=0; i<3; i++)
{
UserInfo ui = new UserInfo();
//JSONObject map = new JSONObject();
ui.ID = i;
ui.Name = "SUN" + i;
ui.Position = "Position" + i;
uiList.add(ui);
}
JSONArray jsonArr = JSONArray.fromObject(uiList);
String msg = jsonArr.toString();
printData(response, msg);
}
// http://localhost:8080/RestWebService/getData/Sun/Royi 方式的调用
@RequestMapping(value = "/{firstName}/{lastName}")
public void printData2(HttpServletRequest request, HttpServletResponse response,
@PathVariable String firstName, @PathVariable String lastName) {
String msg = "Welcome "+ firstName + " " + lastName;
printData(response, msg);
}
// 转换成HTML形式返回
private void printData(HttpServletResponse response, String msg) {
try {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
out.println(msg);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// http://localhost:8080/RestWebService/getData/json?item=0 方式的调用
@RequestMapping(value = "/json")
public void printData3(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value="item", defaultValue="0") String item) {
printDataJason(response, item);
}
// http://localhost:8080/RestWebService/getData/json/1 方式的调用
@RequestMapping(value = "/json/{item}")
public void printData4(HttpServletRequest request, HttpServletResponse response,
@PathVariable String item) {
printDataJason(response, item);
}
// JSON格式化
private void printDataJason(HttpServletResponse response, String item) {
String st = "";
try {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
List<UserInfo> uiList = new ArrayList<UserInfo>();
for (int i=0; i<3; i++)
{
UserInfo ui = new UserInfo();
//JSONObject map = new JSONObject();
ui.ID = i;
ui.Name = "SUN" + i;
ui.Position = "Position" + i;
uiList.add(ui);
out.close();
}
JSONArray jsonArr = JSONArray.fromObject(uiList);
st = jsonArr.toString();
}
catch (Exception e) {
e.printStackTrace();
}
printData(response, st);
}
// http://localhost:8080/RestWebService/getData/query
@GET
@RequestMapping(value = "/query", method = RequestMethod.GET)
@ResponseBody
private String printDataJason1() {
String st = "";
try {
List<UserInfo> uiList = new ArrayList<UserInfo>();
for (int i=0; i<3; i++)
{
UserInfo ui = new UserInfo();
//JSONObject map = new JSONObject();
ui.ID = i;
ui.Name = "SUN" + i;
ui.Position = "Position" + i;
uiList.add(ui);
}
JSONArray jsonArr = JSONArray.fromObject(uiList);
st = jsonArr.toString();
}
catch (Exception e) {
e.printStackTrace();
}
return st;
}
}
添加代码
UserInfo.java
package com.webservice;
public class UserInfo{
Integer ID;
String Name;
String Position;
public Integer getID() {
return ID;
}
public void setID(Integer iD) {
ID = iD;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPosition() {
return Position;
}
public void setPosition(String position) {
Position = position;
}
}
添加配置文件
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_3_0.xsd" version="3.0">
<display-name>RestWebService</display-name>
<!-- spring -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
配置文件rest-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- for processing requests with annotated controller methods and set Message Convertors from the list of convertors -->
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonMessageConverter"/>
</beans:list>
</beans:property>
</beans:bean>
<!-- To convert JSON to Object and vice versa -->
<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>
<context:component-scan base-package="net.javaonline.spring.restful" />
</beans:beans>
配置文件springmvc-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: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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config/>
<mvc:default-servlet-handler/>
<!-- 默认访问跳转到登录页面 -->
<mvc:view-controller path="/" view-name="redirect:/getData" />
<!-- Scans the classpath of this application for @Components to deploy as beans -->
<context:component-scan base-package="com.webservice">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 采用SpringMVC自带的JSON转换工具,支持@ResponseBody注解 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<property name ="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- Configures the @Controller programming model -->
<mvc:annotation-driven/>
</beans>
工程目录
注意事项
导入包时一定要把json相关jar包放到项目的lib目录下