kisonlee
kisonlee
2009-08-25 10:32

请教关于在struts2中传递参数,怎么做,谢谢

已采纳

我有三个jsp,每个jsp都要填一些字段内容,我现在的做法是在每个jsp的action中将该jsp中的字段存入数据库,但这样存在两个问题,对数据库有压力,另外,在后两个jsp不是很好获得第一个jsp操作数据库时插入新的条目的id,后面就无法对应存入了。

现在,我想jsp1->jsp2>-jsp3,并在jsp3中获得3个jsp的参数,统一将这些 参数 存入数据库,请问如何传参,是否需要三个action呢,谢谢

另外问下,在数据库操作中,比如update xx value(...);之后,如何写SQL语句获得刚刚存入数据库的条目的id呢,谢谢
[b]问题补充:[/b]
lovewhzlq

不过三个jsp页面之间的跳转要在同一个请求中跳转 怎么理解

能给出具体的action的配置么,谢谢
[b]问题补充:[/b]
我的前两个jsp表单都很多
[b]问题补充:[/b]
lovewhzlq

那是不是三个jsp要请求三次action呀,能给出稍微具体点的配置么,谢谢
[b]问题补充:[/b]
那action的excute方法要执行三次?

可是这样的话我有些值还没传完整呢。。。
[b]问题补充:[/b]
在action中用method配置是么

另外,如果不配置方法,是不是三次执行action就执行三次excute呢
[b]问题补充:[/b]
jansel
能具体讲下ScopeInterceptor么,我也想了解,没找到太合适的资源,谢谢
[b]问题补充:[/b]
scopeInterceptor 主要起什么作用啊
[b]问题补充:[/b]
我上传了我的工程,数据库也包含在内,不过大家可以把登陆控制取消,改改,要不麻烦

主要有这么几个问题:
1.我在spread.action里面写了4个方法,可是从spread1.jsp->spread2.jsp就会出错,意思是没有input定义,可是我没发现action哪错啦
2.action权限拦截器貌似不起作用,直接进action还是可以,不知道怎么回事
3.登陆页面我启用了sx:head/,也配置了验证文件,但貌似无法异步验证,必须提交才行

