RestFul WebService的创建和使用实例
一. RestFul WebService的创建:
UserInfo.java
[java] view plain copy
3.SpringMVC框架需要修改一些配置:
web.xml
[html] view plain copy
[html] view plain copy
本例使用SpringMVC来写RestFul Web Service。
1.创建【Dynamic Web Prject】
2.添加代码:
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 net.sf.json.JSONArray;
- 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;
- @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) {
- String msg = "Welcome "+ name;
- 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) {
- 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();
- ui.ID = i;
- ui.Name = "SUN" + i;
- ui.Position = "Position" + i;
- uiList.add(ui);
- if (!item.equals("0")){
- JSONArray jsonArr = JSONArray.fromObject(uiList.get(0));
- out.println(jsonArr);
- }
- else{
- JSONArray jsonArr = JSONArray.fromObject(uiList);
- out.println(jsonArr);
- //out.println(uiList);
- }
- out.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
UserInfo.java
[java] view plain copy
- 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;
- }
- }
3.SpringMVC框架需要修改一些配置:
web.xml
[html] view plain copy
- <?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>
[html] view plain copy
- springmvc-servlet.xml:
- <pre name="code" class="html"><?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" />
- &n
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。