码迷,mamicode.com
首页 > 其他好文 > 详细

Struts2的Action(二)

时间:2015-03-18 01:08:50      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

  Struts2的Action可以是一个POJO(即简单的javaBean),也实现Action接口,或者继承ActionSupport类。

  1.Action接口:

public interface Action {
    public static final String SUCCESS = "success";
    public static final String NONE = "none";
    public static final String ERROR = "error";
    public static final String INPUT = "input";
    public static final String LOGIN = "login";
    public String execute() throws Exception;
}

  将LoginAction实现Action接口,则execute方法可以改为:

public String execute() {
        if(getUserName().equals("kaima") && getPassword().equals("asd")) {
            return SUCCESS;
        }
        else
            return ERROR;
    }

  Action运行所用到的数据都保存在ActionContext中,继续修改我们的LoginAction:

    public String execute() {
        if(getUserName().equals("kaima") && getPassword().equals("asd")) {
            ActionContext.getContext().getSession().put("name", userName);
            return SUCCESS;
        }
        else
            return ERROR;
    }

  上面这句话相当于session.setAttribute("name", userName)。这样,在我们的JSP页面中就能使用name这个值了。

 

  2.ActionSupport类就比较复杂,提供了数据校验功能。

  将LoginAction继承ActionSupport类,修改execute并覆盖validate()方法:

    public String execute() {
        if(getUserName().equals("kaima") && getPassword().equals("asd")) {
            return SUCCESS;
        }
        else
            return ERROR;
    }
    
    @Override
    public void validate() { //validate方法在execute之前执行
        if(userName == null || userName.equals(""))
            this.addFieldError("username", "用户名不能为空");
        if(password == null || password.equals(""))
            this.addFieldError("password", "密码不能为空");
    }

  validate()方法会在execute方法前执行,如果没通过,会将错误信息存放到Action的fieldError中,并将请求转发到input对应的逻辑视图中。在struts.xml中指定input对应的视图:

<?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>
   <package name="myStruct" extends="struts-default">
      <action name="login" class="myWeb.LoginAction"> 
            <result name="success">/welcome.jsp</result>
            <result name="error">/error.jsp</result>
            <result name="input">/login.jsp</result>
      </action>
   </package>
</struts>

  如果想将错误信息显示出来,需要在login.jsp中加上:

<%@ taglib uri="/struts-tags" prefix="s" %>

  并在你想显示错误信息的地方加上:

<s:fielderror></s:fielderror>
<form action="login.action" method="post">
<table>......

  这里我是在table前加上错误信息的显示,如果用户不输入用户名/密码,就会如下:

技术分享

Struts2的Action(二)

标签:

原文地址:http://www.cnblogs.com/programmer-kaima/p/4346006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!