spread.action
[code="java"]package action;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import javax.imageio.ImageIO;
import org.apache.struts2.ServletActionContext;
import bean.DBUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class Spread extends ActionSupport
{
private static final long serialVersionUID = 1L;

public String getLanguage()
{
    return language;
}
public void setLanguage(String language)
{
    this.language = language;
}
public String getType()
{
    return type;
}
public void setType(String type)
{
    this.type = type;
}
public String getTeachpoint()
{
    return teachpoint;
}
public void setTeachpoint(String teachpoint)
{
    this.teachpoint = teachpoint;
}
public String getLevel()
{
    return level;
}
public void setLevel(String level)
{
    this.level = level;
}
public String getTheme()
{
    return theme;
}
public void setTheme(String theme)
{
    this.theme = theme;
}
public String getMedia()
{
    return media;
}
public void setMedia(String media)
{
    this.media = media;
}
public String getFullname()
{
    return fullname;
}
public void setFullname(String fullname)
{
    this.fullname = fullname;
}
public String getKeyword()
{
    return keyword;
}
public void setKeyword(String keyword)
{
    this.keyword = keyword;
}
public String getAuthor()
{
    return author;
}
public void setAuthor(String author)
{
    this.author = author;
}
public String getIsbn()
{
    return isbn;
}
public void setIsbn(String isbn)
{
    this.isbn = isbn;
}
public Date getWritetime()
{
    return writetime;
}
public void setWritetime(Date writetime)
{
    this.writetime = writetime;
}
public Date getPublictime()
{
    return publictime;
}
public void setPublictime(Date publictime)
{
    this.publictime = publictime;
}
public String getLength()
{
    return length;
}
public void setLength(String length)
{
    this.length = length;
}
public String getWidth()
{
    return width;
}
public void setWidth(String width)
{
    this.width = width;
}
public String getHeight()
{
    return height;
}
public void setHeight(String height)
{
    this.height = height;
}
public String getPages()
{
    return pages;
}
public void setPages(String pages)
{
    this.pages = pages;
}
public String getColoredpages()
{
    return coloredpages;
}
public void setColoredpages(String coloredpages)
{
    this.coloredpages = coloredpages;
}
public String getWeight()
{
    return weight;
}
public void setWeight(String weight)
{
    this.weight = weight;
}
public String getMaterial()
{
    return material;
}
public void setMaterial(String material)
{
    this.material = material;
}
public String getIntro()
{
    return intro;
}
public void setIntro(String intro)
{
    this.intro = intro;
}
public File[] getUpload()
{
    return upload;
}

public void setUpload(File[] upload)
{
    this.upload = upload;
}
public String[] getUploadContentType()
{
    return uploadContentType;
}
public void setUploadContentType(String[] uploadContentType)
{
    this.uploadContentType = uploadContentType;
}
public String[] getUploadFileName()
{
    return uploadFileName;
}

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

public String getSavePath() 
{ 
    return ServletActionContext.getServletContext().getRealPath(savePath); 
} 
public void setSavePath(String savePath) 
{ 
    this.savePath = savePath; 
}
public String getChennel()
{
    return chennel;
}
public void setChennel(String chennel)
{
    this.chennel = chennel;
}
public String getMarketprice()
{
    return marketprice;
}
public void setMarketprice(String marketprice)
{
    this.marketprice = marketprice;
}
public String getSaleprice()
{
    return saleprice;
}
public void setSaleprice(String saleprice)
{
    this.saleprice = saleprice;
}
public String getAccess()
{
    return access;
}
public void setAccess(String access)
{
    this.access = access;
}

private boolean copy(File src, File dst)
{
    InputStream in = null;
    OutputStream out = null;
    try
    {
        try
        {
            in = new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);
            out = new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);
            byte[] buffer = new byte[BUFFER_SIZE];
            int len = 0; 
            while ((len = in.read(buffer)) > 0)
            {
                out.write(buffer, 0, len);
            }
            return true;
        } 
        finally
        {
            if (in != null)
            {
                in.close();
            }
            if (out != null)
            {
                out.close();
            }
        }
    } catch(Exception e)
    {
        e.printStackTrace();
    }
    return false;
}

private boolean checkSize(File [] files)
{
    BufferedImage image = null;
    for (int i = 0; i < files.length; i++)
    {
        try
        {
            image = ImageIO.read(files[i]);
        } catch(IOException e)
        {
            e.printStackTrace();
        }
        String size = null;
        if (image.getWidth() > 260 || image.getHeight() > 260)
        {
            size ="上传图片宽高不能超过260*260";
            ActionContext.getContext().put("size",size);
            return false;
        }
    }
    return true;
}

private String getRealPath(String imageString)
{
    return getSavePath() + "\\" + imageString;
}

public String firstStep()
{
    System.out.println(getLanguage());
    System.out.println(getTeachpoint());
    System.out.println(getLevel());
    System.out.println(getType());
    System.out.println(getTheme());

    return SUCCESS;
}

public String secondStep()
{
    System.out.println(getMedia());
    System.out.println(getFullname());
    System.out.println(getKeyword());
    System.out.println(getAuthor());
    System.out.println(getIsbn());
    System.out.println(getWritetime());
    System.out.println(getPublictime());
    System.out.println(getLength());
    System.out.println(getWidth());
    System.out.println(getHeight());
    System.out.println(getPages());
    System.out.println(getColoredpages());
    System.out.println(getWeight());
    System.out.println(getMaterial());
    System.out.println(getIntro());

    return SUCCESS;
}

public String thirdStep()
{
    File [] files = getUpload();
    if (!checkSize(files))
        return INPUT;

    for (int i = 0; i < files.length; i++)
    {
        imageFileName = new Date().getTime() + uploadFileName[i].substring(uploadFileName[i].lastIndexOf("."));
        File imageFile = new File(getSavePath() + "\\" + imageFileName); 
        copy(files[i],imageFile);
        realPath[i] = getRealPath(imageFileName);       
    }

    System.out.println(realPath[0]);
    System.out.println(realPath[1]);
    return SUCCESS;
}

