基于jersey的pojo对象获取前台ajax的json参数

来源:互联网 发布:淘宝无线手焦4 编辑:程序博客网 时间:2024/06/08 20:00

这里就不介绍Jersey了,它Sun自己实现的一个RESTFUL Web Service。具体看这里:使用 Jersey 和 Apache Tomcat 构建 RESTful Web 服务

我这里要说的是关于如何获取前台ajax请求的json数据。网上搜了很多都没有讲这一块的,要么都是用client来模拟,我这里测试成功了,先给出方法。


废话少说,先上代码:

首先是jsp页面ajax请求:

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript" src="js/jquery-1.7.1.js"></script><script type="text/javascript">$.ajax( {url : '/CPSolutionTest/services/update',type : 'POST',data : {a1:"a1111",a2:"a22222"},dataType : 'json',contentType:'application/json',async : false,success : function(data) {alert("success");alert(data.name);alert(data.age);$.ajax( {url : '/CPSolutionTest/services/requestTest',type : 'GET',data : {a11:"a1111111111111",a22:"a2222222222222"},dataType : 'json',contentType:'application/json',async : false,success : function(data) {alert("success");alert(data.name);alert(data.age);},error : function() {alert("ajax error");}});},error : function() {alert("ajax error");}});</script></head><body></body></html>

后台resource处理:

@Path("/")public class HelloWorld {    @GET    @Path("/helloWorld")    @Produces(MediaType.TEXT_PLAIN)    public String abc() {        String ret = "Hello World!";        return ret;    }    @POST    @Path("/update")    @Produces("application/json")    public Person update(@FormParam(value = "a1") String a1, @FormParam(value = "a2") String a2) {        System.out.println(a1);        System.out.println(a2);                return new Person("testPerson", "22");    }        @GET    @Path("/requestTest")    @Produces("application/json")    public Person update(@Context HttpServletRequest request) {        System.out.println("request:" + request.getParameter("a11"));        System.out.println("request:" + request.getParameter("a22"));        System.out.println("request:" + request.getQueryString());        return new Person("testPerson", "33");    }}

注意上面的ajax请求,第一个是post请求的update方法,@FormParam(value = "a1") String a1, @FormParam(value = "a2") String a2 这里的a1 和 a2就是前台传来的参数了,在update方法里就可以使用了。但是如果json数据很多,我们不可能在方法里一个个列出来,另外一种方法就是通过request来获取:@Context HttpServletRequest request。这里要注意的是请求的方法是GET。这样我们就可以很轻松的拿到前台json传来的参数了。而且可以获取session里的值。


这个测试就到这,谢谢

原创粉丝点击