JavaEE的Struts2框架

来源:互联网 发布:微信联系人数据库恢复 编辑:程序博客网 时间:2024/06/01 10:23

Struts2的三个重要构件

  1. 核心控制器 filterDispatcher;
  2. 逻辑组件 javaBean;
  3. 业务控制器 Action。

Struts2的基本包

可以到官网上下载轻松版:struts-2.5.10-min-lib.zip。

这里写图片描述

struts.xml的配置文件的结构

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

表明这是一个xml文件。

< !DOCTYPE struts PUBLIC “-//Apache Software Foundation //DTD Struts Configuration 2.5//EN” “http://localhost:8080/项目名称/WEB-INF/classes/struts-2.5.dtd”

DTD的定义
DTD(Document Type Definition)是对文档类型的定义。
不同的struts版本对应不同的dtd文件。
!DOCTYPE标签的格式
DTD声明始终以!DOCTYPE开头,空一格后跟着文档根元素的名称,如struts。
如果是内部DTD(私有DTD),则再空一格出现[],在中括号中是文档类型定义的内容.。
而对于外部DTD,则又分为私有DTD与公共DTD。
私有DTD使用SYSTEM表示,接着是外部DTD的URL。
公共DTD则使用PUBLIC,接着是DTD公共名称,接着是DTD的URL。
外部DTD之公共DTD的格式
DTD名称格式为”注册//组织//类型 标签//语言”。
“注册”指示组织是否由国际标准化组织(ISO)注册,+表示是,-表示不是。
“组织”即组织名称,如:Apache Software Foundation。
“类型”一般是DTD。
“标签”是指定公开文本描述,即对所引用的公开文本的唯一描述性名称,后面可附带版本号,如Struts Configuration 2.5。
“http://localhost:8080/项目名称/WEB-INF/classes/struts-2.5.dtd”
表示已经下载好的struts-2.5.dtd文件被存放在项目中的位置。
xml解析器通过该位置找到dtd文件,并利用它来检查当前xml文档的合法性。
也可以在可以上网的情况下,换成这个:

"http://struts.apache.org/dtds/struts-2.5.dtd"

struts标签

常量配置

< constant name="struts.devMode" value="true"/ >

struts.devMode也就是struts的开发模式,默认值为false,这里修改为true就可以了,以后一旦修改这个文件中的配置就不用去重启tomcat,着实方便许多。
后来经过多次查找发现有人说这个属于struts2.1的bug,tomcat目录不能有空格。我仔细一瞧我的tomcat路径,还真出现空格的。。。

<constant name="struts.action.extension" value=".do"/>  

此为设置action的访问扩展名为.do。

<constant name="struts.i18n.encoding" value="utf-8"/>

此为设置参数编码为utf-8。

<constant name="struts.multipart.maxSize" value="1075555555"/>

此为设置文件上传允许的最大字节数。

<constant name="struts.multipart.saveDir" value="C:/temp"/>

此为指定上传文件时的临时文件夹。

bean配置

<bean name="bean的名字" class="自定义的组件类"/>

包配置

< package name="struts2" extends="struts-default" namespace="/可不写">

所有的Action配置都应该放在package下。
name是你自定义的包名,extends表示你所继承的包空间,默认为struts-default。
拦截器配置
struts2框架提供了一系列拦截器。
拦截器配置应放在package下。
拦截器的作用就是在执行action之前或之后进行某种拦截操作。
例如,用户请求删除某些数据时,拦截器会首先判断用户是否有权删除,如果有,就通过action删除,如果没有权限,就不会执行action操作。
interceptor-stack是一堆拦截器组成的一个拦截器栈。也可以当拦截器使用。
interceptor-ref是指定某个action使用哪一个拦截器,可以是一个interceptor,也可以是一个interceptor-stack。

<interceptors>    <interceptor-stack name="拦截器栈名字">          <!--定义拦截器-->          <interceptor-ref  name="拦截器名字"   class="拦截器类的类名"/>    </interceptor-stack></interceptors>

