Jersey实现Restful webservice及Ajax访问

jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<html>
  <head>
   <script src="js/jquery/jquery.js"></script>
   <script>
   		function rest1(){
   			$.ajax({
			type: 'POST',
			url: 'http://localhost:8080/RestDemo/webapi/users',
			dataType: "json",
            contentType: "application/json",
            data: "{\"userId\":\"004\", \"userName\":\"Susan\", \"age\":\"33\"}",
			cache : false,
			error:function(){alert('系统连接失败,请稍后再试!')},
			success: function(obj){
				alert(obj.userName);
			}
		});
   		}
   </script>

    <script>
   		function rest2(){
   			$.ajax({
			type: 'POST',
			url: 'http://localhost:8080/RestDemo/webapi/users/user',
			dataType: "json",
            contentType: "application/x-www-form-urlencoded",
            // data: "{\"userId\":\"004\", \"userName\":\"Susan\", \"age\":\"33\"}",
            data:  {
              		"user": "{\"userId\":\"004\", \"userName\":\"Susan\", \"age\":\"33\"}"
          		   },
			cache : false,
			error:function(){alert('系统连接失败,请稍后再试!')},
			success: function(obj){
				alert(obj.userName);
			}
		});
   		}
   </script>

    <script>
   		function rest3(){
   			$.ajax({
			type: 'POST',
			url: 'http://localhost:8080/RestDemo/webapi/users/delete/001',
			dataType: "json",
            contentType: "application/json",
          //  data: "{\"userId\":\"004\", \"userName\":\"Susan\", \"age\":\"33\"}",
			cache : false,
			error:function(){alert('系统连接失败,请稍后再试!')},
			success: function(obj){
				alert(obj.userName);
			}
		});
   		}
   </script>
  </head>

  <body>
    <h2>Jersey RESTful Web Application!</h2>
    <p><a href="webapi/myresource">Jersey resource</a>
    <p>Visit <a href="http://jersey.java.net">Project Jersey website</a>
    for more information on Jersey!

      <input type="button" onclick="rest1();"  value="sss">
      <input type="button" onclick="rest2();" value="aaa">
      <input type="button" onclick="rest3();" value="ddd">
  </body>
</html>

java

