首页 > 代码库 > Action 类中访问Servelt API
Action 类中访问Servelt API
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class LoginCounterAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private String userName;
private String userPassword;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String counter(){
//获取当前 ActionContext对象
ActionContext context=ActionContext.getContext();
/*String yu="21312";
context.getApplication().put("yu", yu);*/
String appCounter=(String)context.getApplication().get("appCounter");
if(appCounter==null){
appCounter="1";
}else{
appCounter=Integer.toString((Integer.parseInt(appCounter)+1));
//System.out.println(appCounter);
}
context.getApplication().put("appCounter", appCounter);
if(userName!=null){
String sessionCounter=(String) context.getSession().get("sessionCounter");
if(sessionCounter==null){
sessionCounter="1";
}else{
sessionCounter=Integer.toString((Integer.parseInt(sessionCounter)+1));
//System.out.println(sessionCounter);
}
context.getSession().put("sessionCounter", sessionCounter);
return "success";
}else{
return "error";
}
}
}
<body>
<form action="/Chapter1/login.action" method="post">
账号<input type="text" name="userName" >
密码<input type="password" name="userPassword">
<input type="submit" value=http://www.mamicode.com/"登录">
</form>
</body>
<body>
恭喜${userName},您登陆成功! <br>
您是第${sessionScope.sessionCounter} 次访问本网站!<br>
本网站被访问了${applicationScope.appCounter} 次!<br>
</body>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3
//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="logincode" extends="struts-default">
<action name="login" class="com.yu.LoginCounterAction" method="counter">
<result name="success">/Test1/loginSuccess.jsp</result>
<result name="error">/Test1/loginFail.jsp</result>
</action>
</package>
</struts>
Action 类中访问Servelt API