When the user submits a form you can bind the form to Java model class in Struct 2. We will see how to do it
First we will create the model class User.Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package example; public class User { private String firstName; private String lastName; public User(){ } @Override public String toString() { 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; } } |
Then you can create the jsp file to have the form. I am going to create a jsp file names person.jsp
and I will add following code to it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Login Form</h1> <s:form action="example/test.action"> <s:textfield name="userBean.firstName" label="First name" /> <s:textfield name="userBean.lastName" label="Last name" /> <s:submit value="Submit" /> </s:form> </body> </html> |
Then you can create the TestAction.Java
classs which will have refernce to your User bean class and ececute method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package example; import static com.opensymphony.xwork2.Action.SUCCESS; import com.opensymphony.xwork2.ActionSupport; public class TestAction extends ActionSupport { private User userBean; public User getUserBean() { return userBean; } public void setUserBean(User userBean) { this.userBean = userBean; } @Override public String execute() throws Exception{ System.out.println("Test"); return SUCCESS; } } |
Finally you can update your struts.xml
file
1 2 3 4 5 6 7 8 9 10 |
<struts> <package name="example" namespace="/example" extends="struts-default"> <action name="HelloWorld" class="example.HelloWorld"> <result>/example/HelloWorld.jsp</result> </action> <action name="test" class="example.TestAction"> <result>/thankyou.jsp</result> </action> </package> </struts> |