Archive

Posts Tagged ‘Kukuh Utama’

How To Find Longest Palindrome In String

July 29, 2017 Leave a comment

Below is code to find longest palindrome in string.


public class Palindrome {

public String getLongestPalindrome(String words) {
String longest = words.substring(0, 1);
for (int i = 0; i < words.length(); i++) {
String temp = helper(words, i, i);
if (longest.length() < temp.length()) {
longest = temp;
}

temp = helper(words, i, i + 1);
if (longest.length() < temp.length()) {
longest = temp;
}
}
return longest;
}

private String helper(String words,int left, int right) {
while (left >= 0 && right < words.length()&& words.charAt(left) == words.charAt(right)) {
left--;
right++;
}
return words.substring(left + 1, right);
}
}

ūüôā

Advertisements

Terekam Tak Pernah Mati

June 30, 2017 Leave a comment

Photo Idul Fitri 1438 H,

 

 

 

 

 

 

 

 

Alhamdulillah. ūüôā

Struts2 CRUD Tutorial

May 8, 2017 Leave a comment

In this tutorial I will show you how to perform create, retrieve, update and delete operation using struts2 framework. In this tutorial I have used Spring as DI, Hibernate as ORM and Maven as build tool also. Below are tutorial screen shoot,

Add View

 

Update View

 

 

Lets get started,

Structure Directory Project

  • Entity class (Student.java)
package strutshelloworld.net.ren.struts2.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

// TODO: Auto-generated Javadoc
/**
 * The Class Student.
 */
@Entity
@Table(name="student")
public class Student {
    
    /** The id. */
	@Id
	@GeneratedValue
	@Column(name="id")
    private int id;
    
    /** The first name. */
	@Column(name="first_name")
    private String firstName;
    
    /** The last name. */
	@Column(name="last_name")
    private String lastName;
    
    /**
     * Instantiates a new student.
     */
    public Student() {
	
    }
    
    /**
     * Instantiates a new student.
     *
     * @param id the id
     * @param firstName the first name
     * @param lastName the last name
     */
    public Student(int id, String firstName, String lastName) {
	super();
	this.id = id;
	this.firstName = firstName;
	this.lastName = lastName;
    }
    
    /**
     * Gets the id.
     *
     * @return the id
     */
    public int getId() {
	return id;
    }
    
    /**
     * Sets the id.
     *
     * @param id the new id
     */
    public void setId(int id) {
	this.id = id;
    }
    
    /**
     * Gets the first name.
     *
     * @return the first name
     */
    public String getFirstName() {
	return firstName;
    }
    
    /**
     * Sets the first name.
     *
     * @param firstName the new first name
     */
    public void setFirstName(String firstName) {
	this.firstName = firstName;
    }
    
    /**
     * Gets the last name.
     *
     * @return the last name
     */
    public String getLastName() {
	return lastName;
    }
    
    /**
     * Sets the last name.
     *
     * @param lastName the new last name
     */
    public void setLastName(String lastName) {
	this.lastName = lastName;
    }
    
}
  • Repository class (AbstractBaseRepository.java)
package strutshelloworld.net.ren.struts2.repository;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.persistence.Query;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * The Class AbstractBaseRepository.
 *
 * @param <T>
 *            the generic type
 */
public abstract class AbstractBaseRepository<T> implements BaseRepository<T> {

	/** The entity class. */
	private Class<T> entityClass;

	/** The session factory. */
	@Autowired
	private SessionFactory sessionFactory;

	/** The hql. */
	private String hql;

	/** The entities. */
	private List<T> entities;
	/**
	 * Instantiates a new abstract base repository.
	 */
	public AbstractBaseRepository() {
		Type t = getClass().getGenericSuperclass();
		ParameterizedType pt = (ParameterizedType) t;
		entityClass = (Class) pt.getActualTypeArguments()[0];
	}