public String forthStep()
{
    return SUCCESS;
}

private String language;
private String type;
private String teachpoint;
private String level;
private String theme;

private String media;
private String fullname;
private String keyword;
private String author;
private String isbn;
private Date writetime;
private Date publictime;
private String length;
private String width;
private String height;
private String pages;
private String coloredpages;
private String weight;
private String material;


private String intro;

private static final int BUFFER_SIZE = 16 * 1024;
private File[] upload;
private String[] uploadContentType;
private String[] uploadFileName;
private String imageFileName;
private String savePath;
private String [] realPath = new String[2];

private String chennel;
private String marketprice;
private String saleprice;
private String access;

}
[/code]
struts.xml
[code="java"]<?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">



<!--不受权限控制的Action请求配置-->


/spread/spread1.jsp
/login.jsp

<package name="authority" extends="struts-default">
    <interceptors>
        <interceptor name="authority" class="interceptor.AuthorityInterceptor" />
        <interceptor-stack name="mydefault">
            <interceptor-ref name="defaultStack" />
            <interceptor-ref name="authority" />
        </interceptor-stack>
    </interceptors>

    <default-interceptor-ref name="mydefault" />

    <global-results>
        <result name="login">/login.jsp</result>
    </global-results>

    <action name="FirstStep" class="action.Spread" method="firstStep">
        <result name="success">/spread/spread2.jsp</result>
    </action>

    <action name="SecondStep" class="action.Spread" method="secondStep">
        <result name="success">/spread/spread3.jsp </result>        
    </action>

    <action name="ThirdStep" class="action.Spread" method="thirdStep">
        <result name="success">/spread/spread4.jsp </result>
        <result name="input">/spread/spread3.jsp </result>
        <interceptor-ref name="fileUpload">
            <param name="allowedTypes">image/jpeg,image/pjpeg</param>
            <param name="maximumSize">204800</param>
        </interceptor-ref>
        <param name="savePath">/upload</param>
    </action>

    <action name="ForthStep" class="action.Spread" method="forthStep">
        <result name="success">/spread/spreadSucc.jsp</result>      
    </action>
</package>



[/code]
权限拦截器
[code="java"]public class AuthorityInterceptor extends AbstractInterceptor
{
private static final long serialVersionUID = 1L;

public String intercept(ActionInvocation invocation) throws Exception
{
    ActionContext ctx = invocation.getInvocationContext();
    String user = (String)ctx.getSession().get("username");
    System.out.print(user);
    if (user != null)
    {
        return invocation.invoke();
    }
    System.out.print(user);
    ctx.put("tip", "您还没有登录,请登陆系统");
    return Action.LOGIN;
}

}[/code]怎么才能起作用呢,而且tip值怎么显示出来
web.xml
[code="java"]<?xml version="1.0" encoding="UTF-8"?>
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_2_5.xsd">

SetCharacterEncodingFilter
filter.SetCharacterEncodingFilter

encoding
UTF-8



