作者:更东陌飞絮蒙蒙 | 来源:互联网 | 2014-08-10 02:57
实现目的: 1.点击“Login”的超链接,进入登录页面 2.填写登录信息,提交表单,将用户信息保存进Session 3.显示用户名,并计算在线人数 4.点击“
实现目的:
1.点击“Login”的超链接,进入登录页面
2.填写登录信息,提交表单,将用户信息保存进Session
3.显示用户名,并计算在线人数
4.点击“Logout”的超链接,在线人数减一,并使Session失效
Struts2实现:
1.配置web.xml文件
struts2-LoginAndLogout
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
2.导入Struts2所需的基本jar包
3.编写Action类
package com.lewa.action;
import java.util.Map;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.SessionAware;
public class LoginAction implements SessionAware,ApplicationAware{
private static final String SUCCESS = "success";
private static final String LOGOUT="logout";
//与表单域中的属性相对应
private String username;
//JavaBean-style
public void setUsername(String username){
this.username=username;
}
public String execute(){
//将用户信息保存到Session中
//1.获取Session,通过SessionAware接口实现
//2.获取登录信息
//3.把登录信息保存到Session中
session.put("username", username);
//在线人数 +1
//1.获取当前在线人数,从Application中获取
Integer count=(Integer) application.get("count");
if(count==null){
count=0;
}
//使当前在线人数 +1
count++;
application.put("count", count);
return SUCCESS;
}
public String Logout(){
//在线人数 -1
//1.获取在线人数
Integer count=(Integer) application.get("count");
//2.在在线人数>0的情况下 -1
if(count!=null && count!=0){
count--;
application.put("count", count);
}
//使Session失效
((SessionMap)session).invalidate();
return LOGOUT;
}
private Map session;
@Override
public void setSession(Map session) {
// TODO Auto-generated method stub
this.session = session;
}
private Map application;
@Override
public void setApplication(Map application) {
// TODO Auto-generated method stub
this.application = application;
}
}
4.在struts.xml中配置Action
/login.jsp
/login-success.jsp
/logout-success.jsp
5.相应的JSP页面
index.jsp
<%@ page language="java" cOntentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
login.jsp
<%@ page language="java" cOntentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
login-success.jsp
<%@ page language="java" cOntentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
使用EL
欢迎,${sessionScope.username }
当前在线人数:${applicationScope.count }
使用OGNL和Struts2 标签
欢迎,
当前在线人数:
logout-success.jsp
<%@ page language="java" cOntentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
当前在线人数:${applicationScope.count }
6.用户请求的扩展名问题
> org/apache/struts2/default.properties: 配置了struts2应用的一些常量
> struts.action.extension=action, , 表示配置struts2受理请求扩展名(默认以.action或者无扩展)
> 在struts.xml文件中以常量配置的方式修改default.properties所配置的常量: