package action;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.sun.org.apache.xml.internal.resolver.helpers.PublicId;
public class LoginAction implements Action,ServletRequestAware,ApplicationAware{
private String username;
private String password;
private HttpServletRequest request;
private Map application;
private static Map<String, String > users= new HashMap<String,String>();
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;
}
static {
users.put("join", "5678");
users.put("mike", "6666");
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
try{
HttpSession session = request.getSession();
Integer counter =(Integer) application.get("counter");
session.setAttribute("username", getUsername());
String pw = users.get(username);
if(pw==null){
request.setAttribute("info", "该用户不存在,登录失败");
return ERROR;
}else{
if(pw.equals(getPassword())){
if(counter == null){
counter =1;
}else{
counter++;
}
application.put("counter", counter);
request.setAttribute("info", "欢迎,已经成功登录");
return SUCCESS;
}else{
request.setAttribute("info", "密码错误,登录失败");
return ERROR;
}
}
}catch(Exception e){
return "fail";
}
/*
try{
ActionContext ctx = ActionContext.getContext();
Map application = ctx.getApplication();
Map session = ctx.getSession();
Integer counter = (Integer) application.get("counter");
//将用户名保存在HttpSession对象中
session.put("username", getUsername());
String pw= users.get(username);
if(pw==null){
//将处理结果保存在HttpServletRequest对象中
ctx.put("info", "该用户不存在,登录失败!");
return ERROR;
}else{
if(pw.equals(getPassword())){
if(counter==null){
counter=1;
}else{
counter++;
}
application.put("counter", counter);
ctx.put("info", "欢迎,已成功登录!");
return SUCCESS;
}else{
ctx.put("info", "密码有误,登录失败!");
return ERROR;
}
}
}catch(Exception e){
return ERROR;
}
*/
}
private String register() throws Exception{
// TODO Auto-generated method stub
return "register";
}
@Override
public void setApplication(Map<String, Object> application) {
// TODO Auto-generated method stub
this.application=application;
}
@Override
public void setServletRequest(HttpServletRequest request) {
// TODO Auto-generated method stub
this.request=request;
}
}
Struts逐步学习
最新推荐文章于 2020-06-15 19:12:56 发布