action配置
result中的name值是execute的返回值。

<action name="login" class="com.action.LoginAction">        <result name="success">/main.jsp</result>        <result name="error">/login.jsp</result> </action>

在action中可以通过框架提供的ActionContext类获取Servlet中的参数。
ActionContext类是一个局部线程,每个线程中的内容都是唯一的。
action就是一个普通的java类,如下。

package com.action;import java.util.Map;import com.bean.LoginBean;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;public class LoginAction extends ActionSupport{    private String act;    private String pwd;    public String getAct() {        return act;    }    public void setAct(String act) {        this.act = act;    }    public String getPwd() {        return pwd;    }    public void setPwd(String pwd) {        this.pwd = pwd;    }    public String execute() throws Exception {        LoginBean lb=new LoginBean();        if(lb.login(act, pwd)){            Map session=ActionContext.getContext().getSession();            session.put("account", getAct());            return SUCCESS;        }        else   return ERROR;    }}

在Action中需要注意的是:

Action中重写的方法(如validate())在Action执行时,会自动运行。

在web.xml中配置Struts2的核心控制器FilterDispatcher

web.xml根标签web-app规范:

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee       http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  

javaee就是j2ee就是jdk+jre就是开发工具包+运行时环境即Java虚拟机。
XML结构定义 ( XML Schemas Definition )
XML Schema 是DTD的替代品。XML Schema语言也就是XSD。
可以说,XML Schema是多种XSD文件的集合。
XML Schema描述了XML文档的结构。可以用一个指定的XML Schema来验证某个XML文档,以检查该XML文档是否符合其要求。文档设计者可以通过XML Schema指定一个XML文档所允许的结构和内容,并可据此检查一个XML文档是否是有效的。XML Schema本身是一个XML文档,它符合XML语法结构。可以用通用的XML解析器解析它。
一个XML Schema会定义:文档中出现的元素、文档中出现的属性、子元素、子元素的数量、子元素的顺序、元素是否为空、元素和属性的数据类型、元素或属性的默认和固定值。
XSD是DTD替代者的原因,一是据将来的条件可扩展,二是比DTD丰富和有用,三是用XML书写,四是支持数据类型,五是支持命名空间。
XSD文件的后缀名为.xsd。
XML Schemas for Java EE Deployment Descriptors
意思是:为Java EE的所有部署描述符 服务的 XML结构定义文件。
xmlns
是xhtml namespace 的缩写,中文名为xml(标准通用标记语言的子集)命名空间。
产生原因:xml解析器无法处理标签命名冲突。
用它来指明该webapp的xml命名空间。

xmlns="http://java.sun.com/xml/ns/javaee"

xsi
是xml schema instance 的缩写,中文名为 xml 结构规范 。

用它来指明web-app_3_0.xsd文件的位置。

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

以下代码表示 命名空间的结构规范。

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

filter配置
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter的来源:
将struts2-core-2.5.jar解压,如下图:

<!-- 过滤器 --> <filter>      <!-- struts2核心控制器器名-->      <filter-name>struts2</filter-name>      <!-- struts2核心控制器的类-->      <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>  </filter>  <!-- 过滤器的URL映射 -->  <filter-mapping>      <!-- struts2核心控制器器名 -->      <filter-name>struts2</filter-name>      <!-- 拦截所有URL请求 -->      <url-pattern>/*</url-pattern>  </filter-mapping><!-- 指定会话超时的时间间隔 -->  <session-config>      <session-timeout>30</session-timeout> </session-config> 

ServletActionContext

action可以通过struts2提供的ServletActionContext类来获取servlet

//调用ServletActionContext.getRequest()方法获取requestHttpServletRequest request=ServletActionContext.getRequest();HttpSession session=request.getSession();session.setAttribute("username",this.username);session.setAttribute("password",this.password);

Struts2的OGNL表达式

  1. ${根对象的属性} ,如获取业务控制器的属性:
 ${name}
  1. 井号 名称空间 . 属性,如获取request、session、application的属性:
 #request.name #session.name #application.name

Struts2的标签库

写在< html >前。

<%@ taglib prefix="s" tri="/struts-tags" %>
<s:if test="   'a' in {'a','b'}   " >     .     .     .</s:if><s:if test="   'a' not in {'a','b'}   " >     .     .     .</s:if>//?:用于获取符合逻辑的多个元素//^:用于获取符合逻辑的第一个元素//$:用于获取符合逻辑的最后一个元素//获取Student的所有sex值为male的集合Student.sex{?#this.sex=='male'}

Struts2的信息验证

前端验证
用JavaScript写。
服务器验证
在execute()中进行验证。

Struts2的数据定时更新

支持ajax需要的包
struts2-dojo-plugin-1.3.4.1.jar
导入jsp页面

<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>//只在页面加载时获取数据<sx:div id="" theme="ajax" href="%{getData}"></sx:div>   //每6s更新一次数据,并延迟2s<sx:div id="" theme="ajax" href="%{getData}" updateFreq="6000" delay="2000"></sx:div>   

Struts2的抽象拦截器

package interceptor;import com.opensymphony.xwork2.Action;//action对象import com.opensymphony.xwork2.ActionInvocation;//action调用import com.opensymphony.xwork2.Interceptor.AbstractInterceptor;public class MyInterceptor extends AbstractInterceptor{     //方法重写     public String intercept(ActionInvocation ai) throws Exception{         //获取action的实例         Object object=ai.getAction();         //这里用PublicAction指代某一个Action类         if(object!=null)         {             if(object instanceof PublicAction){                   PublicAction ac=(PublicAction)object;                   //获取用户提交的评论                   String content =ac.getcontent();                   //判断内容中是否有需要过滤的内容                   if(content.contains("操蛋")){                        //以"**"代替"操蛋"                        content = content.replaceAll("操蛋","**");                        ac.setContent(content);                   }                   //对象不空,继续执行                   //actionInvocation.invoke() 就是通知struts2接着干下面的事情比如 调用下一个拦截器 或 执行下一个Action                   return ai.invoke();                   else{                       //返回给action一个结果(逻辑字符串)                       return  ACTION.静态成员常量;                   }              }         }          return  ACTION.静态成员常量;     }}

Struts2的文件上传和下载

文件上传必要包
commons-fileupload-1.2.2.jar
文件上传,只需要普通的Action就可做到。

fileUpload.jsp<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><%@ taglib prefix="s" uri="/struts-tags" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>上传页面</title></head><body>   <s:form action="fileUpload" method="post" enctype="multipart/form-data">       <s:file name="file" label="上传文件"></s:file>       <s:submit value="上传"/>       <s:reset value="重置"/>   </s:form></body></html>
result.jsp<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>result</title></head><body>  文件上传成功!<br> 上传文件名:${fileFileName}<br> 上传文件类型:${fileContentType}</body></html>

Struts2提供了文件上传拦截器(fileUpload),可对文件的大小和类型等进行过滤

struts.xml<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"    "http://struts.apache.org/dtds/struts-2.5.dtd"><struts>   <!--  设置全局常量,设置文件上传允许的最大值为10MB = 10*1024*1024 = 10485760 Byte,value的值以字节为单位-->   <constant name="struts.multipart.maxSize" value="10485760"></constant>    <package name="Action" extends="struts-default">        <action name="fileUpload" class="Action.FileUploadAction">            <result name="success">/result.jsp</result>            <result name="input">/fileUpload.jsp</result>            <result name="error">/fileUpload.jsp</result>            <interceptor-ref name="defaultStack">                <!-- 限制上传文件的最大值为4MB -->                <param name="fileUpload.maximumSize">4194304</param>                <param name="fileUpload.allowedExtensions">.txt,.doc,.jpg</param>                <param name="fileUpload.allowedTypes">text/plain,application/octet-stream,image/jpeg</param>            </interceptor-ref>        </action>    </package></struts>
web.xml<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>SinglesFileUpload</display-name>  <jsp-config>        <jsp-property-group>            <url-pattern>*.jsp</url-pattern>            <page-encoding>UTF-8</page-encoding>            <default-content-type>text/html</default-content-type>        </jsp-property-group>    </jsp-config>  <filter>     <filter-name>struts2</filter-name>     <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>  </filter>  <filter-mapping>     <filter-name>struts2</filter-name>     <url-pattern>/*</url-pattern>  </filter-mapping>  <welcome-file-list>    <welcome-file>fileUpload.jsp</welcome-file>  </welcome-file-list></web-app>

格式要求详解链接:http://blog.csdn.net/u013234928/article/details/51014075

package Action;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class FileUploadAction extends ActionSupport{    //注意:这个uploadFileName,uploadContentType。如果File 属性名xxx(private File xxx;) 。那这个必须是xxxFileName, xxxContentType。然后也是分别给set 方法就可以。    //提交过来的文件、文件名、文件类型    //注意,file并不是指前端jsp上传过来的文件本身,而是文件上传过来存放在临时文件夹下面的文件    private File file;    private String fileFileName;    //提交过来的file的MIME类型    private String fileContentType;    public String getFileFileName() {        return fileFileName;    }    public void setFileFileName(String fileFileName) {        this.fileFileName = fileFileName;    }    public File getFile() {        return file;    }    public void setFile(File file) {        this.file = file;    }    public String getFileContentType() {        return fileContentType;    }    public void setFileContentType(String fileContentType) {        this.fileContentType = fileContentType;    }    @Override    public String execute() throws Exception {        System.out.println("真实文件名: " + fileFileName);        // 因为file是存放在临时文件夹的文件,我们可以将其文件名和文件路径打印出来,看和之前的fileFileName是否相同        System.out.println("临时文件名: " + file.getName());        System.out.println("临时文件存储路径: " + file.getPath());        //文件输入流:将   临时文件信息   写入文件输入流        FileInputStream in=new FileInputStream(file);        //设置文件保存的目录,前提是在WebRoot下你自己建立upload文件夹        String uploadPath=ServletActionContext.getServletContext().getRealPath("/upload");        //在服务器端创建一个空壳文件  new File(保存的文件夹路径,目标文件名)        File toFile=new File(uploadPath,fileFileName);        //文件输出流:将文件信息注入到服务器上的那个空壳文件里        FileOutputStream out=new FileOutputStream(toFile);        byte[] unit=new byte[1024];        int length=0;        //读取文件信息,并将其一份一份地输出到空壳文件里  in.read(数组首地址,起始位置,结束位置)        while(-1!=(length=in.read(unit,0,unit.length))){             out.write(unit);        }        //关闭输入流和输出流        in.close();        out.close();        System.out.println("上传成功"+uploadPath);          return SUCCESS;    }}

中文显示浏览器中的错误提示信息
struts2默认的错误提示信息配置在struts-messages.properties文件中,此文件以key-value的形式配置,其位置在struts2的核心包中。
要使错误提示信息显示为中文,只需新建一个国际化资源文件,重写上面的4个配置。
(1)创建FileUploadMessage.properties放置在src目录下的Action包中:

struts.messages.error.uploading = 上传错误:【{0}】struts.messages.error.file.too.large=上传文件过大:【{0}】【{1}】【{2}】【{3}】struts.messages.error.content.type.not.allowed=上传文件的类型不允许:【{0}】【{1}】【{2}】【{3}】struts.messages.error.file.extension.not.allowed=上传文件的后缀名不允许:【{0}】【{1}】【{2}】【{3}】

(2)在struts.xml中加载该资源文件:

<constant name="struts.custom.i18n.resources"     value="Action.FileUploadMessage"/>

文件下载必要包
commons-io-2.0.1.jar
文件下载,需要在struts.xml中先配置下载拦截器(download)及其参数值。
参数有:
1. contentType:指定文件类型
2. filename:指定文件名
3. inputName:指定下载文件的输入流的入口
4. contentDisposition:指定文件下载的处理方式
5. bufferSize:指定下载文件时的缓存大小
文件下载时可进行权限控制,比如说没登陆或者没充值就不给下载。
这里写图片描述

download.jsp<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>下载页面</title></head><body>    <!-- href中字符串不能有空格,否则会出错 -->    <a href="/FileDownLoad/simpledownload.action?filename=15移动开发毕业设计项目.doc">15移动开发毕业设计项目.doc</a></body></html>
DownLoadAction.javapackage Action;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import org.apache.struts2.ServletActionContext;import sun.misc.BASE64Encoder;import com.opensymphony.xwork2.ActionSupport;public class DownLoadAction extends ActionSupport{    private String filename;    private String contentType;   //代表下载文件的MimeType    /*获取文件名称*/    public String getFilename() throws IOException{        //对不同浏览器传过来的文件名进行编码        System.out.println("文件名:"+filename);        return encodeDownLoadFilename(filename,ServletActionContext.getRequest().getHeader("User-Agent"));    }    public void setFilename(String filename) throws UnsupportedEncodingException{        //对文件名进行编码        filename=new String(filename.getBytes("iso8859-1"),"utf-8");        this.filename = filename;    }    /*获取文件类型*/    public String getContentType() {        System.out.println("文件类型:"+contentType);        return ServletActionContext.getServletContext().getMimeType(filename);    }    public void setContentType(String contentType) {        this.contentType = contentType;    }    /*定义了返回InputStream的方法,该方法作为被下载文件的入口*/    public InputStream getDownLoadFile() throws IOException{        //要被下载的文件在服务器的路径        String filepath="/upload/"+filename;        System.out.println("文件路径:"+filepath);        return ServletActionContext.getServletContext().getResourceAsStream(filepath);    }    @Override    public String execute() throws Exception {        // TODO Auto-generated method stub        return SUCCESS;    }    /*对不同浏览器传过来的文件名称进行转码    @param name 文件名称    @param agent 浏览器    @return 转码后的名称*/    public String encodeDownLoadFilename(String name,String agent) throws IOException{        if(agent.contains("Firefox")){            //火狐浏览器            name="=?UTF-8?B?"+new BASE64Encoder().encode(name.getBytes("utf-8"))+"?=";        }else{            //IE及其他浏览器            name=URLEncoder.encode(name, "utf-8");        }        return name;    }}
struts.xml<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"    "http://localhost:8080/FileDownLoad/WEB-INF/classes/struts-2.5.dtd"><struts>    <package name="Action" extends="struts-default">       <!--  包名和class名的大小写和内容必须正确,否则会报错 -->        <action name="simpledownload" class="Action.DownLoadAction">            <result type="stream">                 <!-- 将Action.FileDownloadAction中的对象属性contentType传过来,并用ognl表达式动态指定文件类型 -->                 <param name="contentType">${contentType}</param>                 <!-- 动态指定文件真实名称 ,其中${filename}中的值是由类Action.DownLoadAction传过来的,其变量名必须与类中的属性名filename一致-->                 <param name="contentDisposition">attachment;filename=${filename}</param>                 <!-- 输入流 的名字,与Action中的获取输入流的方法名getDownLoadFile()要一致-->                 <param name="inputName">DownLoadFile</param>            </result>        </action>    </package></struts>

struts2与spring整合所必须的包

struts2-spring-plugin-版本号.jar

Tomcat启动失败的常见原因

(1)struts2的版本与你所写的dtd文件版本不一致
比如:struts2.5对应的dtd版本应为struts-2.5.dtd;
struts2.3对应的dtd版本应为struts-2.0.dtd。
(2)struts的核心控制器配置的类的版本不一致
比如:struts2.1.8和struts2.3.24对应的核心控制器配置的类为

org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

struts2.3.4对应的核心控制器配置的类为

org.apache.struts2.dispatcher.Filter.FilterDispatcher

struts2.5对应的核心控制器配置的类为

org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
原创粉丝点击