SetCharacterEncodingFilter
/*

<filter>
    <filter-name>accessFilter</filter-name>
    <filter-class>filter.AccessFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>accessFilter</filter-name>
    <url-pattern>/spread/*</url-pattern>
</filter-mapping>

<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>

<servlet>
    <servlet-name>dwr</servlet-name>
    <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
    <init-param>
        <param-name>debug</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>dwr</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
</servlet-mapping>


<welcome-file-list>
    <welcome-file>modelIndex.jsp</welcome-file>
</welcome-file-list>


[/code]
登陆页面
[code="java"]<%@ page language="java" import="java.util.*"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%@taglib prefix="sx" uri="/struts-dojo-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">




sx:head/











/s:form

[/code]
谢谢大家
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

22条回答

  • iteye_15225 iteye_15225 12年前

    LZ 还是再熟悉一下Struts2吧 。

    这种最好的方式当然是ScopeInterceptor了。要是再好一点的就集成Spring的 Webflow搞定。

    一个Action也可以处理,三个Action也可以处理。

    点赞 评论 复制链接分享
  • skysnowking skysnowking 12年前

    我学得可以用这样复制一个bean入在一个地方,用时再弄出来,这是struts1.2项目时我用的。

    点赞 评论 复制链接分享
  • iteye_1557 iteye_1557 12年前

    [b][size=xx-large][color=orange]晕! 其它方法不可以就用一个简单的方法撒,放到application中就OK啦[/color][/size][/b]

    点赞 评论 复制链接分享
  • iteye_15225 iteye_15225 12年前

    LZ 这个我就帮不了了 自己就没想过找一下Struts2的文档看一下吗?

    This is designed to solve a few simple issues related to wizard-like functionality in Struts. One of those issues is that some applications have a application-wide parameters commonly used, such pageLen (used for records per page). Rather than requiring that each action check if such parameters are supplied, this interceptor can look for specified parameters and pull them out of the session.

    This works by setting listed properties at action start with values from session/application attributes keyed after the action's class, the action's name, or any supplied key. After action is executed all the listed properties are taken back and put in session or application context.

    To make sure that each execution of the action is consistent it makes use of session-level locking. This way it guarantees that each action execution is atomic at the session level. It doesn't guarantee application level consistency however there has yet to be enough reasons to do so. Application level consistency would also be a big performance overkill.

    Note that this interceptor takes a snapshot of action properties just before result is presented (using a PreResultListener), rather than after action is invoked. There is a reason for that: At this moment we know that action's state is "complete" as it's values may depend on the rest of the stack and specifically - on the values of nested interceptors.
    Interceptor parameters:
    •session - a list of action properties to be bound to session scope
    •application - a list of action properties to be bound to application scope
    •key - a session/application attribute key prefix, can contain following values:
    ◦CLASS - that creates a unique key prefix based on action namespace and action class, it's a default value
    ◦ACTION - creates a unique key prefix based on action namespace and action name
    ◦any other value is taken literally as key prefix
    •type - with one of the following
    ◦start - means it's a start action of the wizard-like action sequence and all session scoped properties are reset to their defaults
    ◦end - means that session scoped properties are removed from session after action is run
    ◦any other value or no value means that it's in-the-middle action that is set with session properties before it's executed, and it's properties are put back to session after execution
    •sessionReset - name of a parameter (defaults to 'session.reset') which if set, causes all session values to be reset to action's default values or application scope values, note that it is similar to type="start" and in fact it does the same, but in our team it is sometimes semantically preferred. We use session scope in two patterns - sometimes there are wizard-like action sequences that have start and end, and sometimes we just want simply reset current session values.
    •reset - boolean, defaults to false, if set, it has the same effect as setting all session values to be reset to action's default values or application.
    •autoCreateSession - boolean value, sets if the session should be automatically created.
    Extending the interceptor:

    There are no know extension points for this interceptor.
    Example code:

    <!-- As the filter and orderBy parameters are common for all my browse-type actions,
    you can move control to the scope interceptor. In the session parameter you can list
    action properties that are going to be automatically managed over session. You can
    do the same for application-scoped variables-->




    filter,orderBy
    true

    good_result.ftl

    点赞 评论 复制链接分享
  • iteye_15225 iteye_15225 12年前

    jsp1--->action中可以配置哪些数据可以放在session中;

    action--->jsp2--->action中可以配置哪些字段可以从session中获取;

    以此类推,这样做的好处就是不用jsp2页面中使用hidden值来保存jsp1传送过来的值;因为hidden的值,可能会从客户端修改的,不安全;而且这样写代码也是比较简单的,如果传输的值比较多,页面写起来就很头疼。

    至于scopeInterceptor LZ可以看一下Struts2 的showcase 里面有一个类似的例子

    点赞 评论 复制链接分享
  • pwz1985 dsfsdfsdfdsfsdfds 12年前

    变态的需求。。

    点赞 评论 复制链接分享
  • skysnowking skysnowking 12年前

    你想要达到什么样的目的呢!
    我觉得你可以用最笨的办法遥request.getSession().set^你们知道是什么意思吧!
    不过这样不太好!
    我也是刚学struts!

    点赞 评论 复制链接分享
  • sun201200204 sun201200204 12年前

    不明白你为什么要用struts。
    第一个jsp直接传值到第二个jsp,第二个jsp传值到第三个jsp。然后第三个jsp去用struts就OK了吗?

    点赞 评论 复制链接分享
  • walsh_bupt walsh_bupt 12年前

    [size=large][color=red]晕,最简单的方法就是,你只写一个Action,然后每个页面都让这个Action处理,然后在这个Action中写对应的三个方法,每个页面调用相应的方法就行了,别把你的execute()方法写进去,然后在配置文件中配置,就OK了。[/color][/size]

    点赞 评论 复制链接分享
  • iteye_19440 iteye_19440 12年前

    jsp的form中直接写action="user!onAdd.action"

    这样说明白么?

    点赞 评论 复制链接分享
  • iteye_19440 iteye_19440 12年前

    可以http://..../user!onAdd.action这种方式可以直接调用action中的方法

    user是action名儿
    onAdd是action中的方法

    点赞 评论 复制链接分享
  • wanghaolovezlq wanghaolovezlq 12年前

    如果不配置方法,自然就是三次执行action就执行三次excute

    点赞 评论 复制链接分享
  • wanghaolovezlq wanghaolovezlq 12年前

    你不是非要用excute方法啊,可以写三个方法对应三个jsp
    action可以配置执行的方法嘛,

    点赞 评论 复制链接分享
  • iteye_19440 iteye_19440 12年前

    可以写多个方法啊 ,不必在一个方法上吊死,再者你也可以在excute中用参数区别开嘛

    点赞 评论 复制链接分享
  • iteye_19440 iteye_19440 12年前

    比如action中有属性 a , b , c 分别对应jsp1 ,jsp2 ,jsp3中的参数

    当你提交jsp1时,给a赋值,然后跳转到jsp2,提交jsp2时给b赋值...依次类推

    只要按action的默认的result type ,属性a,b,c是一直存在的

    点赞 评论 复制链接分享
  • iteye_19440 iteye_19440 12年前

    也就是 action的result type 默认的就可以 ,不要redirect

    点赞 评论 复制链接分享
  • wanghaolovezlq wanghaolovezlq 12年前

    这样的话,当然是三个jsp要请求三次action,你不请求action,怎么把参数传给action呢

    点赞 评论 复制链接分享
  • iteye_19440 iteye_19440 12年前

    1,如果三个页面在同一个action中,可以参数都对应到action中的属性

    2.也可以在跳转到下一个jsp2时,将上一个jsp1的参数带入jsp2,在jsp2的表单中以 hidden隐藏域的形式出现

    点赞 评论 复制链接分享
  • wanghaolovezlq wanghaolovezlq 12年前

    也就是默认的这种就是在同一个请求的跳转

    点赞 评论 复制链接分享
  • walsh_bupt walsh_bupt 12年前

    有以下几种办法:
    1.把你的参数放到session中

    2.如果你的前一个页面参数不是太多,那就作为下一个页面表单中的隐藏域,然后通过最后一个页面提交给Action进行处理。

    点赞 评论 复制链接分享
  • wanghaolovezlq wanghaolovezlq 12年前

    可以用一个action来实现,三个jsp页面的参数都对应到action的属性,

    不过三个jsp页面之间的跳转要在同一个请求中跳转,

    点赞 评论 复制链接分享
  • javagaoran javagaoran 12年前

    如果你的业务是连贯的。那么请把你的参数值放入到session中去。或者参数一个一个往下传。都是可行的。

    点赞 评论 复制链接分享

相关推荐