struts2标签基本知识

 

http://blog.sina.com.cn/s/blog_55d6c18f0100gvno.html

<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
</head>
<body>
<s:form action="login.action" method="post" name="student" enctype="multipart/form-data">

      <s:textfield label="姓名" name="student.username"
       tooltip="Enter your Name here" />
  
      <s:textfield label="密码" name="student.password"
       tooltip="Enter your password here" />

      <s:textarea tooltip="Enter your remart" label="备注" name="remart"
       cols="20" rows="3" />
   
    <!-- 在value中设置默认选中哪个项 -->
  
      <s:select tooltip="Choose user_type" label="用户类型"
       list="#{'dayi':'大一','daer':'大二'}" value="#{'dayi':'大一'}"
       name="student.user_type" emptyOption="false" headerKey="None"
       headerValue="None" />
  
     
      <s:checkboxlist tooltip="Choose your Friends" label="朋友"
       list="{'Patrick', 'Jason', 'Jay', 'Toby', 'Rene'}"
       value="{'Patrick','Jason'}" name="friends" />
  
      <s:doubleselect tooltip="Choose Your State" label="State"
       name="region" list="{'North', 'South'}" value="'North'"
       doublue="'Florida'"
       doubleList="top == 'North' ? {'Oregon', 'Washington'} : {'Texas', 'Florida'}"
       doubleName="state" headerKey="-1"
       headerValue="---------- Please Select ----------"
       emptyOption="true" />
  
      <s:checkbox tooltip="Confirmed that your are Over 18" label="年龄"
       name="legalAge" value="18" />
  
    <!-- 上传附件 -->
        
     <s:file tooltip="Upload Your Picture" label="Picture"
       name="picture" />
  
      <s:submit />
</s:form>
</body>
</html>

 

 

 

 

 

struts2 对于form表单的一个tomcat警告

2008-06-02 10:07

tomcat控制台会打出如下警告:
WARN - No configuration found for the specified action: 'xxxxx'in namespace: '/'. Form action defaulting to 'action' attribute's literal value.

如果在jsp页面使用了 标签 <s:form action="xxxx.action"></s:form>就会出现上边警告

原因是 struts.xml中struts.action.extension 已经默认给你加上了.action 在页面就不用显示的加了

所以修改为: <s:form action="xxxx"></s:form>

 

 

 

Struts2 拦截器的学习笔记

2008-06-04 20:19

1.自己定义一个拦截器,像MyInterceptor这个类这样,
package com.yan.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class MyInterceptor implements Interceptor{
public void destroy() {
   System.out.println("destroy");  
}
public void init() {
   System.out.println("init");  
}
public String intercept(ActionInvocation invocation) throws Exception {
   System.out.println("intercept");
   String result=invocation.invoke();
   return result;
}
}
然后再struts.xml中进行配置:
在<package>标签下
   <interceptors>
<interceptor name="myInterceptor" class="com.yan.interceptor.MyInterceptor"></interceptor>
   </interceptors>

2.要把这个拦截器应用到那个action上的话,就在相应的action中进行配置
像这样:
<action name="register" class="com.yan.action.RegisterAction">
    <result name="success">/success.jsp</result>
    <result name="input">/register.jsp</result>
    <interceptor-ref name="myInterceptor"></interceptor-ref>
</action>
3.在struts.xml中的这句话<package name="struts2" extends="struts-default">
意思是定义这个包名strut2,然后这个包会继承struts2-core-2.0.11.1.jar这个jar包中
org.apache.struts2下面的struts-default.xml这个文件中的内容,在这个文件中会看到
定义了许多的拦截器,这些拦截器就是struts2的核心,它们会拦截我们的请求并加入一些处理,
像表单属性的自动添加、表单的自动校验。但是,大家可以在这个文件的最后看到一句
<default-interceptor-ref name="defaultStack"/>这句话说明,默认的拦截器是一个拦截器
栈(拦截器栈里面可以放很多个拦截器),这个defaultStack的定义在本文件的209行(我的是这样)
<interceptor-stack name="defaultStack">这个里面定义引用了一系列的拦截器。当我们没有
自定义拦截器的时候,这些拦截器会自动的加到我们的每个action上作为默认的拦截器,但是当我们自定
义了拦截器后像1、2步做的那样时,默认的拦截器就会被覆盖,调用这个action的时候不会调用默认的
拦截器了,这就是为什么我的的表单的自动验证等一些默认的功能不起作用的原因了因此这时候我们必须
手动地配置默认拦截器,只需要把第2步的配置增加一句,像这样:
<action name="register" class="com.yan.action.RegisterAction">
    <result name="success">/success.jsp</result>
    <result name="input">/register.jsp</result>
    <interceptor-ref name="myInterceptor"></interceptor-ref>
    <interceptor-ref name="defaultStack"/>
   </action>
  
这样就行了。
至此一个拦截器就配置完成了。

4.当然我们可以自己定义一个拦截器栈

   <interceptors>
  
<interceptor name="myInterceptor" class="com.yan.interceptor.MyInterceptor"></interceptor>

   <interceptor-stack name="mystack">
    <interceptor-ref name="myInterceptor"></interceptor-ref>
    <interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>

   </interceptors>
下面就这样配置就可以了
   <action name="register" class="com.yan.action.RegisterAction">
    <result name="success">/success.jsp</result>
    <result name="input">/register.jsp</result>
    <interceptor-ref name="mystack"/>
   </action>
5.如果你的每一个action都要调用某个自定义的拦截器的话,可以在struts.xml文件中
自己设置默认的拦截器,这样就不用每一个action都配置一遍拦截器了
像这样:
<package>标签下
   <default-interceptor-ref name="mystack"></default-interceptor-ref>

 

 

 

 

 

 

 

