Struts2总结

来源:互联网 发布:飞向札幌的班机js 编辑:程序博客网 时间:2024/06/05 09:31
引子:看完风中叶讲师的视频感觉不错,但毕竟是初次学struts2,感觉自己学的东西非常的零碎,所以,再将我学习的过程捋一下,可以使自己加深对struts2的理解,对struts2框架更加系统。下面就对struts2的各个模块分别系统的总结一下:

一、         构建struts2框架的基本配置

1、  创建项目

2、  导入struts2的五个基本jar包: commons-logging-1.0.4.jar:日志包、freemarker-2.3.13.jarognl-2.6.11.jarstruts2-core-2.1.6.jar:核心包、xwork-2.1.2.jarwebWork的核心包,struts2也依赖于它、commons-fileupload-1.2.1.jar

3、  配置项目下的web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <filter>

       <filter-name>struts2</filter-name>

       <filter-class>

           org.apache.struts2.dispatcher.FilterDispatcher

       </filter-class>

    </filter>

    <filter-mapping>

       <filter-name>struts2</filter-name>

       <url-pattern>/*</url-pattern>

    </filter-mapping>

</web-app>

4、  src目录下创建struts2的配置文件struts.xml

<?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" extends="struts-default">
    <action name="login" class="com.test.action.LoginAction">
        <result name="success">/result.jsp</result>
    </action>
</package>

</struts>

package里的extends与类的继承相似,struts-defaultstruts2里已经存在的包 action里的name与页面里表单里的action的值

5、  com.test.action包下建相应的Action

public class LoginAction extends ActionSupport {

    private String username;

    private String password;

    public String getUsername() {

       return username;

    }

    public void setUsername(String username) {

       this.username = username;

    }

    public String getPassword() {

       return password;

    }

    public void setPassword(String password) {

       this.password = password;

    }

    @SuppressWarnings("unchecked")

    public String execute() throws Exception {

       if ("hello".equals(this.getUsername().trim())

              && "world".equals(this.getPassword().trim())) {

                     @SuppressWarnings("unused")

           Map map=ActionContext.getContext().getSession();

           map.put("user","valid");

           return "success";

       }

       else{

           this.addFieldError("username","username or password error");

           return "failer";

       }

    }

    public void validate() {

       if (null == this.getUsername() || "".equals(this.getUsername().trim())) {

           this.addFieldError("username""username required");

       }

    if (null == this.getPassword() || "".equals(this.getPassword())) {

           this.addFieldError("password""password required");

       }

    }

}

:继承ActionSupport类,实现Action

二、         struts2类型转换

序:类型转换就是客户端用户输入的参数转化为服务器端java的对象,不管用户输入什么样的内容,到客户端都是以字符串的形式存在。

1、  某个Action类或类对象的属性需要类型转换,则要写一个.properties的属性文件,使其能找到完成类型转换的类,有两种方式:

第一种是局部属性文件,即在action包下创建,命名规则为action类名-conversion.properties,在属性文件里是以keyvalue对形式存在,keystruts2要转换的属性名,value是转换这个属性的类。当用户要转换多个属性里可以换行加多个

第二种是全局属性文件,即在src根目录下创建一个名为xwork-conversion.properties的属性文件(名字不可以更改),在里面写配置信息。形式是:要转换类的路径=作为转换器的类路径

2、  创建类型转换的类

转换类继承StrutsTypeConverter类,分别实现它里是面的convertToString(Map context, Object o)convertFromString(Map context, String[] values, Class toClass)两个抽象方法,代码如下:

public class PointConverter2 extends StrutsTypeConverter {

    public Object convertFromString(Map context, String[] values, Class toClass) {

       Point point = new Point();

       String[] paramValues = values[0].split(",");

       int x = Integer.parseInt(paramValues[0]);

       int y = Integer.parseInt(paramValues[1]);

       point.setX(x);

       point.setY(y);

       return point;

    }

    public String convertToString(Map context, Object o) {

       Point point = (Point) o;

       int x = point.getX();

       int y = point.getY();

       String result = " [ x=  " + x + ",  y=" + y + "]";

       return result;

    }

}

三、         struts2校验

序:输入校验是验证用户输入的信息是否合法是否有效。输入校验是建立在类型转换的基础之上的。若验证有错则显示提示信息。输入校验的流程是:首先,类型转换,然后校验,若都没错则执行execute()方法,,若出错,则跳转到input指向的页面。假若类型转换不成功也要进行校验。

1类型转换,如果类型转换失败系统有默认的错误提示信息,改变这种系统的错误提示信息有两种,就是有创建全局或局部的属性文件,首先全局的是在classes目录下写属性文件message.properties,内容是xwork.default.invalid.fieldvalue={0} error的键值对,在struts.xml中的配置是<constantname="struts.custom.i18n.resources" value="message"></constant>,其次局部的是在action包下创建“Action类名.properties”属性文件,内容格式:invalid.fieldvalue.属性名=要现实的信息。

2、校验,struts2提供的多种校验方式:

是在action中重写validate()方法,在其内对各个参数进行校验,校验代码如下:

public void validate() {

       if (null == username || username.length() < 6 || username.length() > 10) {

           this.addActionError("username invalid");

       }

       if (null == password || password.length() < 6 || password.length() > 10) {

           this.addActionError("password invalid");

       else if (null == repassword || repassword.length() < 6

              || repassword.length() > 10) {

           this.addActionError("repassword invalid");

       else if (!password.equals(repassword)) {

           this.addActionError("two password not the same");

       }

       if (age < 1 || age > 130) {

           this

                 .addActionError("\u8f93\u5165\u5e74\u9f84\u5e94\u8be5\u57280\u5c81\u5230120\u5c81\u4e4b\u95f4");

       }

        if(null==birthday){

        this.addActionError("birthday invalid");

        }

        if(null==graduation){

        this.addActionError("graduation invalid");

        }

       if (null != birthday && null != graduation) {

           Calendar c1 = Calendar.getInstance();

           c1.setTime(birthday);

           Calendar c2 = Calendar.getInstance();

           c2.setTime(graduation);

           if (!c1.before(c2)) {

              this.addActionError("birthday should before graduation");

           }

    }

:错误提示信息由action级别的,也有field级别的,field级别的,应在

<s:fielderror cssStyle="color:red" />标签内显示,action只需改fieldaction即可。可以用多种方式添加错误提示信息,可以在validate()方法中加入this.addActionError("password invalid");this.addFieldError("password""password invalid");以增加错误提示信息。

是最常用的xml校验方式,即在action包下创建名称为“Action类名-validation.xml”文件,系统运行是会自动寻找该文件进行校验,其格式参照第三章。这是对整个类的全局校验方式,如果action类中有多个校验方法,则用文件名为”Action类名-方法名-validation.xml”的校验文件对action类的某个方法进行校验。Xml内容格式与全局是一样的。

还以用js在客户端进行验证,使用方法是在struts2标签form中加入onsubmit=”return validate();”,待验证的每个struts标签中都加入一个唯一标志id,通过id获得提交的属性值。具体使用方法参照第三章。

四、         struts2校验框架

对上述校验的细化,可相对第四章。

五、         拦截器

1、创建拦截器类(这是一个验证用户是否登录的实例):

public class AuthInterceptor extends AbstractInterceptor {

    public String intercept(ActionInvocation invocation) throws Exception {

       Map map = invocation.getInvocationContext().getSession();//得到execute()中保存在session中的值

       if (map.get("user") == null) {

           return Action.LOGIN;//若为空则返回登录页面,需在struts.xml中配置

       else {

           return invocation.invoke();//若成功则到达指定页面

       }

    }

}

sessionaction类(execute方法)中已经写入,即

           @SuppressWarnings("unused")

           Map map=ActionContext.getContext().getSession();

           map.put("user","valid");

2、  配置struts.xml

Struts.xml中配置拦截器:

<interceptor name="auth" class="com.test.interceptor.AuthInterceptor">

</interceptor>

    //应用拦截器:

<interceptor-ref name="auth"></interceptor-ref>

<interceptor-ref name="defaultStack"></interceptor-ref>

若验证用户没登录则跳转到登录页面,在struts.xml中配置全局action

<global-results>

    <result name="login" type="redirect">/login2.jsp</result>

</global-results>

注:注意一定要加入<interceptor-ref name="defaultStack"></interceptor-ref>默认拦截器栈,否则出错。

六、         文件上传下载

上传

1、 导入两个jar包:commons-io-1.3.2.jarcommons-fileupload-1.2.1.jar

2、 文件上传jsp页面:

表单代码:

<s:form action="upload" theme="simple" enctype="multipart/form-data"

           method="post">

           <table align="center" border="1" width="50%">

              <tr>

                  <td>

                     file

                  </td>

                  <td id="more">

                     <s:file name="file"></s:file>

                     <input type="button" value="Add More.." onclick="addMore()">

                  </td>

              </tr>

              <tr>

                  <td>

                     <s:submit value="submit"></s:submit>

                  </td>

                  <td>

                     <s:reset value="reset"></s:reset>

                  </td>

              </tr>

           </table>

    </s:form>

js代码:

       <script type="text/javascript">

    function addMore(){

       var td=document.getElementById("more");

       var br=document.createElement("br");

       var input=document.createElement("input");

       var button=document.createElement("input");

       input.type="file";

       input.name="file";

       button.type="button";

       button.value="Remove";

       button.onclick =function(){

           td.removeChild(br);

           td.removeChild(input);

           td.removeChild(button);

       }

       td.appendChild(br);

       td.appendChild(input);

       td.appendChild(button);

    }

</script>

3、  上传文件的Action类核心代码:

public class UploadAction extends ActionSupport {

    private List<File> file;//上传多个文件用集合泛型

    private List<String> fileFileName;//文件名

    private List<String> fileContentType;//文件类型

    public List<File> getFile() {

       return file;

    }

    public void setFile(List<File> file) {

       this.file = file;

    }

    public List<String> getFileFileName() {

       return fileFileName;

    }

    public void setFileFileName(List<String> fileFileName) {

       this.fileFileName = fileFileName;

    }

    public List<String> getFileContentType() {

       return fileContentType;

    }

    public void setFileContentType(List<String> fileContentType) {

       this.fileContentType = fileContentType;

    }

    @Override

    public String execute() throws Exception {

       for (int i = 0; i < file.size(); i++) {

           InputStream is = new FileInputStream(file.get(i));

//         String root = ServletActionContext.getRequest().getRealPath(

//                "/upload");

//         String path="D://";

            String

            path=this.getClass().getResource("/").getPath();//得到d:/tomcat/webapps/工程名WEB-INF/classes/路径

            path=path.substring(1,

            path.indexOf("WEB-INF/classes"));//从路径字符串中取出工程路劲

            path=path+"/upload";

           File destFile = new File(path, this.getFileFileName().get(i));//在目的路径下医院文件名创建文件

           OutputStream os = new FileOutputStream(destFile);

           byte[] buffer = new byte[400];

           int length = 0;

           while ((length = is.read(buffer)) > 0) {

              os.write(buffer, 0, length);//写入硬盘

           }

           is.close();

           os.close();

       }

       return SUCCESS;

    }

}

4、  struts.xml文件上传配置

<action name="upload" class="com.test.action.UploadAction">

           <result name="success">/uploadResult.jsp</result>

           <result name="input">/upload.jsp</result>

           <interceptor-ref name="fileUpload">

              <param name="maximumSize">4096000</param>

              <param name="allowedTypes">application/vnd.ms-powerpoint</param>

           </interceptor-ref>

           <interceptor-ref name="defaultStack"></interceptor-ref>

    </action>

5、 上传结果显示页面

username:<s:property value="username"/><br>

password:<s:property value="password"/><br>

file:<s:property value="fileFileName"/>

下载

1、超链接jsp下载页面

    <s:a href="download.action">download</s:a>

2、下载核心代码action

public class DownloadAction extends ActionSupport {

    public InputStream getDownloadFile(){ 

       return ServletActionContext.getServletContext().getResourceAsStream("/upload/struts.ppt");

    }

    @Override

    public String execute() throws Exception {      

       return SUCCESS;

    }

}

3、 struts.xml配置

<action name="download" class="com.test.action.DownloadAction">

           <result name="success" type="stream">

              <param name="contentType">application/vnd.ms-powerpoint</param>

              <param name="contentDisposition">filename="struts.ppt"</param>

              <param name="inputName">downloadFile</param>

           </result>

    </action>

七、         struts2国际化

详细请参照第七章

0 0
原创粉丝点击