得到post object的方式
一。序列化数据
public String testPost2() throws IOException{
System.out.println("得到POST传递过来的对象——doPost");
InputStream in = ServletActionContext.getRequest().getInputStream();
ObjectInputStream ois = new ObjectInputStream(in);
try{
LoginObj lo = (LoginObj)(ois.readObject());
System.out.println(lo.ip);
System.out.println(lo.port);
System.out.println(lo.uin);
TwoDimensionalCodeValidate tdcv = new TimeStampUUIDValidate();
System.out.println("validate:"+tdcv.validate(lo.two_dim_code));
if(tdcv.validate(lo.two_dim_code)){
System.out.println("--");
CacheOperation co = new MemCachedOperation();
co.saveData(lo);
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
二。非序列化数据
public String testPost() throws IOException{
System.out.println("----得到POST传递过来的对象——doPost start----");
InputStream in = ServletActionContext.getRequest().getInputStream();
byte[] bytes = new byte[1024*4];
int read = in.read(bytes);
System.out.println("read:"+read);
JSONObject returnjson = new JSONObject();
LoginObj obj = new LoginObj();
if( read > 0 )
{
String str = new String(bytes,0,read);
System.out.println(str );
try {
JSONObject json = new JSONObject(str);
obj.getValue(json);
TwoDimensionalCodeValidate tdcv = new TimeStampUUIDValidate();
System.out.println("validate:"+tdcv.validate(obj.two_dim_code));
if(tdcv.validate(obj.two_dim_code)){
CacheOperation co = new MemCachedOperation();
co.saveData(obj);
returnjson.put("ret", 1);
}else{
returnjson.put("ret", 2);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter out;
ServletOutputStream ps ;
ps = ServletActionContext.getResponse().getOutputStream();
//ps.print(returnjson.toString().getBytes("UTF-8"));
byte[] out_bytes = returnjson.toString().getBytes("UTF-8");
ps.write(out_bytes, 0, out_bytes.length);
ps.flush();
ps.close();
return null;
}else{
try {
returnjson.put("ret", 0);
} catch (JSONException e) {
e.printStackTrace();
}
PrintWriter out;
out = ServletActionContext.getResponse().getWriter();
out.print(returnjson);
return null;
}
}
本文详细介绍了通过Servlet API从POST请求中获取对象的方法,包括序列化与非序列化的两种实现方式。通过实例代码展示了如何在请求中接收和验证用户提交的数据,并进行相应的业务操作。
897

被折叠的 条评论
为什么被折叠?