Struts 2.0实现文件上传

2008-12-11 12:49

 

Struts2使用开源项目Apache Jakarta Commons FileUpload和内建的FileUploadInterceptor拦截器实现文件上传,所需的jar包如下:

commons-logging-1.1.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
struts2-core-2.0.6.jar
xwork-2.0.1.jar
commons-io-1.3.1.jar
commons-fileupload-1.2.jar

一:单文件止传

1.文件上传页面 fileUpload.jsp

<body>
    <s:form action="/fileUpload.action" method="post" enctype="multipart/form-data">
        <s:fielderror></s:fielderror>
        <s:file name="myFile" label="图片上传"></s:file>
        <s:textfield name="caption" label="标题"></s:textfield>
        <s:submit value="提交"></s:submit>
    </s:form>  
</body>

2.创建FileUploadAction.java:处理文件上传

   
public class FileUploadAction extends ActionSupport {
   
    private static final int BUFFER_SIZE = 10*1024;
    private File myFile; //对应页面文件name
    private String contentType; //文件类型
    private String fileName; //文件名
    private String imageFileName; //
    private String caption; //标题
   
    public void setMyFileContentType(String contentType){
        this.contentType = contentType;
    }
   
    public void setMyFileFileName(String fileName){
        this.fileName = fileName;
    }
   
    public void setMyFile(File myFile){
        this.myFile = myFile;
    }
   
    public String getImageFileName(){
        return imageFileName;
    }
   
    public String getCaption(){
        return caption;
    }
   
    public void setCaption(){
        this.caption = caption;
    }
   
    public static void copy(File src,File dst){
        InputStream in = null; //输入流
        OutputStream out = null;//输出流
       
        try {
            in = new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);
            out = new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);
            byte[] buffer = new byte[BUFFER_SIZE];
            while (in.read(buffer)>0 ) {
                out.write(buffer);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
   
    public static String getExtention(String fileName){
        int pos = fileName.lastIndexOf(".");
        return fileName.substring(pos);
    }

    @Override
    public String execute() throws Exception {
        //创建新的文件名(系统时间+原文件扩展名)
        Date date = new Date();
        String newFileName = this.getExtention(fileName);
        imageFileName = date.getTime()+newFileName;
        //创建新文件保存路径
        File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages")+"/"+imageFileName);
        this.copy(myFile, imageFile);
        return SUCCESS;
    }
}

在fileupload.jsp中,只有doc一个字段,而FileUploadAction.java中,却有三个字段,Struts2怎么通过页面的 一个字段设置Action里的三个字段呢?没错,这就是FileUploadInterceptor的功劳了!你所要做的只是按照一定的样式命名这三个字 段的set方法,而字段名可以任意命名。第一个File类型的字段的set方法还是以常规的方式命名,另两个String类型的字段的set方法必须分别 以“File字段的set方法名+FileName”和“File字段的set方法名+ContentType”来命名。

3.struts.xml配置

<!-- 文件上传配置 -->
    <package name="fileupload" namespace="/" extends="struts-default">   
        <action name="fileUpload" class="fileupload.FileUploadAction">
            <interceptor-ref name="fileUpload">
                <param name="allowedTypes">
                    image/bmp,image/png,image/gif,image/jpeg
                </param>
            </interceptor-ref>
            <interceptor-ref name="fileUploadStack"></interceptor-ref>
            <result name="input">/fileupload/fileUpload.jsp</result>
            <result name="success">/fileupload/showUpload.jsp</result>
        </action>
    </package>

4.web.xml配置

<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>
   
    <filter>
        <filter-name>struts-cleanup</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts-cleanup</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

5.显示页面:showUpload.jsp

<body>
    <img src='UploadImages/<s:property value="imageFileName"/>'/>
    <br>
    <s:property value="caption"/>
</body>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

二:多文件上传

Struts 2实现多文件上传也很简单。你可以将多个<s:file />绑定Action的数组或列表。如下例所示。

< s:form action ="doMultipleUploadUsingList" method ="POST" enctype ="multipart/form-data" >
< s:file label ="File (1)" name ="upload" />
< s:file label ="File (2)" name ="upload" />
< s:file label ="FIle (3)" name ="upload" />
< s:submit />
</ s:form >

如果你希望绑定到数组,Action的代码应类似:

private File[] uploads;
private String[] uploadFileNames;
private String[] uploadContentTypes;

public File[] getUpload() { return this .uploads; }
public void setUpload(File[] upload) { this .uploads = upload; }

public String[] getUploadFileName() { return this .uploadFileNames; }
public void setUploadFileName(String[] uploadFileName) { this .uploadFileNames = uploadFileName; }

public String[] getUploadContentType() { return this .uploadContentTypes; }
public void setUploadContentType(String[] uploadContentType) { this .uploadContentTypes = uploadContentType; }

如果你想绑定到列表,则应类似:

private List < File > uploads = new ArrayList < File > ();
private List < String > uploadFileNames = new ArrayList < String > ();
private List < String > uploadContentTypes = new ArrayList < String > ();

public List < File > getUpload() {
return this .uploads;
}
public void setUpload(List < File > uploads) {
this .uploads = uploads;
}

public List < String > getUploadFileName() {
return this .uploadFileNames;
}
public void setUploadFileName(List < String > uploadFileNames) {
this .uploadFileNames = uploadFileNames;
}

public List < String > getUploadContentType() {
return this .uploadContentTypes;
}
public void setUploadContentType(List < String > contentTypes) {
this .uploadContentTypes = contentTypes;
}

你可能感兴趣的:(struts2标签)