package com;
import java.util.Map;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;
public class loginAction extends ActionSupport {
private String name;
private String pwd;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getPwd(){
return pwd;
}
public void setPwd(String pwd){
this.pwd=pwd;
}
public String checkLogin(){
ActionContext ac=ActionContext.getContext();//获得ActionContext
Map app=ac.getApplication();
ac.getSession().put("login",this.name);//把登录名称放入session中
ac.getApplication().put("login",this.name);//把登录名称放入application中
return SUCCESS;
}
}
loginAction比较简单,只有name和pwd两个属性,这里我们没有实现登录验证,只是简单地把登录名称存放到了session和application中。
下面在struts.xml 文件中对loginAction属性进行配置,代码如下所示:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="struts2_login" extends="struts-default" namespace="/login"> <action name="checkLogin" class="com.loginAction" method="checkLogin"> <result>/index.jsp</result> </action> </package> </struts>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <body> <center> <br> <h2>用户登录</h2> <s:form action="checkLogin" namespace="/login"> <s:textfield name="name" label="登录名称" size="15" /> <s:textfield name="pwd" label="登录密码" size="15" /> <s:submit value="登录" /> </s:form> </center> </body> </html>下面介绍显示登录信息的页面,新建一个名字为index.jsp的文件,代码如下所示:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <body> <br> <center><h2> 读取session中的信息:欢迎<s:property value="#session.login" />! <br><br> 读取application中的信息:欢迎<s:property value="#application.login" />! </body> </html>
该页面使用OGNL把存储在session和application中的信息读取了出来
关于OGNL知识,请查看http://blog.csdn.net/jdfkldjlkjdl/article/details/9863749