问题
I have created a simple program that gets the firstname and lastname of a user using a textfield. But the problem is that when I click the submit button I cannot redirect it to another jsp file which shows the firstname and lastname of the user.
Here's my HelloAction class:
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";
}
}
Here's my userInput.jsp file
<%@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>
Here's my resultInput.js file
<%@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>
Here's my struts-traning.xml file
<?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>
回答1:
You should use form tag with additional attributes that map the form to another action.
<s:form name="inputData" namespace="/exercise" action="submitData">
<s:textfield key="firstName"/>
<s:textfield key="lastName"/>
<s:submit/>
</s:form>
then for additional action you need to write action config
<action name="submitData" class="com.novamsc.training.struts.action.HelloAction"
method="save">
<result type="redirectAction">inputData</result>
</action>
add additional method to map the new action
public String save(){
return ActionSupport.SUCCESS;
}
This additional action is required to follow PRG (Post-Redirect-Get) pattern.
来源:https://stackoverflow.com/questions/44615535/cannot-redirect-a-jsp-file-and-display-values-using-struts-2