Archive

Posts Tagged ‘Struts2’

Struts2 Dynamic Method Invocation

April 14, 2017 Leave a comment

Dynamic invocation in Struts2 is used to avoid configuration separate action mapping for each method in action class by using wildcard method.

Look at Struts configuration below.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
	<constant name="struts.devMode" value="false" />
	<constant name="struts.custom.i18n.resources" value="app-resources" />
	<constant name="struts.action.extension" value="html" />
        <constant name="struts.mapper.action.prefix.enabled" value="true"/>
 
	<package name="default" namespace="/" strict-method-invocation="false" extends="struts-default">

		<action name="*Book" method="{1}" class="strutshelloworld.net.ren.struts2.actions.BookAction">
		      <result name="success">/WEB-INF/jsp/Book.jsp</result>
		</action>
	</package>
</struts>

Action code.

import com.opensymphony.xwork2.ActionSupport;

/**
 * The Class BookAction.
 */
public class BookAction extends ActionSupport {

    /** The message. */
    private String message;

    /* (non-Javadoc)
     * @see com.opensymphony.xwork2.ActionSupport#execute()
     */
    public String execute() {
        message = "Inside execute method";
        return SUCCESS;
    }

    /**
     * Adds the.
     *
     * @return the string
     */
    public String add() {
        message = "Inside add method";
        return SUCCESS;
    }

    /**
     * Update.
     *
     * @return the string
     */
    public String update() {
        message = "Inside update method";
        return SUCCESS;
    }

    /**
     * Delete.
     *
     * @return the string
     */
    public String delete() {
        message = "Inside delete method";
        return SUCCESS;
    }

    /**
     * Gets the message.
     *
     * @return the message
     */
    public String getMessage() {
        return message;
    }

    /**
     * Sets the message.
     *
     * @param message the new message
     */
    public void setMessage(String message) {
        this.message = message;
    }
}

Please consider this as view code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ 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>In here</title>
</head>
<body>


<h1>Hello Here</h1>


<s:form action="Book">
<s:submit action="addBook" key="label.submit" align="center" />
<s:submit action="updateBook" key="label.update" align="center" />
<s:submit action="deleteBook" key="label.delete" align="center" />
</s:form>
</body>
</html>

As you can see, instead writing different name for each action name, action is provided with name=”*Book” method=”{1}” means if the input is “addBook” or “updateBook” then the add() / update() method will be executed in Action class accordingly.

Please note it, strict-method-invocation (SMI) property in package tag has default value true. For futher reading about Strict Method Invocation (SMI)  you can see in here and here.

Thank you. 🙂

Struts2 Interceptor Example

February 12, 2017 Leave a comment

In Struts2 interceptor are called one after other one in a configured order for each invocation of an action class. So with interceptor we can do some perform task like logging, validation before action is called.
In this tutorial it shows how to create an own interceptor in Struts2 (Login and Loggin Interceptor). Sumary steps below.

  • Create a class that implements com.opensymphony.xwork2.interceptor.Interceptor interface and override the intercept(ActionInvocation invocation), init, destroy method.

