转发请注明出处
1.页面传值。
传值
前台
<s:form action="login1">//action 名字 需要在structs配置
用户<s:textfield name="user.userName" type="text"/>//传对象
<s:textfield name="user.password" key="pass" />//传对象
<s:textfield name="password" key="pass" />//传值
<s:submit key="login" />
</s:form>
配置文件
<?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>
<constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant> <package name="userManager" namespace="/" extends="struts-default"> <!-- //登录 -->
<action name="login1" class="action.LoginAction" method="login">
<result name="success">/loginuser.jsp</result>
<result name="loginout">/adetails.jsp</result>
</action>
<!-- //登出 -->
<action name="loginout" class="action.LoginAction" method="loginout">
<result name="success">/login.jsp</result>
<result name="loginout">/adetails.jsp</result>
</action>
</package>
</struts>
后台类
import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import bean.User;
import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport{ /**
*
*/
private static final long serialVersionUID = 1L; private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
} //与前台页面name="password" 一致
public void setPassword(String password) {
this.password = password;
}
// 此处用于传对象
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user; //structs 把对应的值放到对象,在这里获取 user.userName,user.password 在这里把对象赋值,下面才可以调用
} public String login(){ HttpServletRequest request = ServletActionContext.getRequest();
System.out.println("111");
System.out.print(user);
request.getSession().setAttribute("username", user.getUserName());
request.getSession().setAttribute("user", user); System.out.println(user.getUserName());
return "success"; }
public String loginout(){
HttpServletRequest request = ServletActionContext.getRequest();
request.getSession().setAttribute("username", ""); /* HttpServletRequest request = ServletActionContext.getRequest();
request.getSession().setAttribute("username", user.getUserName());
或者 把Username 设置为空
*/ return "success"; } }
前台页面
<%@taglib prefix="s" uri="/struts-tags"%> <body>
<s:a href="loginout.action">登出
</s:a> 用户名:<s:property value="user.userName" />
密码:<s:property value="user.password"/>
<s:property value="password"/> 值:
<br>
用struts标签: <s:property value="#session.username" />
<br>
用EL表达式:${session.username}
<br>
用java代码:<%=session.getAttribute("username")%>
<br> 对象
<br>
用struts标签: <s:property value="#session.user.userName" />
<br>
用EL表达式:${session.user.password}
<br>
用java代码:<%=session.getAttribute("user")%>
此处还用到过滤器