	/**
	 * Sets the session factory.
	 *
	 * @param sessionFactory
	 *            the new session factory
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * Gets the current session.
	 *
	 * @return the current session
	 */
	protected Session getCurrentSession() {
		try {
			return sessionFactory.getCurrentSession();
		} catch (HibernateException e) {
			return sessionFactory.openSession();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.repository.BaseRepository#add(java.lang.
	 * Object)
	 */
	public void add(T entity) {
		getCurrentSession().saveOrUpdate(entity); // .save(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.repository.BaseRepository#deleteById(
	 * int)
	 */
	@SuppressWarnings("unchecked")
	public void deleteById(int id) {
		hql = "delete " + entityClass.getName() + " where id = :id";
		Query q = getCurrentSession().createQuery(hql).setParameter("id", id);
		q.executeUpdate();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.repository.BaseRepository#getById(int)
	 */
	@SuppressWarnings("unchecked")
	public T getById(int id) {
		return (T) getCurrentSession().get(entityClass.getName(), id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see strutshelloworld.net.ren.struts2.repository.BaseRepository#getAll()
	 */
	@SuppressWarnings({ "deprecation", "unchecked" })
	public List<T> getAll() {
		return getCurrentSession().createCriteria(entityClass).list();
	}
	
	/**
	 * Delete all.
	 */
	public void deleteAll(){
		entities = getAll();
		for(T entity : entities){
			getCurrentSession().delete(entity);
		}
	}
	
	/**
	 * Delete.
	 *
	 * @param entity the entity
	 */
	public void delete(T entity){
		getCurrentSession().delete(entity);
	}
}
  • Repository interface (BaseRepository.java)
package strutshelloworld.net.ren.struts2.repository;

import java.util.List;


/**
 * The Interface BaseRepository.
 *
 * @param <T> the generic type
 */
public interface BaseRepository<T> {

	/**
	 * Adds the.
	 *
	 * @param entity the entity
	 */
	public  void add(T entity);

	/**
	 * Delete by id.
	 *
	 * @param id the id
	 */
	public void deleteById(int id);

	/**
	 * Gets the by id.
	 *
	 * @param id the id
	 * @return the by id
	 */
	public  T getById(int id);

	/**
	 * Gets the all.
	 *
	 * @return the all
	 */
	public  List<T> getAll();
	
	/**
	 * Delete all.
	 */
	public void deleteAll();
	
	/**
	 * Delete.
	 *
	 * @param entity the entity
	 */
	public void delete(T entity);

}
  • Repository interface(StudentRepository.java)
package strutshelloworld.net.ren.struts2.repository;

import strutshelloworld.net.ren.struts2.domain.Student;

/**
 * The Interface StudentRepository.
 */
public interface StudentRepository extends BaseRepository<Student> {

}
  • Repository class (StudentRepositoryImpl.java)
package strutshelloworld.net.ren.struts2.repository.impl;

import org.springframework.stereotype.Repository;

import strutshelloworld.net.ren.struts2.domain.Student;
import strutshelloworld.net.ren.struts2.repository.AbstractBaseRepository;
import strutshelloworld.net.ren.struts2.repository.StudentRepository;

/**
 * The Class StudentRepositoryImpl.
 */
@Repository("studentRepository")
public class StudentRepositoryImpl extends AbstractBaseRepository<Student> implements StudentRepository {

}
  • Service Interface (StudentService.java)
package strutshelloworld.net.ren.struts2.service;

import java.util.List;

import strutshelloworld.net.ren.struts2.domain.Student;

// TODO: Auto-generated Javadoc
/**
 * The Interface StudentService.
 */
public interface StudentService {

	/**
	 * Adds the student.
	 *
	 * @param student
	 *            the student
	 */
	public void addStudent(Student student);

	/**
	 * Delete student by id.
	 *
	 * @param id
	 *            the id
	 */
	public void deleteStudentById(int id);

	/**
	 * Find student by id.
	 *
	 * @param id
	 *            the id
	 * @return the student
	 */
	public Student findStudentById(int id);

	/**
	 * Find all.
	 *
	 * @return the list
	 */
	public List<Student> findAll();
	
	/**
	 * Delete all.
	 */
	public void deleteAll();
	
	/**
	 * Delete.
	 *
	 * @param entity the entity
	 */
	public void delete(Student entity);
}
  • Service class (StudentServiceImpl.java)
package strutshelloworld.net.ren.struts2.service.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import strutshelloworld.net.ren.struts2.domain.Student;
import strutshelloworld.net.ren.struts2.repository.StudentRepository;
import strutshelloworld.net.ren.struts2.service.StudentService;

// TODO: Auto-generated Javadoc
/**
 * The Class StudentServiceImpl.
 */
@Service
@Transactional
public class StudentServiceImpl implements StudentService {

	/** The student repository. */
	@Autowired
	private StudentRepository studentRepository;

	/*
	 * (non-Javadoc)
	 * 
	 * @see strutshelloworld.net.ren.struts2.service.StudentService#addStudent(
	 * strutshelloworld.net.ren.struts2.domain.Student)
	 */
	public void addStudent(Student student) {
		studentRepository.add(student);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.service.StudentService#deleteStudentById
	 * (int)
	 */
	public void deleteStudentById(int id) {
		studentRepository.deleteById(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.service.StudentService#findStudentById(
	 * int)
	 */
	public Student findStudentById(int id) {
		return studentRepository.getById(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see strutshelloworld.net.ren.struts2.service.StudentService#findAll()
	 */
	public List<Student> findAll() {
		return studentRepository.getAll();
	}

	/* (non-Javadoc)
	 * @see strutshelloworld.net.ren.struts2.service.StudentService#deleteAll()
	 */
	public void deleteAll() {
		studentRepository.deleteAll();
	}

	/* (non-Javadoc)
	 * @see strutshelloworld.net.ren.struts2.service.StudentService#delete(strutshelloworld.net.ren.struts2.domain.Student)
	 */
	public void delete(Student entity) {
		studentRepository.delete(entity);
	}
}
  • Action class (StudentAction.java)
package strutshelloworld.net.ren.struts2.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

import strutshelloworld.net.ren.struts2.domain.Student;
import strutshelloworld.net.ren.struts2.service.StudentService;

// TODO: Auto-generated Javadoc
/**
 * The Class StudentAction.
 */
public class StudentAction extends ActionSupport implements ModelDriven, Preparable {

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

	/** The student service. */
	@Autowired
	private StudentService studentService;

	/** The list student. */
	private List<Student> listStudent = new ArrayList<Student>();

	/** The student. */
	private Student student = new Student();
	
	/** The request. */
	private HttpServletRequest request;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.ModelDriven#getModel()
	 */
	public Object getModel() {
		return student;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.Preparable#prepare()
	 */
	public void prepare() throws Exception {
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	public String execute() throws Exception {
		return SUCCESS;
	}

	/**
	 * Adds the student.
	 *
	 * @return the string
	 */
	public String addStudent() {
		studentService.addStudent(student);
		return SUCCESS;
	}
	
	/**
	 * Update student.
	 *
	 * @return the string
	 */
	public String updateStudent() {
		studentService.addStudent(student);
		return SUCCESS;
	}

	/**
	 * Delete student.
	 *
	 * @return the string
	 */
	public String deleteStudent() {
        request = (HttpServletRequest) ActionContext.getContext().get( ServletActionContext.HTTP_REQUEST);
		studentService.deleteStudentById((Integer.parseInt(request. getParameter("id"))));
		return SUCCESS;
	}

	/**
	 * Gets the all student.
	 *
	 * @return the all student
	 */
	public String getAllStudent() {
		listStudent = studentService.findAll();
		return SUCCESS;
	}

	/**
	 * Update student.
	 *
	 * @return the string
	 */
	public String getStudentById(){
		request = (HttpServletRequest) ActionContext.getContext().get( ServletActionContext.HTTP_REQUEST);
		student = studentService.findStudentById(Integer.parseInt(request. getParameter("id")));
		return SUCCESS;
	}
	
	/**
	 * Delete all.
	 *
	 * @return the string
	 */
	public String deleteAll(){
		studentService.deleteAll();
		return SUCCESS;
	}
	
	/**
	 * Gets the list student.
	 *
	 * @return the list student
	 */
	public List<Student> getListStudent() {
		return listStudent;
	}

}
  • 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="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="/" extends="struts-default">

		<action name="index">
			<result type="redirect">/login.html</result>
		</action>

	  <action name="showAddStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="execute">
			<result name="success">/WEB-INF/jsp/AddStudent.jsp</result>
		</action>

		<action name="addStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="addStudent">
			<result name="success" type="redirect">listStudent.html</result>
		</action>
		
		<action name="updateStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="updateStudent">
			<result name="success" type="redirect">listStudent.html</result>
		</action>
		
		<action name="deleteStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="deleteStudent">
			<result name="success" type="redirect">listStudent.html</result>
		</action> 
        
        <action name="deleteAll" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="deleteAll">
              <result name="success" type="redirect">listStudent.html</result>
        </action>
	
		<action name="getStudentById" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="getStudentById">
				<result name="success">/WEB-INF/jsp/AddStudent.jsp</result>
		</action> 
		  
	   <action name="listStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="getAllStudent">
			<result name="success">/WEB-INF/jsp/ListStudent.jsp</result>
		</action>
		
		<action name="login" class="strutshelloworld.net.ren.struts2.actions.LoginAction">
			<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>
  • application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

	<context:property-placeholder location="classpath:hibernate.properties" />
	
    <context:annotation-config/>
    
    <context:component-scan base-package="strutshelloworld.net.ren.struts2"></context:component-scan>
    
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

	<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="packagesToScan" value="strutshelloworld.net.ren.struts2.domain" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
			</props>
		</property>
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
		
	<tx:annotation-driven transaction-manager="transactionManager" />

</beans>
  • application-context.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>
  
   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/application-context.xml</param-value>
    </context-param>
     
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
  <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>
  • AddStudent.jsp
<%@ 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">
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Student</title>
</head>
<body>
	<h1>Struts 2 ModelDriven example</h1>
	<s:if test="%{model.id == 0}">
		<h2>Add Student</h2>
	</s:if>
	<s:else>
		<h2>Update Student</h2>
	</s:else>
	<s:form action="addStudent">
		<s:if test="%{model.id != 0}">
            <s:textfield name="id" key="label.id" value="%{model.id}" />
	   </s:if>
		<s:textfield name="firstName" key="label.fname"
			value="%{model.firstName}" />
		<s:textfield name="lastName" key="label.lname"
			value="%{model.lastName}" />
		<s:if test="%{model.id == 0}">
			<s:submit key="label.submit" align="center"/>
		</s:if>
		<s:else>
			<s:submit key="label.update" align="center" action="updateStudent"/>
		</s:else>
	</s:form>
	
</body>
</html>
  • ListStudent.jsp
<%@ 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">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>List of Student</title>
</head>
<body>
     <table cellpadding="5px">
		<tr class="even">
			<th>Id</th>
			<th>Fist Name</th>
			<th>Last Name</th>
			<th>Edit </th>
			<th>Delete </th>
		</tr>
        <c:forEach items="${listStudent}" var="student">
			<tr>
				<td><c:out value="${student.id}"/></td>
				<td><c:out value="${student.firstName}"/></td>
				<td><c:out value="${student.lastName}"/></td>
		    	<td>
               <s:url var="updateUrl" action="getStudentById">
					<s:param name="id">${student.id}</s:param>
				</s:url> 
				<s:a href="%{updateUrl}">Update</s:a>
                </td>
				<td>
                <s:url var="deleteUrl" action="deleteStudent">
					<s:param name="id">${student.id}</s:param>
				</s:url> 
                <s:a href="%{deleteUrl}">Delete</s:a>
                </td> 
			</tr>
		</c:forEach> 
	</table>
	<s:url var="deleteAllUrl" action="deleteAll"/>
	<s:a href="%{deleteAllUrl}">Delete All</s:a>
</body>
</html>

You can get project in here via Github
Thank you.

PS.
Before running this code, you must edit hibernate.properties file to adjust your local and create database with “hibernate” name in mysql.

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. ūüôā

java.lang.ClassNotFoundException: org.Springframework.Web.Context.ContextLoaderListener

March 16, 2017 Leave a comment

How to solve java.lang.ClassNotFoundException: org.Springframework.Web.Context.ContextLoaderListener.

Firstly we must know root cause :
This error because using Spring MVC framework in Java Web application and configured org.springframework.web.context.ContextLoaderListener as a listener in your deployment descriptor also known as web.xml, but the JAR which contains this class is not available in web application’s classpath. This jar appears in spring-web.jar, if you use maven as build tool so make sure that spring-web dependency exist in pom file.


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>

Second, right click web project -> Select “Deployment Assembly” -> Click the “Add..” button on the right -> Select “Java Build Path Entries” from the menu of Directive Type and click “Next” -> Select “Maven Dependencies” from the Java Build Path Entries menu -> Click finish.

Please see picture below.

Build path

Thank you.

Categories: Java, Java and Web Tags: , ,

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. ūüôā

Lesson Is Learned

January 23, 2017 Leave a comment

Job assignment to Tangerang is really disappointed. End up at outsourcing thing, yeah I have to keep positive mindset.

But Lesson is learned,

If better opportunity knock, you have take it do not ignore it.

I will not make same mistake, do not take¬†‘Sweet Promise’ seriously.

Kukuh.

Categories: Ren's Notes Tags: