思路:表单每次访问action,就会把上下文中的counter参数加一,jsp文件用来显示次数
LoginAction.java文件内容
package action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String username;
private String password;
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;
}
@Override
public String execute() throws Exception {
//获取上下文对象
ActionContext actionContext = ActionContext.getContext();
//计数器。通过上下文对象获得参数,从这些参数中获取名字叫"counter"这个对象
Integer counter = (Integer)actionContext.getApplication().get("counter");
if(counter == null) {
//如果没有找到这个对象,说明是第一次访问
counter = 1;
} else {
//计数器加一
counter++;
}
//修改过值的counter变量在放回上下文对象中
actionContext.getApplication().put("counter", counter);
return SUCCESS;
}
}
struts.xml文件加上,用于映射
<action name="LoginAction" class="action.LoginAction">
<result>/content/Test1.jsp</result>
</action>
Test1.jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<s:form action="LoginAction">
<s:submit/>
</s:form>
访问次数:${application.counter }
</body>
</html>