Search code examples
javaxmljspstruts2model-driven

Unable to execute Struts 2 program with ModelDriven interceptor


I am new to Struts 2 framework. I have made a program for understanding modelDriven interceptor. But I am unable to execute it. Following are the list of files and in the end there is a output (error).

index.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <%-- <jsp:useBean id="ent" class="pack.Entity" scope="session" /> --%>
    <s:form method="get" action="go">
        <s:textfield name="t1" label="Name"></s:textfield>
        <s:password name="p1" label="Password"></s:password>
        <s:submit value="accept"></s:submit>
    </s:form>
</body>
</html>

Entity.java:

package actions_pack;

public class Entity {
private String t1;
private String p1;
public String getP1() {
    return p1;
}

public void setP1(String p1) {
    this.p1 = p1;
}

public Entity() {
    super();
    // TODO Auto-generated constructor stub
}

public String getT1() {
    return t1;
}

public void setT1(String t1) {
    this.t1 = t1;
}

}

GoAction.java:

package actions_pack;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor;
import com.opensymphony.xwork2.util.ValueStack;
public class GoAction implements ModelDriven<Entity> {
    private Entity en;

    public Entity getEn() {
        return en;
    }
    public void setEn(Entity en) {
        this.en = en;
    }
    public String execute(){
        System.out.println("inside action");
        if(en.getT1().equalsIgnoreCase("nitin")){
            return "success";
        }
        else{
            return "failure";
        }
    }
    @Override
    public Entity getModel() {
        System.out.println("inside model driven....");
        en=new Entity();
        return en;
    }
}

struts.xml:

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <package name="dd">
            <result-types>
            <result-type name="dispatcher"
                class="org.apache.struts2.dispatcher.ServletDispatcherResult"
                default="true" />
        </result-types>
        <interceptors>
        <interceptor name="modelDriven" class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/>
        <interceptor-stack name="myStack">
        <interceptor-ref name="modelDriven"></interceptor-ref>
        </interceptor-stack>
        </interceptors>
        <action name="go" class="actions_pack.GoAction">
        <interceptor-ref name="myStack"></interceptor-ref>
            <result name="success" type="dispatcher" >/one/welcome.jsp</result>
            <result name="failure" type="dispatcher">/one/error.jsp</result>
        </action>
    </package>
</struts>

welcome.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Welcome, <s:property value="t1"/>
</body>
</html>

web-page output(500 error):

HTTP Status 500 -

type Exception report

message

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.lang.NullPointerException
    actions_pack.GoAction.execute(GoAction.java:24)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
    com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:563)
    org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.34 logs.

Apache Tomcat/7.0.34

In struts.xml file I don't want to use/extend struts-default package. Although, when I include params interceptor entry along with modelDriven interceptor in struts.xml, problem solves. What is the reason behind this. Can any one guide me?


Solution

  • You have a property in the action class that needs initialize prior to the action execution. You can do it in many ways.

    The way you have chosen relies on modelDriven interceptor which is running before your action is executed. It invokes getModel() to push it on top of the valueStack. So, your entity property is being initialized. If you remove this interceptor you will get NullPointerException when the action is executed.

    If your Entity is a simple POJO that you can instantiate yourself then simply do it inline instead of in getModel().

    private Entity en = new Entity();     
    
    @Override
    public Entity getModel() {
        System.out.println("inside model driven....");
        return en;
    }
    

    Next part is about params interceptor. It uses OGNL to populate a top object that is a model if you have used modelDriven interceptor prior params interceptor.

    Living it along with your action allows to initialize some properties you reference in the execute().

    For example t1 should be initialized.