e.jsp页面;如果execute方法返回error字符串,则请求被转发到/error.jsp页面。 2.4.3 增加视图资源完成应用 经过上面步骤,这个最简单的Struts 2应用几乎可以运行了,但还需要为该Web应用增加两个JSP文件,两个JSP文件分别是error.jsp页面和welcome.jsp页面,将这两个JSP页面文件放在Web应用的根路径下(与WEB-INF在同一个文件夹下)。 这两个JSP页面文件是更简单的页面,它们只是包含了简单的提示信息。其中welcome.jsp页面的代码如下: <%@ page language=\contentType=\charset=GBK\
因此,借助于上面的Action接口,我们可以将原来的Action类代码修改为如下:
//实现Action接口来实现Struts 2的Action类 public class LoginAction implements Action {
//下面是Action内用于封装用户请求参数的两个属性 private String username; private String password;
//username属性对应的getter方法 public String getUsername() {
return username; }
//username属性对应的setter方法 public void setUsername(String username) {
this.username = username; }
//password属性对应的getter方法 public String getPassword() {
return password; }
//password属性对应的setter方法 public void setPassword(String password) {
this.password = password; }
//处理用户请求的execute方法
public String execute() throws Exception
{
//当用户请求参数的username等于scott,密码请求参数为tiger时,返回success 字符串
//否则返回error的字符串 if (getUsername().equals(\&& getPassword().equals(\) {
return SUCCESS; } else {
return ERROR; } } }
对比前面Action和此处的Action实现类,我们发现两个Action类的代码基本相似,除了后面的Action类实现了Action接口。因为实现了Action接口,故Action类的execute方法可以返回Action接口里的字符串常量。
2.5.2 跟踪用户状态
前面的Action处理完用户登录后,仅仅执行了简单的页面转发,并未跟踪用户状态信息——通常,当一个用户登录成功后,需要将用户的用户名添加为Session状态信息。
为了访问HttpSession实例,Struts 2提供了一个ActionContext类,该类提供了一个getSession的方法,但该方法的返回值类型并不是HttpSession,而是Map。这又是怎么回事呢?实际上,这与Struts 2的设计哲学有关,Struts 2为了简化Action类的测试,将Action类与Servlet API完全分离,因此getSession方法的返回值类型是Map,而不是HttpSession。
虽然ActionContext的getSession返回的不是HttpSession对象,但Struts 2的系列拦截器会负责该Session和HttpSession之间的转换。
为了可以跟踪用户信息,我们修改Action类的execute方法,在execute方法中通过ActionContext访问Web应用的Session。修改后的execute方法代码如下:
//处理用户请求的execute方法
public String execute() throws Exception {
//当用户请求参数的username等于scott,密码请求参数为tiger时,返回success字符串 //否则返回error的字符串 if (getUsername().equals(\&& getPassword().equals(\) {
//通过ActionContext对象访问Web应用的Session
ActionContext.getContext().getSession().put(\, getUsername()); return SUCCESS; } else {
return ERROR; } }
上面的代码仅提供了Action类的execute方法,该Action类的其他部分与前面的Action类代码完全一样。在上面的Action类通过ActionContext设置了一个Session属性:user。为了检验我们设置的Session属性是否成功,我们修改welcome.jsp页面,在welcome.jsp页面中使用JSP 2.0表达式语法输出Session中的user属性。下面是修改后的welcome.jsp页面代码:
<%@ page language=\contentType=\charset=GBK\
欢迎,${sessionScope.user},您已经登录!