2017-06-18 110 views
1

我創建了一個簡單的程序,它可以獲取使用文本字段的用戶的名字和姓氏。但問題是,當我點擊提交按鈕時,我無法將它重定向到另一個顯示用戶名和姓氏的jsp文件。無法重定向jsp文件並使用Struts 2顯示值

這裏是我的HelloAction類:

package com.novamsc.training.struts.action; 

import com.opensymphony.xwork2.ActionSupport; 

public class HelloAction extends ActionSupport { 

    private String firstName; 
    private String lastName; 

    public String user(){ 
     return "hello"; 
    } 

    public String getFirstName() { 
     return firstName; 
    } 

    public void setFirstName(String firstName) { 
     this.firstName = firstName; 
    } 

    public String getLastName() { 
     return lastName; 
    } 

    public void setLastName(String lastName) { 
     this.lastName = lastName; 
    } 

    public String display(){ 
     return "hi"; 
    } 
} 

這是我的userInput.jsp文件

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<%@ taglib uri="/struts-tags" prefix="s"%> 

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>User Form</title> 
</head> 

<body> 
    <s:form name="inputData"> 
    <s:textfield key="firstName"/> 
    <s:textfield key="lastName"/> 
    <s:submit/> 
    </s:form> 

</body> 

</html> 

這裏是我的resultInput.js文件

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<%@ taglib uri="/struts-tags" prefix="s"%> 

<html> 

<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Get Result</title> 
</head> 

<body> 
    <p> 
    <s:property value="firstName" /> 
    </p> 
    <p> 
     <s:property value="lastName" /> 
    </p> 
</body> 

</html> 

這裏是我的支柱,traning.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="hello" namespace="/exercise" extends="training-default"> 

     <action name="userInput" class="com.novamsc.training.struts.action.HelloAction" 
      method="user"> 
      <result name="hello">/jsp/userInput.jsp</result> 
     </action> 

     <action name="inputData" class="com.novamsc.training.struts.action.HelloAction" 
      method="display"> 
      <result name="hi">/jsp/resultInput.jsp</result> 
     </action> 
    </package> 

</struts> 
+0

表單默認提交給同一個動作。如果您需要在提交表單後重定向到其他操作,那麼您應該使用重定向結果類型或更好地重定向操作結果類型。 –

+0

你能告訴我怎麼樣? –

+0

我已經告訴你如何,如果這是你的問題? –

回答

0

您應該使用表單標籤與映射形式到另一個動作的附加屬性。

<s:form name="inputData" namespace="/exercise" action="submitData"> 
    <s:textfield key="firstName"/> 
    <s:textfield key="lastName"/> 
    <s:submit/> 
</s:form> 

然後爲進一步的行動,你需要編寫動作配置

<action name="submitData" class="com.novamsc.training.struts.action.HelloAction" 
      method="save"> 
      <result type="redirectAction">inputData</result> 
</action> 

添加額外的方法來映射新的動作

public String save(){ 
     return ActionSupport.SUCCESS; 
} 

這額外的行動必須遵循PRG (Post-Redirect-Get)模式。