Interceptor class (AuthInterceptor.java)

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
* The Class AuthInterceptor.
*/
public class AuthInterceptor implements Interceptor {

/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
*/
public void destroy() {
System.out.println("destroy Auth");
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#init()
*/
public void init() {
System.out.println("init Auth");
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
public String intercept(ActionInvocation invoke) throws Exception {
SessionMap sessionMap = (SessionMap) ActionContext.getContext().getSession();
if(sessionMap.get("user") == null){
return Action.LOGIN;
} else {
return invoke.invoke();
}
}
}

Interceptor class (LogInterceptor.java)

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
/**
* The Class LogInterceptor.
*/
public class LogInterceptor implements Interceptor {

/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
*/
public void destroy() {
System.out.println("destroy Log");
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#init()
*/
public void init() {
System.out.println("init Log");
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
public String intercept(ActionInvocation invoke) throws Exception {
String className = invoke.getAction().getClass().getName();
long startTime = System.currentTimeMillis();
System.out.println("Before calling action: " + className);

String result = invoke.invoke();

long endTime = System.currentTimeMillis();
System.out.println("After calling action: " + className + " Time taken: " + (endTime - startTime) + " ms");
return result;
}
}

If any intercept method in interceptor class decides action should not executed,
it can return a string value and response will be created from global result that same name in struts config file.

  • Configure the interceptor in the struts.xml.
<interceptors>
<interceptor name="authentication" class="strutshelloworld.net.ren.struts2.interceptors.AuthInterceptor">
</interceptor>

<interceptor name="logging" class="strutshelloworld.net.ren.struts2.interceptors.LogInterceptor">
</interceptor>

<interceptor-stack name="authStack">
<interceptor-ref name="authentication" />
<interceptor-ref name="logging" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="defaultStack"></default-interceptor-ref>
  • Add global result
<action name="index">
<interceptor-ref name="authStack"></interceptor-ref>
<result type="redirect">/home.html</result>
</action>
  • Add interceptor in action
<action name="home" class="strutshelloworld.net.ren.struts2.actions.UserAction">
<interceptor-ref name="authStack"></interceptor-ref>
<result name="success">/WEB-INF/jsp/Welcome.jsp</result>
</action>

For complete code, you can get it in here.
Fyi, I used project in this post as basis.

Thank you. 🙂

Struts2 Hello World

August 30, 2015 1 comment

Goal :

Login Form Struts2

Login Form Struts2

 

Hello Struts2

Hello Struts2

Steps:

  • Create Maven Project
  • Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>strutshelloworld</groupId>
<artifactId>net.ren.struts2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>net.ren.struts2</name>

<properties>
<struts2.version>2.5.2</struts2.version>
<log4j2.version>2.5</log4j2.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>

<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts2.version}</version>
</dependency>

<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-config-browser-plugin</artifactId>
<version>${struts2.version}</version>
</dependency>

<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-junit-plugin</artifactId>
<version>${struts2.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.5</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<encoding>UTF-8</encoding>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>

</plugins>
</build>
</project>

  • Web.xml
 
<?xml version="1.0" encoding="UTF-8"?> 
<web-app id="struts_blank" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 
<display-name>Struts Blank</display-name> 
<filter> 
<filter-name>struts2</filter-name> 
<filter-class> org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter </filter-class>
 </filter> 
<filter-mapping> 
<filter-name>struts2</filter-name> 
<url-pattern>/*</url-pattern> 
</filter-mapping> 
<welcome-file-list> 
<welcome-file>index.html</welcome-file> 
</welcome-file-list> 
</web-app> 
  • Action class

package strutshelloworld.net.ren.struts2.actions;

import com.opensymphony.xwork2.ActionSupport;
/**
* The Class Login.
*/
public class Login extends ActionSupport {

/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;

/** The username. */
private String username;

/** The password. */
private String password;

/* (non-Javadoc)
* @see com.opensymphony.xwork2.ActionSupport#execute()
*/
public String execute() throws Exception {
if( getUsername()== null || getPassword() == null){
return "input";
}
else if (this.username.equals("admin") && this.password.equals("admin123")) {
return "success";
} else {
addActionError(getText("error.login"));
return "error";
}
}

/**
* Gets the username.
*
* @return the username
*/
public String getUsername() {
return username;
}

/**
* Sets the username.
*
* @param username the new username
*/
public void setUsername(String username) {
this.username = username;
}

/**
* Gets the password.
*
* @return the password
*/
public String getPassword() {
return password;
}

/**
* Sets the password.
*
* @param password the new password
*/
public void setPassword(String password) {
this.password = password;
}

}

  • Create properties file ( app-resources.properties )

copy this content into properties file

label.username= Username
label.password= Password
label.login= Login
error.login= Invalid Username/Password.
  • Create JSP files ( Login.jsp and Welcome.jsp )

Login.jsp


<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Struts 2 - Login Application</title>
</head>
<body>

<h2>Struts 2 - Login Application</h2>

<s:actionerror />
<s:form action="login.action" method="post">
<s:textfield name="username" key="label.username" size="20" />
<s:password name="password" key="label.password" size="20" />
<s:submit method="execute" key="label.login" align="center" />
</s:form>
</body>
</html>

Welcome.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome</title>
</head>
<body>

<h2>Howdy, <s:property value="username" />...!</h2>

</body>
</html>
  • Create struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
 <constant name="struts.enable.DynamicMethodInvocation" value="false" />
 <constant name="struts.devMode" value="true" />
<!-- <constant name="struts.action.extension" value="html" / -->
 <constant name="struts.custom.i18n.resources" value="app-resources" />

 <package name="default" namespace="/" extends="struts-default">
 <default-action-ref name="login" />
 <action name="login" class="strutshelloworld.net.ren.struts2.actions.Login">
 <result name="success">/WEB-INF/jsp/Welcome.jsp</result>
 <result name="error">/WEB-INF/jsp/Login.jsp</result>
 <result name="input">/WEB-INF/jsp/Login.jsp</result>
 </action>
 </package>
 
</struts>
  • index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=login.action">
</head>

<body>

</body>
</html>

  • Project Structure
Project Structure

Project Structure

Project in github

Categories: Java Tags: , , ,