方式一、使用ServletActionContext(耦合度高,不建议使用)
public String login(){ ServletActionContext.getRequest().getSession().setAttribute("user","王彬"); return "success"; } Struts.xml <action name="login" class="cn.xcq.entity.Action1" method="login"> <result>/success.jsp</result> </action> Success.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <h1>成功页面</h1> ${sessionScope.user} </body> </html>
方式二、实现接口
这个案例使用session作用域,所以实现SessionAware接口 Struts2底层将作用域都封装成了Map。 public class Action1 implements SessionAware { //声明一个Map private Map<String, Object> session; //使用session需 实现sessionaware接口 //requesr RequestAware接口。。。。 public String login(){ session.put("user","程高升"); return "success"; } //重写SessionAware的setSession方法,将声明的session赋值给它 @Override public void setSession(Map<String, Object> map) { this.session=map; } } Success.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <h1>成功页面</h1> ${sessionScope.user} </body> </html>
方式三、ActionContext
//方式三 public String login(){ //session Map<String, Object> session = ActionContext.getContext().getSession(); session.put("user","林帅"); //request Map<String, Object> request =(Map<String, Object>) ActionContext.getContext().get("request"); request.put("name","程高升"); return "success"; }