packagebussiness;importjava.io.UnsupportedEncodingException;importjava.net.URLDecoder;importjava.net.URLEncoder;importjava.sql.SQLException;importjavax.servlet.http.Cookie;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.apache.commons.dbutils.QueryRunner;importorg.apache.commons.dbutils.handlers.BeanHandler;importorg.json.JSONObject;public classuserOperation {//定义全局变量
protectedHttpServletResponse response;protectedHttpServletRequest request;private final static String URL_CODE = "UTF-8"; //解决cookie存中文乱码
/** 统一获取数据的入口*/
public String getData(HttpServletRequest req, HttpServletResponse resp) throwsSQLException {
request=req;
response=resp;if ("userLoginCheck".equals(flags))returnuserLoginCheck();else if("userLoginOut".equals(flags))returnuserLoginOut();return "";
}/** 自定义用户注销*/
privateString userLoginOut() {
JSONObject jsonObject= newJSONObject();
addCookie(response,"userName","");
jsonObject.put("message", "userLoginOutSuccess");returnjsonObject.toString();
}/** 自定义用户登录函数*/
privateString userLoginCheck() {
JSONObject jsonObject= newJSONObject();try{
QueryRunner qr= newQueryRunner(DataSourceUtils.getDataSource());
String sql= "select * from http_login where name='" +name+ "' and password='" + password + "'";
userOperation user= qr.query(sql, new BeanHandler(userOperation.class));if(user!=null){
jsonObject.put("statusCode", 200);
jsonObject.put("referer", "index.html");
jsonObject.put("message", "用户登录成功。");//存储登录信息
addCookie(response,"userName",user.getName());
}else{
jsonObject.put("statusCode", 404);
jsonObject.put("referer", "/");
jsonObject.put("message", "用户或密码错误.");
}
}catch(SQLException e) {
e.printStackTrace();
}returnjsonObject.toString();
}/** addCookie,setCookie函数*/
private voidaddCookie(HttpServletResponse resp, String key, String value){try{
Cookie cookie= newCookie(key, URLEncoder.encode(value, URL_CODE));
cookie.setPath("/");
resp.addCookie(cookie);
}catch(UnsupportedEncodingException e) {
e.printStackTrace();
}
}privateString getCookie(HttpServletRequest req, String key){
Cookie[] cookies=req.getCookies();if (cookies != null) {try{for(Cookie cookie : cookies) {if(cookie.getName().equals(key))returnURLDecoder.decode(cookie.getValue(), URL_CODE);
}
}catch(UnsupportedEncodingException e) {
e.printStackTrace();
}
}return null;
}//实体bean参数以及getter/setter
privateString name;privateString password;privateString flags;publicString getFlags() {returnflags;
}public voidsetFlags(String flags) {this.flags =flags;
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}publicString getPassword() {returnpassword;
}public voidsetPassword(String password) {this.password =password;
}
}