Struts2笔记3

1.Action接受请求参数

  在action中定义属性,并添加set方法,当从页面中传过来的参数中有名称一样的参数时会自动给action中的属性赋值,添加get方法就可以从在页面中得到action的属性值。get或者post方法都可以。如下:

package cn.itcast.action;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class helloworld {
    private String msg;
    
    public String getMessage() {
        return msg;
    }

    public void setMessage(String message) {
        this.msg = message;
    }

    public String execute() throws Exception{
        return "SUCCESS";
    }

}
 <form action="<%=request.getContextPath()%>/test/list.do" method="get">
    message:<input type="text" name="message"/>
    <input type="submit" value="发送"/>
<%@ page language="java" 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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${message }
</body>
</html>

还可以定义一个对象用来接收所有参数,如Person,参数名如person.id

package cn.itcast.action;


import javax.xml.registry.infomodel.PersonName;

public class helloworld {
    private Person person;
    
    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    public String execute() throws Exception{
        return "SUCCESS";
    }

}
package cn.itcast.action;

public class Person {
    private String id;
    private String name;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}
<form action="<%=request.getContextPath()%>/test/list.do" method="get">
    id:<input type="text" name="person.id"/><br/>
    name:<input type="text" name="person.name"/><br/>
    <input type="submit" value="发送"/>
</form>
<%@ page language="java" 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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${person.id }
${person.name }
</body>
</html>

默认Person对象为空的时候,会调用默认的构造函数新建对象,所以要提供默认的构造函数。(内部通过反射技术实现)。

注:Struts2.1.6会出现请求参数乱码问题

2.如果属性定义为Date类型,在地址路径中写http://localhost:8080/struts2/test/list.action?birthday=2013-01-14在页面中显示出的值为Mon Jan 14 00:00:00 CST 2013,但是如果传递的参数是20130114,就会报错,因为给action的属性赋值的时候会去找setBirthday参数为String类型的方法,找不到会报错。所以就要进行类型转换。

  struts2有两种类型转换,局部和全局,局部只对某个action起作用,全局是对所有action中的类都起作用。

  步骤如下:

  1)新建一个转换器类重写DefaultTypeContronter中的convertValue方法,可以进行双向转换

package cn.itcast.type.converter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;

public class DateConverter extends DefaultTypeConverter {

    @Override
    public Object convertValue(Map<String, Object> context, Object value,Class toType) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd");
        try{
            if(toType==Date.class){
                String[] params = (String[])value;
                return dateFormat.parse(params[0]);
            }else if(toType==String.class){
                Date date  = (Date)value;
                return dateFormat.format(date);
            }
        
        }catch (Exception e) {}
            return null;
    }
        
}

  2)在需要进行类型转换的Action的包下新建:Action名称-conversion.properties,如:helloworld-conversion.properties,在文件中写:属性名=类转换器的完成包名加类名

birthday=cn.itcast.type.converter.DateConverter

  3)将局部类型转换器改成全局类型转换器,将properties文件名称改为xwork--conversion.properties,放在src下,文件内容改为:类型的类名=类转换器的完成包名加类名

java.util.Date=cn.itcast.type.converter.DateConverter

   PS:这时类型转换器将多所有Date类型的数据进行转换,这时参数的格式只能是“19990909”这种形式,不能是“1999-9-9”

3.往application/session/request范围放入属性

     ActionContext ctx = ActionContext.getContext();
        ctx.getApplication().put("app", "应用范围");//往ServletContext里放入app
        ctx.getSession().put("ses", "session范围");//往session里放入ses
        ctx.put("req", "request范围");//往request里放入req

  得到application/session/request对象,并放入值

     HttpServletRequest request = ServletActionContext.getRequest();
        ServletContext servletContext = ServletActionContext.getServletContext();
        request.getSession();
        
        request.setAttribute("req", "request范围2");
        request.getSession().setAttribute("ses", "session范围2");
        servletContext.setAttribute("app", "应用范围2");

  在页面显示:

${applicationScope.app }<br/>
${sessionScope.ses }<br/>
${requestScope.req }<br/>

 4.文件上传

  1)在WEB-INF/lib目录下加入commons-fileupload-1.2.1.jar,commons-io-1.3.2.jar这两个jar包(commons-fileupload-1.2.1.jar这个在之前用struts的时候已经加入了,commons-io-1.3.2.jar是因为要使用FileUtils这个类)

  2)设置form表单

  <form enctype="multipart/form-data" action="${pageContext.request.contextPath }/test/fileUp.action" method="post">
        <input type="file" name="image">
        <input type="submit" value="上传"/>
    </form>

  3)写Action类

package cn.itcast.action;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

public class FileUp {
    private File image;
    private String imageFileName;
    
    public File getImage() {
        return image;
    }

    public void setImage(File image) {
        this.image = image;
    }

    public String getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    public String execute() throws IOException{
        String realPath = ServletActionContext.getServletContext().getRealPath("/images");
        System.out.println(realPath);
        if(image!=null){
            File savaFile = new File(new File(realPath),imageFileName);
            if(!savaFile.getParentFile().exists()){
                savaFile.getParentFile().mkdirs();
            }
            FileUtils.copyFile(image, savaFile);
            ActionContext.getContext().put("message", "上传成功");
        }
        return "success";
    }
}

  4)struts的配置

    <action name="fileUp" class="cn.itcast.action.FileUp" method="execute">
            <result name="success">/WEB-INF/pages/helloworld.jsp</result>
        </action>

  5)访问form表单的页面,上传成功后会自动跳转到helloworld.jsp

  6)默认的文件最大为2097152,如果超过,就要在struts.xml中设定常数

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

  PS:这个不能无限大,用网页上传,太大的话会失败

5.多文件上传

  1)将form改成多个input

<form enctype="multipart/form-data" action="${pageContext.request.contextPath }/test/fileUp.action" method="post">
        <input type="file" name="image"><br/>
        <input type="file" name="image"><br/>
        <input type="file" name="image"><br/>
        <input type="submit" value="上传"/>
    </form>

2)修改Action的属性及保存文件的代码

package cn.itcast.action;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

public class FileUp {
    private File[] image;
    private String[] imageFileName;
    
    

    public File[] getImage() {
        return image;
    }



    public void setImage(File[] image) {
        this.image = image;
    }



    public String[] getImageFileName() {
        return imageFileName;
    }



    public void setImageFileName(String[] imageFileName) {
        this.imageFileName = imageFileName;
    }



    public String execute() throws IOException{
        String realPath = ServletActionContext.getServletContext().getRealPath("/images");
        System.out.println(realPath);
        if(image!=null){
            File realPathFile = new File(realPath);
            if(!realPathFile.exists()){
                realPathFile.mkdirs();
            }
            for(int i=0;i<image.length;i++){
                File savaFile = new File(realPathFile,imageFileName[i]);
                FileUtils.copyFile(image[i], savaFile);
            }
            
            ActionContext.getContext().put("message", "上传成功");
        }
        return "success";
    }
}

 

posted @ 2013-01-24 16:14  柱柱  阅读(169)  评论(0编辑  收藏  举报