Struts 2.x Model Driven Action – Using Netbeans IDE

The following example describes the use of Struts 2.x Model Driven Action – Using Netbeans IDE and uses Struts 2.x ActionSupport class and ModelDriven, Preparable and ServletRequestAware interfaces to depict the use of Model Driven Action in Struts 2.x (Java).

To perform this example create a Struts 2.x project using Netbeans IDE.

Project Tree :
project_structure

  • index.jsp

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

  • success.jsp

<%@page import=”data.Data”%> <%@page contentType=”text/html” pageEncoding=”UTF-8″%><% String o=(session.getAttribute(“n”)).toString(); out.println(o); Data d=(Data)session.getAttribute(“obj”); out.println(d.getCity()); out.println(d.getSex()); out.println(d.isDonot()); %>

  • Data.Jsp

package data;

public class Data {

private String name;

private String sex;

private boolean donot;

private String city;

public String getName() {

return name; }

public void setName(String name)

{ this.name = name;

} public String getSex() {

return sex; }

public void setSex(String sex) {

this.sex = sex; }

public boolean isDonot() {

return donot; }

public void setDonot(boolean donot) {

this.donot = donot; }

public String getCity() {

return city; }

public void setCity(String city)

{ this.city = city;

}}

  • One.java
package one;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import data.Data;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;

public class One extends ActionSupport implements ModelDriven, Preparable, ServletRequestAware{
    private Data data;
    private HttpServletRequest hsr;
    private HttpSession hs;
    @Override
    public Object getModel() {
        return data;
    }

    @Override
    public void prepare() throws Exception {
        this.data=new Data();
    }
    public String execute(){
        this.hs=hsr.getSession();
        hs.setAttribute("n", data.getName());
        hs.setAttribute("obj", data);
        return "success";
        
    }
    @Override
    public void validate(){
        if(data.getName().equals("")){
            addFieldError("name", "Name cannot be left blank");
        }
    }

    @Override
    public void setServletRequest(HttpServletRequest hsr) {
        this.hsr=hsr;
    }
}

 

Output:

Output2