简单的访问计数器

思路:表单每次访问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>


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值