赞
踩
当初没有添加获取request的代码,所以总是反应空指针异常
下面我就给出一个实例程序来演示如何处理有多个submit的form:
【第1步】实现主页面(more_submit.jsp)
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%@ taglib prefix="s" uri="/struts-tags"%>
- <html>
- <head>
- <title></title>
- </head>
- <body>
- <s:form action="submit.action" >
- <s:textfield name="msg" label="请输入内容"></s:textfield>
- <s:submit name="save" method="save" value="保存"/>
- <s:submit name="print" method="print" value="打印" />
- </s:form>
- </body>
- </html>
在more_submit.jsp中有两个submit:保存和打印。其中分别通过method属性指定了要调用的方法:save和print。因此,在Action类中必须要有save和print方法。
【第2步】实现Action类(MoreSubmitAction)
- package action;
-
- import javax.servlet.http.HttpServletRequest;
-
- import org.apache.struts2.ServletActionContext;
-
- import com.opensymphony.xwork2.ActionContext;
- import com.opensymphony.xwork2.ActionSupport;
-
- public class FirstAction extends ActionSupport {
- private String msg;
-
- public String getMsg() {
- return msg;
- }
-
- public void setMsg(String msg) {
- this.msg = msg;
- }
-
- // 处理savesubmit按钮动作
- public String save() throws Exception {
- HttpServletRequest request=ServletActionContext.getRequest();
- request.setAttribute("result", "成功保存[" + msg + "]");
- return "save";
- }
-
- // 处理printsubmit按钮动作
- public String print() throws Exception {
- HttpServletRequest request=ServletActionContext.getRequest();
- request.setAttribute("result", "成功打印["+msg+"]");
- return "print";
- }
-
- }
【第3步】配置Struts2 Action
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="demo" extends="struts-default">
- <action name="submit" class="action.FirstAction">
- <result name="save">/result.jsp</result>
- <result name="print">/result.jsp</result>
- </action>
- </package>
- </struts>
【第4步】编写结果页(result.jsp)
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'result.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
-
- </head>
-
- <body>
- <h1>${result }</h1>
- </body>
- </html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。