package org.nercita.zmx;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class User {

	private String userId;
	private String userName;
	private String age;

	public User() {};

	public User(String userId, String userName, String age) {
		this.userId = userId;
		this.userName = userName;
		this.age = age;
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
}
package org.nercita.zmx;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/users")
public class UserResource {

	private static Map<String,User> userMap = new HashMap<String,User>();//存储用户

	 /**
     * 查询所有
     * @return
     */
    @GET
    @Produces(MediaType.APPLICATION_XML)
    public List<User> getAllUsers(){
		List<User> users = new ArrayList<User>();
		User u1 = new User("001","WayLau","26");
		User u2 = new User("002","King","23");
		User u3 = new User("003","Susan","21");

		userMap.put(u1.getUserId(), u1);
		userMap.put(u2.getUserId(), u2);
		userMap.put(u3.getUserId(), u3);

		users.addAll( userMap.values() );
		return users;
    }

    @GET
    @Path("/getUserXml")
    @Produces(MediaType.APPLICATION_XML)
    public User getUserXml() {
     User user  = new User();
     user.setAge("21");
     user.setUserId("004");
     user.setUserName("Amand");
     return user;
    }

   @GET
   @Path("/getUserJson")
   @Produces(MediaType.APPLICATION_JSON)
   public User getUserJson() {
     User user  = new User();
     user.setAge("27");
     user.setUserId("005");
     user.setUserName("Fmand");
     return user;
   } 

   /**
	* 增加
	* @param user
	*/
   @POST
   @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Produces(MediaType.APPLICATION_JSON)
   public User createStudent(User user)
   {
		userMap.put(user.getUserId(), user );
		return user;
   }

   /**
	* 增加
	* @param user
	*/
   @POST
   @Path("/user")
   public User addStudent(@FormParam("j") String j)
   {
		System.out.println(j);
		User user  = new User();
	    user.setAge("27");
	    user.setUserId("005");
	    user.setUserName("Fmand");
	    return user;
   }

   /**
	* 删除
	* @param user
	*/
   @POST
   @Path("/delete/{id}")
   @Produces(MediaType.APPLICATION_JSON)
   @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   public User delStudent(@PathParam("id")String id)
   {
		System.out.println(id);
		User user  = new User();
	    user.setAge("27");
	    user.setUserId("005");
	    user.setUserName("Fmand");
	    return user;
   }

	/**
	 * 删除
	 * @param id
	 */
   @DELETE
   @Path("{id}")
   public void deleteStudent(@PathParam("id")String id){
   	userMap.remove(id);
   }

   /**
    * 修改
    * @param user
    */
   @PUT
   @Consumes(MediaType.APPLICATION_XML)
   public void updateStudent(User user){
		userMap.put(user.getUserId(), user );
   }

   /**
    * 根据id查询
    * @param id
    * @return
    */
   @GET
   @Path("{id}")
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   public User getUserById(@PathParam("id") String id){
   	User u = userMap.get(id);
   	return u;
   }

}
package org.nercita.zmx;

import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.glassfish.jersey.server.ResourceConfig;

public class RestApplication extends ResourceConfig {

	public RestApplication() {

     //服务类所在的包路径
     packages("org.nercita.zmx");
     //注册JSON转换器
     register(JacksonJsonProvider.class); 

	}

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
     see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <!-- <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>org.nercita.zmx</param-value>
        </init-param> -->
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>org.nercita.zmx.RestApplication</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
</web-app>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.nercita.ltxx</groupId>
    <artifactId>RestDemo</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>RestDemo</name>

    <build>
        <finalName>RestDemo</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
            <!-- artifactId>jersey-container-servlet</artifactId -->
        </dependency>

        <!-- uncomment this to get JSON support
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
        </dependency>
        -->

		<!--Jackson  Json支持 -->
		<dependency>
		    <groupId>org.codehaus.jackson</groupId>
		    <artifactId>jackson-core-asl</artifactId>
		    <version>1.9.12</version>
		</dependency>
		<dependency>
		    <groupId>org.codehaus.jackson</groupId>
		    <artifactId>jackson-mapper-asl</artifactId>
		    <version>1.9.12</version>
		</dependency>
		<dependency>
		    <groupId>org.codehaus.jackson</groupId>
		    <artifactId>jackson-jaxrs</artifactId>
		    <version>1.9.12</version>
		</dependency>

    </dependencies>
    <properties>
        <jersey.version>2.22.2</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>
时间: 2024-11-14 00:23:11

Jersey实现Restful webservice及Ajax访问的相关文章

Eclipse + Jersey 发布RESTful WebService(一)了解Jersey

2018-4-6 OK,我得承认,是因为Axis2没走通,所以改了用Jersey,因为之前一次用过觉得还挺容易用. 具体Jersey是什么,目前完全不了解,接下来1天时间来试试看. -- 怎么着都不成 一.下文中需要的资源地址汇总 Apache Maven Apache网站 http://maven.apache.org/ Maven下载地址: http://maven.apache.org/download.cgi Jersey Jersey(JAX-RS 2.1 / Jersey 2.26+

【jersey】 spring 整合jersey 实现RESTful webservice

Jersey是一个RESTFUL请求服务JAVA框架,与常规的JAVA编程使用的struts框架类似,它主要用于处理业务逻辑层.与Struts类似,它同样可以和hibernate,spring框架整合. 由于Struts2+hibernate+spring整合在市场的占有率太高,所以很少一部分人去关注Jersey.所以网上有关于Jersey的介绍很少.但是它确实是一个非常不错的框架.对于请求式服务,对于GET,DELETE请求,你甚至只需要给出一个URI即可完成操. jar 文件依赖: <pro

spring+jersey构建restful webservice(数据源采用c3p0)

项目下载地址:  http://files.cnblogs.com/files/walk-the-Line/payment.zip

CXF发布支持ajax跨域访问的restful webservice

用apache cxf构建了一个玩具型restful webservice,内嵌jetty,加上gradle,发布无比轻松. apply plugin: 'java' apply plugin: 'application' repositories { maven { url "http://maven.oschina.net/content/groups/public" } } [compileJava,compileTestJava,javadoc]*.options*.encod

在Eclipse中使用Jersey和Tomcat构建RESTful WebService及其调用

在Eclipse中使用Jersey和Tomcat构建RESTful WebService及其调用 RESTful Web 服务简介 REST 在 2000 年由 Roy Fielding 在博士论文中提出,他是 HTTP 规范 1.0 和 1.1 版的首席作者之一. REST 中最重要的概念是资源(resources),使用全球 ID(通常使用 URI)标识.客户端应用程序使用 HTTP 方法(GET/ POST/ PUT/ DELETE)操作资源或资源集.RESTful Web 服务是使用 H

$.ajax访问RESTful Web Service报错:Unsupported Media Type

最近在项目中,前台页面使用jquery ajax访问后台CXF发布的rest服务,结果遇到了错误"Unsupported Media Type". 发布的服务java代码如下: import javax.jws.WebService; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produ

SOAP webserivce 和 RESTful webservice 对比及区别

简单对象访问协议(Simple Object Access Protocol,SOAP)是一种基于 XML 的协议,可以和现存的许多因特网协议和格式结合使用,包括超文本传输协议(HTTP),简单邮件传输协议(SMTP),多用途网际邮件扩充协议(MIME),基于"通用"传输协议是 SOAP的一个优点.它还支持从消息系统到远程过程调用(Remote Procedure Call,RPC)等大量的应用程序.SOAP提供了一系列的标准,如WSRM(WS-Reliable Messaging)形

RESTful WebService入门

RESTful WebService入门 RESTful WebService是比基于SOAP消息的WebService简单的多的一种轻量级Web服务,RESTful WebService是没有状态的,发布和调用都非常的轻松容易. 下面写一个最简单的Hello World例子,以便对RESTful WebService有个感性认识.因为非常专业理论化的描述RESTful WebService是一件理解起来很痛苦的事情.看看例子就知道个大概了,再看理论就容易理解多了. /** * RESTful

RESTful WebService入门(转)

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://lavasoft.blog.51cto.com/62575/229206 RESTful WebService是比基于SOAP消息的WebService简单的一种轻量级Web服务,RESTful WebService是没有状态的,发布和调用都是非常的轻松容易. 以下是一个最简单的Hello World例子,以便对RESTful WebService有个感性认识.因为非常专业理论化