Form and Java Model class in Struts 2

February 7, 2018

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

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


<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@ taglib prefix="s" uri="/struts-tags" %>

    
        
        JSP Page
    
    
        

Login Form

Then you can create the TestAction.Java classs which will have refernce to your User bean class and ececute method

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



    
        
            /example/HelloWorld.jsp
        
      
            /thankyou.jsp