Unable to execute Struts 2 program with ModelDriven interceptor - java

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?

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.

Related

Exception while registering custom interceptor in Struts2

I am new to Struts2 framework. i am working with custom interceptors to write logic for session management in my interceptor class which would be fired before accessing home page.here I have dummy custom interceptor only to check wether it executes or not but it throws exception while registering interceptor class. I dont know that is reason behind it.I just want it to work so that I could write my main logic than. Thanks dev.
Here is my code.
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<s:form action="login">
<s:textfield name="name" label="Username"/>
<s:submit value="Submit"/>
</s:form>
</body>
</html>
struts.xml
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- Configuration for the default package. -->
<package name="default" extends="struts-default">
<interceptors>
<interceptor name="MyInterceptor" class="MyActions.MyInterceptor"/>
<interceptor-stack name="mystack">
<interceptor-ref name="MyInterceptor"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<action name="default">
<result>index.jsp</result>
</action>
<action name="login" class="MyActions.Login">
<interceptor-ref name="mystack"/>
<result name="SUCCESS">success.jsp</result>
</action>
</package>
</struts>
MyInterceptor.java
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class MyInterceptor implements Interceptor {
#Override
public String intercept(ActionInvocation invoke) throws Exception
{
System.out.println("Preprocessing.........");
String ret=invoke.invoke();
System.out.println("Post processing.........");
return ret;
}
#Override
public void destroy() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void init() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Login.java
import com.opensymphony.xwork2.ActionSupport;
public class Login extends ActionSupport{
String name;
public String execute()
{
return "SUCCESS";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
success.jsp
<%#taglib prefix="s" uri="/struts-tags" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>
Hellow, <s:property value="name"/>
</h1>
</body>
</html>

how to add excludeMethods parameter list for custom interceptor in struts2

How can I add excludeMethods parameter list for my custom interceptor in struts.xml file.
workflow and validation interceptor have this parameter i.e excludeMethods through witch the workflow interceptor will not fire for excluded methods as described like this:
<action name="action" class="abc.ActionClass">
<interceptor-ref name="defaultStack">
<param name="workflow.excludeMethods">doSomething</param>
</interceptor-ref>
<result>Success.jsp</result>
</action>
This I know. What I want to know is how can I do the same for my custom interceptor. I tried but failed. Here is my code:
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>
<s:url action="go2" method="forGo2" var="v_go2"/>
HIT to check if excludeMethods parameter working or NOT.
</body>
</html>
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="abc" extends="struts-default">
<interceptors>
<interceptor name="cust_intrcptr" class="pack.MyInterceptor2">
<param name="excludeMethods">forGo2</param> <!-- parameter for excluded method -->
</interceptor>
<interceptor-stack name="mystack2">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="cust_intrcptr"/>
</interceptor-stack>
</interceptors>
<action name="go2" class="pack.GoAction" method="forGo2">
<interceptor-ref name="mystack2"/>
<result name="success">/welcome2.jsp</result>
</action>
</package>
</struts>
custom-interceptor
package pack;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class MyInterceptor2 implements Interceptor{
#Override
public void destroy() {
// TODO Auto-generated method stub
}
#Override
public void init() {
// TODO Auto-generated method stub
}
#Override
public String intercept(ActionInvocation ai) throws Exception {
// TODO Auto-generated method stub
System.out.println("#####Inside Interceptor#####");
ai.invoke();
}
}
Action Class
package pack;
import com.opensymphony.xwork2.ActionSupport;
public class GoAction extends ActionSupport{
public String forGo2(){
return "success";
}
}
Output generated without any errors. But in console output I am viewing "#####Inside Interceptor#####" that I did not expected because I excluded the interceptor for forGo2 method. How can I exclude this interceptor for any given method in this case like forGo2.
There is a specific base class for this: MethodFilterInterceptor. From the Documentation:
An abstract Interceptor that is applied to selectively according to
specified included/excluded method lists.
To use, first extend it in your interceptor:
public class MyInterceptor2 extends MethodFilterInterceptor {
Now, instead of overriding the intercept method, override doIntercept:
#Override
public String doIntercept(ActionInvocation ai) throws Exception {
// TODO Auto-generated method stub
System.out.println("#####Inside Interceptor#####");
ai.invoke();
}
The base class will handle excludeMethods automatically and invoke doIntercept as required.

How to change post request to get redirect with minimum code changes in struts2?

My struts version is 2.3.15.3
In my current struts2 project, all post requests do not redirect to get requests
So I will get resubmit alert when I click the back button if I use https and chrome
How to use minimum effort to change them to keep using post request, but use get redirect to show the JSP? Can I just modify the struts.xml?
Or, is it possible to prevent the alert without PRG?
this is my current code
struts.xml:
<action name="Get" class="test.PostAction">
<result name="gotoform">/WEB-INF/jsp/PostForm.jsp</result>
<result name="success">/WEB-INF/jsp/showGet.jsp</result>
</action>
PostAction.java:
public class PostAction extends ActionSupport{
#Override
public String execute() throws Exception {
Map para = ActionContext.getContext().getParameters();
if(para.get("post")==null)
{
return "gotoform";
}
else
{
return "success";
}
}
}
PostForm.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="Get.action" method="POST">
<input type="text" name="post" value="yes">
<input type="submit">
</form>
</body>
</html>
showGet.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Display here</h1>
</body>
</html>
New showGet.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Display here, Post value=</h1> <%= request.getParameter("post") %>
</body>
</html>
new PostAction.java:
package test;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
public class PostAction extends ActionSupport{
private String post;
#Override
public String execute() throws Exception {
Map para = ActionContext.getContext().getParameters();
System.out.print("post = "+post);
if(para.get("post")==null)
{
return "gotoform";
}
else
{
return "success";
}
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
}
new 2 showGet.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Display here</h1>,
<s:property value="post"/>,
${post},
<%= post %>,
<%= getPost() %>
</body>
</html>
Additional action required to expose redirectAction result.
<action name="showGet">
<result>/WEB-INF/jsp/showGet.jsp</result>
</action>
<action name="Get" class="test.PostAction">
<result name="gotoform">/WEB-INF/jsp/PostForm.jsp</result>
<result name="success" type="redirectAction">showGet</result>
</action>

How to fetch data entries from mysql in jsp using struts2 in eclipse environment?

EventDropDown.java //Page 1
package com.tutorialspoint.struts2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
//import java.util.List;
import com.mysql.jdbc.ResultSetMetaData;
import com.opensymphony.xwork2.ActionSupport;
#SuppressWarnings("serial")`enter code here`
public class EventDropdownAction extends ActionSupport {
ArrayList<Event> eventList=new ArrayList<Event>();
public ArrayList<Event> getList() {
return eventList;
}
public void setList(ArrayList<Event> eventList) {
this.eventList = eventList;
}
private String eventName;
public String execute()
{
logger.info("Message-execute");
return "";
}
public String getEventList()
{
Connection conn = null;
try {
String URL = "jdbc:mysql://localhost:3306/bookmyshow_dates";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, "dra2", "dr#2");
"CASE \r\n" +
" WHEN DATEDIFF(DATE,NOW()) = 0 THEN CONCAT('Today',',',DAY(DATE),' ',MONTHNAME(DATE))\r\n" +
" WHEN DATEDIFF(DATE,NOW()) = 1 THEN CONCAT('Tomorrow',',',DAY(DATE),' ',MONTHNAME(DATE))\r\n" +
" WHEN DATEDIFF(DATE,NOW()) > 1 THEN CONCAT(DAYNAME(DATE),',',DAY(DATE),' ',MONTHNAME(DATE))\r\n" +
"END AS EventDay\r\n" +
"FROM EVENTS\r\n" +
"WHERE DATE_FORMAT(DATE,'%d/%m/%Y') >= DATE_FORMAT(NOW(),'%d/%m/%Y')";
String sql ="SELECT * FROM user3333";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
int rowCount=0;
if(rs.last()){
rowCount= rs.getRow();
} else {
rowCount= 0; //just cus I like to always do some kind else statement.
}
while (rs.next()) {
Event objEvent=new Event();
objEvent.setEventId(rs.getInt("EventId"));
objEvent.setEventName(rs.getString("EventName"));
objEvent.setEventDay(rs.getString("EventDay"));
Event objEvent=new Event(rs.getInt(1),rs.getString(2));
eventList.add(objEvent);
ret = SUCCESS;
}
} catch (Exception e)
{
ret = ERROR;
return "error";
}
finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
return "eventDropdown";
}
}
Event.java //Page 2
package com.tutorialspoint.struts2;
public class Event {
public int EventId;
public String EventName,EventDay;
Event()
{
this.EventId = 0;
this.EventName = "";
}
Event(int eventId, String eventName)
{
this.EventId = eventId;
this.EventName = eventName;
}
public int getEventId() {
return EventId;
}
public void setEventId(int id) {
this.EventId = id;
}
public String getEventName() {
return EventName;
}
public void setEventName(String name) {
this.EventName = name;
}
public String getEventDay() {
return EventDay;
}
public void setEventDay(String eventDay) {
this.EventDay = eventDay;
}
}
Error.jsp //Page 3
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>
error page.
</body>
</html>
**Success.jsp** //Page 3
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>
success page.
</body>
</html>
EventDayDropdown.jsp //Page 4
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!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>
<s:select name="username" label="Username" list="{'Mike','John','Smith'}" />
<br>
<s:select label="Select Event" name="ddlEvent" headerKey="0" headerValue="--Select--" list="{eventList}" listKey="{EventId}" listValue="{EventName}"/>
<%-- <s:select label="Select Event" name="ddlEvent" headerKey="0" headerValue="--Select--" list="{eventList}" /> --%>
<%-- <s:select name="event" list="eventList" listKey="eventId" listValue="eventName" headerKey="0" headerValue="--Event--" label="Select a event" /> --%>
</body>
</html>
Struts.xml //Page 5
<?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="helloworld" extends="struts-default">
<action name="event" class="com.tutorialspoint.struts2.EventDropdownAction"
method="getEventList">
<result name="success">/success.jsp</result>
<result name="failure">/error.jsp</result>
<result name="eventDropdown">/EventDayDropdown.jsp</result>
</action>
</package>
</struts>
These are files that is done with struts 2 in Eclipse IDE.
My database contains
3 Columns with atrributes
Event_Id 1, 2, 3, 4
EventName 2 states, Hobbit, Gravity,Gladiator.
Dates 20/5/2014, 21/5/2014, 21/5/2014, 23/5/2014
Like this.
Please help me. I am beginner.
Try trace your code block by block my using logging framework or simply System.out.println statements and but them in the start middle before db call after db call during db fetch and before return from the methods and see, what are exactly your problems? is it in the db or from struts2 or from Java code.
Another solution is to create separate applications, create a standlone project to fetch data from mysql database and test it in the console and create a a struts2 project with static
contents instead of trying fetching the data from database and see if the web application
provide what you need. Finally join both projects. so if any errors happened you can solve
it separately.

What naming convention should be used for custom Interceptor class and package in order to avoid struts.xml in Struts2

I am interested to know if there is any convention for naming custom interceptor in struts2 for the auto detection of interceptors like there are for the action classes.
I am using "struts2-convention-plugin-2.3.24.1.jar".
The Package structure is as follow
ProtienTracker
>Java Resources
>src
>com.nagarro.actions
>HelloAction.java
>com.nagarro.interceptors
>custInterceptor.java
>WebContent
>META_INF
>WEB_INF
>content
>hello.jsp
>lib
>web.xml
The code runs perfect without "struts.xml" and without "custInterceptor". The action is automatically detected by the struts2-convention-plugin.
As soon as i attach the interceptor with
#org.apache.struts2.convention.annotation.Action(value="hello",
interceptorRefs=#InterceptorRef("custInterceptor"))
i get the error as shown below.
The files are as follow
hello.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!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>Hello</title>
</head>
<body>
<h1><s:property value="greeting"/></h1>
<p>hi</p>
</body>
</html>
HelloAction.java
package com.nagarro.actions;
import com.opensymphony.xwork2.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;
public class HelloAction implements Action {
private String greeting="ab";
#Override
#org.apache.struts2.convention.annotation.Action(value="hello",
interceptorRefs=#InterceptorRef("custInterceptor"))
public String execute() throws Exception {
setGreeting("Hello Structs 2");
return "success";
}
public String getGreeting() {
return greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
custInterceptor.java
package com.nagarro.interceptors;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class custInterceptor implements Interceptor{
private static final long serialVersionUID = 1L;
#Override
public void destroy() {
System.out.println("custInterceptor destroy() is called...");
}
#Override
public void init() {
System.out.println("custInterceptor init() is called...");
}
#Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("custInterceptor intercept() is called...");
System.out.println(invocation.getAction().getClass().getName());
return invocation.invoke();
}
}
I get the following error:
Caused by: Unable to find interceptor class referenced by ref-name custInterceptor - [unknown location]
at com.opensymphony.xwork2.config.providers.InterceptorBuilder.constructInterceptorReference(InterceptorBuilder.java:63)
at org.apache.struts2.convention.DefaultInterceptorMapBuilder.buildInterceptorList(DefaultInterceptorMapBuilder.java:95)
at org.apache.struts2.convention.DefaultInterceptorMapBuilder.build(DefaultInterceptorMapBuilder.java:86)
at org.apache.struts2.convention.DefaultInterceptorMapBuilder.build(DefaultInterceptorMapBuilder.java:70)
at org.apache.struts2.convention.PackageBasedActionConfigBuilder.createActionConfig(PackageBasedActionConfigBuilder.java:947)
at org.apache.struts2.convention.PackageBasedActionConfigBuilder.buildConfiguration(PackageBasedActionConfigBuilder.java:734)
at org.apache.struts2.convention.PackageBasedActionConfigBuilder.buildActionConfigs(PackageBasedActionConfigBuilder.java:355)
at org.apache.struts2.convention.ClasspathPackageProvider.loadPackages(ClasspathPackageProvider.java:53)
at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:274)
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67)
... 17 more
As mentioned in define interceptors with struts2 annotations.
you cannot eliminate a need of struts.xml if you are using custom
interceptors.
To define a new interceptor in xml you need to define it in struts.xml files
<struts>
......
<package name="my-default" extends="struts-default" />
<!-- Define the intercepor class and give it a name-->
<interceptors>
<interceptor name="custInterceptor" class=com.nagarro.interceptors.custInterceptor" />
</interceptors>
<!-- Add it to a package. for example I add
the interceptor at top of struts default stack-->
<interceptor-stack name="myDefaultStack">
<interceptor-ref name="custInterceptor"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
<!-- Use the interceptor stack in your action with #InterceptorRef or set it as default -->
<default-interceptor-ref name="myDefaultStack" />
</package>
</struts>
You can see struts-default.xml https://struts.apache.org/docs/struts-defaultxml.html as a good sample for how interceptors are defined and used.

Categories