在之前的一篇文章中,讲过用MyEclipse作为服务器连接数据库输出xml格式的数据,这里记录一下如何输出json格式的数据,还是有有一点不同的。
环境:MyEclipse
所需要到的jar包:
json-lib-2.2.3-jdk15.jar
ezmorph-1.0.6.jar
commons-lang 2.4
commons-beanutils 1.7.0
commons-collections 3.2
commons-logging 1.1.1
这些jar包在网上都找得到。
创建一个web项目,然后再新建一个servlet的Java文件,在dopost()方法里操作你想要实现的json数据格式。这里贴出我写的:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCaracterEncoding(“UTF-8”);//汉字转码
response.setContentType("text/html");
PrintWriter out=response.getWriter();
JSONObject json=new JSONObject();
JSONObject json1=new JSONObject();
String msg="success";
int errorcode=0;
try{
Update dao=new Update();
List list=dao.getPersonList();
if(list.size()>0){
JSONArray jsonArray=new JSONArray();
for(PersonMsg person: list){
json1.put("id",person.getId());
json1.put("name",person.getName());
json1.put("major",person.getMajor());
jsonArray.add(json1);
}
json.put("data", jsonArray);
}else{
msg="没有符合要求的数据";
errorcode=1;
json.put("data","");
}
}catch(Exception e){
e.printStackTrace();
msg="系统错误";
errorcode=10000;
} finally{
json.put("message", msg);
json.put("errorcode", errorcode);
out.print(json);
out.flush();
out.close();
}
这里一定要记住写这一句:
response.setCaracterEncoding(“UTF-8”);//汉字转码
response.setContentType("text/html");
说明字符编码和内容类型,不然的话可能会出现乱码。
personMsg是一个实体类,定义了name和major两个属性,这个跟数据库同步。Update.java用于执行同步,即更新Android SQLite数据库中的数据。
最后部署到tomcat运行之后得到json:
{"data":[{"id":1,"name":"郭大侠","major":"计算机",},{"id":2,"name":"杨德柳","major":"数学"}],"message":"success","errorcode":0
很多跟上一篇都大同小异,就不细讲了。
接触过表单的同学应该比较清楚,比如我们在登录注册时会post你的账号密码。
这时dopost方法可以这样写:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String username=req.getParameter("username");
String password=req.getParameter("password");
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
if(username.equals("calolin")&&password.equals("123456")){
out.print("login success");
}else{
out.print("login failed");
}
out.flush();
out.close();
}
这里只做简单的验证,只是简单的返回信息。
接下来,你在浏览器输入 【url】?username=【参数】&password=【参数】回车,就可以返回信息。
这只是个引子吧,通过提交的参数返回不同的数据,从而在客户端能解析使用,加油吧骚年。
这两种方法有本质的区别,get只有一个流,参数附加在url后,大小个数有严格限制且只能是字符串。post的参数是通过另外的流传递的,不通过url,所以可以很大,也可以传递二进制数据,如文件的上传。
在servlet开发中,以doGet()和doPost()分别处理get和post方法。
首先判断请求时是get还是post,如果是get就调用doGet(), 如果是post就调用doPost()。都会执行这个方法。
1.doGet
GET 调用用于获取服务器信息,并将其做为响应返回给客户端。当经由Web浏览器或通过HTML、JSP直接访问Servlet的URL时,一般用GET调用。 GET调用在URL里显示正传送给SERVLET的数据,这在系统的安全方面可能带来一些问题,比如用户登录,表单里的用户名和密码需要发送到服务器端, 若使用Get调用,就会在浏览器的URL中显示用户名和密码。
2.doPost
它用于客户端把数据传送到服务器端,也会有副作用。但好处是可以隐藏传送给服务器的任何数据。Post适合发送大量的数据。
3.可以把方法写在doGet()方法中,在doPost()方法中调用执行,这样,无论你提交的是post还是get方法都可以执行,最好就用这种啦。