struts2 + jquery 登录、发送消息例子
LoginAction 登录 action, queryCurrentMsg 方法用于组织sql 查询当前登录人待接收信息;getCurrentSession 方法把当前登录人信息置放在 session 中,execute 主执行方法,继承于ActionSupport类
package com.longtop.components.jquery.action;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import net.sf.json.JSONObject;
import com.longtop.components.jquery.model.MessageModel;
import com.longtop.components.jquery.model.UserModel;
import com.longtop.conponents.db.DBConnection;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private static final Logger logger;
static {
logger = Logger.getLogger(LoginAction.class);
}
public UserModel getModel() {
return model;
}
public void setModel(UserModel model) {
this.model = model;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
private UserModel model;
private String result;
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private String password;
public String execute(){
Map sessions = getCurrentSession();
HttpSession session = (HttpSession) sessions.get("session");
session.setAttribute("username", this.username);
List list = queryCurrentMsg(this.username);
int count = list.size() > 0 ? list.size(): 0;
String sum = String.valueOf(count);
//MessageModel msg = (MessageModel)list.get(0);
Map<String, String> map = new HashMap<String, String>();
map.put("username", this.username);
map.put("password", this.password);
map.put("count", sum);
JSONObject json = JSONObject.fromObject(map);
this.result = json.toString();
System.out.println(this.result);
return SUCCESS;
}
private Map getCurrentSession(){
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse reponse = ServletActionContext.getResponse();
HttpSession session = request.getSession();
Map<String,HttpSession> map = new HashMap<String, HttpSession>();
map.put("session", session);
return map;
}
private List queryCurrentMsg(String ...params){
if (params.length <= 0) {
logger.error("params length is null!");
}
List<MessageModel> msgs = new ArrayList<MessageModel>();
String sql = "select * from wf_message msg where msg.msg_rec_id='"+params[0]+"'";
List list = (List)DBConnection.executionQuery(sql);
MessageModel model = new MessageModel();
model.setMsg_title((String) list.get(3));
model.setMsg_content((String)list.get(2));
msgs.add(model);
return msgs;
}
}