Tuesday, March 4, 2014

spring constructor injection

Lets take two classes parent class and children class.
Parent class want's children object within itself.

Class Children {
public helloChildren (){
System.out.orintln ("hello children");
}
}


Class Parent {
private Children children;
@autowired
public Parent (Children children){
this.children=children;
}
public void helloParent (){
System.out.println ("hello parent");
children.helloChildren ();
}
}

Its done threw annotation. 

spring dependency injection

There are three type of dependency injection in spring:-

  1. Constructor Injection
  2. Setter Injection
  3. Interface Injection
If there is constructor injection, setter injection and interfeace injection in same class Constructor injection is prefered overriding others.

It there is setter injection and interface injection then setter injection is preferred over interface injection.

Monday, December 2, 2013

Spring 3.0 + Hibernate 4.0

Step 1 : Create new J2ee project in eclipse name SpringHibernate in my case with structure as follow .



Step 2 : Add following jar in lib folder under WebContent/WEB-INF/lib/ .



Step 3 : Modify web.xml file under /WebContent/WEB-INF/ folder in project with following content .

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SpringHibernate</display-name>

<servlet>
       <servlet-name>dispatcher</servlet-name>
       <servlet-class>
               org.springframework.web.servlet.DispatcherServlet
       </servlet-class>
       <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
       <servlet-name>dispatcher</servlet-name>
       <url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
       <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>

Step 4 : Create file dispatcher-servlet.xml under /WebContent/WEB-INF/ folder in project with following content .

<?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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

<context:property-placeholder location="classpath:/resources/config/db/jdbc-mysql.properties" />
<context:component-scan base-package="com.company" />

<tx:annotation-driven transaction-manager="hibernateTransactionManager" />

<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>

   <bean id="dataSource" 
    class="org.apache.commons.dbcp.BasicDataSource">
      <property name="driverClassName" value="${jdbc.driverClassName}" />
      <property name="url" value="${jdbc.url}" />
      <property name="username" value="${jdbc.user}" />
      <property name="password" value="${jdbc.password}" />
   </bean>
<bean id="sessionFactory" 
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="packagesToScan" value="com.company.model" />
      <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>
            <prop key="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</prop>
         </props>
      </property>
   </bean>

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

</beans>

Step 5 : Create file index.jsp under /WebContent/ folder in project with following content .

<jsp:forward  page="login.do"></jsp:forward>

Step 6 : Create package .com.company.controller under /src folder in project .
Step 7 : Create package .com.company.dao under /src folder in project .
Step 8 : Create package .com.company.model under /src folder in project .
Step 9 : Create package .com.company.service under /src folder in project .
Step 10 : Create package .resources.config.db under /src folder in project .
Step 11 : Create file jdbc-mysql.properties in .resources.config.db under /src folder in project with following content .

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springhibernate?createDatabaseIfNotExist=true
jdbc.user=root
jdbc.password=
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.globally_quoted_identifiers=true
#validate | update | create | create-drop
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true

Step 12 : Create file ArticleController.java .com.company.controller under /src folder in project with following content .

package com.company.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.company.model.Article;
import com.company.model.Login;
import com.company.service.article.IArticleService;
import com.company.service.login.ILoginService;

@Controller
@RequestMapping("/")
public class ArticleController {

@Autowired
private IArticleService articleService;
@Autowired
private ILoginService loginService;

@RequestMapping(value = "save", method = RequestMethod.POST)
public ModelAndView saveArticle(@ModelAttribute(" article") Article  article,
BindingResult result) {
articleService.addArticle( article);
return new ModelAndView("redirect:/list.do");
}

@RequestMapping(value = "list", method = RequestMethod.GET)
public ModelAndView listArticles() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("articles",  articleService.listArticles());
return new ModelAndView("articlesList", model);
}

@RequestMapping(value = "add", method = RequestMethod.GET)
public ModelAndView addArticle(@ModelAttribute("article") Article article,
BindingResult result) {
return new ModelAndView("addArticle");
}
@RequestMapping(value = "login", method = RequestMethod.POST)
public ModelAndView loginGet(@ModelAttribute("login") Login login, BindingResult result) {
return new ModelAndView("login");
}
@RequestMapping(value = "login", method = RequestMethod.GET)
public ModelAndView loginPost(@ModelAttribute("login") Login login, BindingResult result) {
return new ModelAndView("login");
}
@RequestMapping(value = "validate", method = RequestMethod.POST)
public ModelAndView validateGet(@ModelAttribute("login") Login login, BindingResult result) {
return new ModelAndView("redirect:/add.do");
}
@RequestMapping(value = "validate", method = RequestMethod.GET)
public ModelAndView validatePost(@ModelAttribute("login") Login login, BindingResult result) {
return new ModelAndView("redirect:/add.do");
}
}

Step 13 : Create file ArticleDao.java .com.company.dao under /src folder in project with following content .

package com.company.dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.context.internal.ThreadLocalSessionContext;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.company.model.Article;

@Repository("articleDao")
public class ArticleDao {

@Autowired
private SessionFactory sessionFactory;

protected Session getCurrentSession(){
ThreadLocalSessionContext oThreadLocalSessionContext = new ThreadLocalSessionContext((SessionFactoryImplementor) sessionFactory);
return oThreadLocalSessionContext.currentSession();
}
// To Save the article detail
public void save(Article article) {
Transaction oTransaction = getCurrentSession().beginTransaction();
article.setAddedDate(new Date());
getCurrentSession().save(article);
oTransaction.commit();
}
// To Save the article detail
public void update(Article article) {
Transaction oTransaction = getCurrentSession().beginTransaction();
article.setAddedDate(new Date());
getCurrentSession().update(article);
oTransaction.commit();
}
// To get list of all articles
@SuppressWarnings("unchecked")
public List<Article> listArticles() {
Transaction oTransaction = getCurrentSession().beginTransaction();
List<Article> oList = (List<Article>) getCurrentSession().createCriteria(Article.class).list();
oTransaction.commit();
return oList;
}
}


Step 14 : Create file LoginDao.java .com.company.dao under /src folder in project with following content .

package com.company.dao;

import java.util.Date;
import java.util.List;

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

import com.company.model.Login;

@Repository("loginDao")
public class LoginDao {

@Autowired
private SessionFactory sessionFactory;

protected Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
// To Save the article detail
public void save(Login login) {
login.setLoginTime(new Date());
getCurrentSession().save(login);
}
// To Save the article detail
public void update(Login login) {
login.setLoginTime(new Date());
getCurrentSession().update(login);
}
// To get list of all articles
@SuppressWarnings("unchecked")
public List<Login> listUser() {
return (List<Login>) getCurrentSession().createCriteria(Login.class).list();
}
}

Step 15 : Create file Article.java .com.company.model under /src folder in project with following content .

package com.company.model;

import java.io.Serializable;
import java.util.Date;

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

@Entity
@Table(name = "article")
public class Article implements Serializable{

/**
*/
private static final long serialVersionUID = -3879168248261387800L;

@Id
@GeneratedValue
@Column(name = "article_id")
private Long articleId;

@Column(name = "article_name", nullable = false, length=20)
private String articleName;

@Column(name = "article_desc", nullable = false)
private String articleDesc;
@Column(name = "date_added")
private Date addedDate;
public Article() {
}
public Long getArticleId() {
return articleId;
}

public void setArticleId(Long articleId) {
this.articleId = articleId;
}

public String getArticleName() {
return articleName;
}

public void setArticleName(String articleName) {
this.articleName = articleName;
}

public String getArticleDesc() {
return articleDesc;
}

public void setArticleDesc(String articleDesc) {
this.articleDesc = articleDesc;
}

public Date getAddedDate() {
return addedDate;
}

public void setAddedDate(Date addedDate) {
this.addedDate = addedDate;
}
}

Step 16 : Create file Login.java .com.company.model under /src folder in project with following content .

package com.company.model;

import java.io.Serializable;
import java.util.Date;

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

@Entity
@Table(name = "login")
public class Login implements Serializable{

private static final long serialVersionUID = -3879168248261387800L;

@Id
@Column(name = "oauth_token", nullable = false, length=40)
private String oauthtoken;
@Column(name = "user_id", nullable = false, length=40)
private String userID;

@Column(name = "user_name", nullable = false, length=40)
private String username;

@Column(name = "login_time", nullable = false)
private Date loginTime;
public Login() {
}

public String getOauthtoken() {
return oauthtoken;
}

public void setOauthtoken(String oauthtoken) {
this.oauthtoken = oauthtoken;
}

public String getUserID() {
return userID;
}

public void setUserID(String userID) {
this.userID = userID;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public Date getLoginTime() {
return loginTime;
}

public void setLoginTime(Date loginTime) {
this.loginTime = loginTime;
}

}

Step 17 : Create package .com.company.service.article under /src folder in project .

Step 18 : Create package .com.company.service.login under /src folder in project .

Step 19 : Create package .com.company.service.article.impl under /src folder in project .

Step 20 : Create package .com.company.service.login.impl under /src folder in project .

Step 21 : Create file IArticleService.java .com.company.service.article under /src folder in project with following content .

package com.company.service.article;

import java.util.List;

import com.company.model.Article;

public interface IArticleService {

public void addArticle(Article article);

public List<Article> listArticles();
}

Step 22 : Create file ILoginService.java .com.company.service.login under /src folder in project with following content .

package com.company.service.login;

import java.util.List;

import com.company.model.Login;

public interface ILoginService {

public void addLogin(Login login);

public List<Login> listLogin();
}

Step 23 : Create file ArticleServiceImpl.java .com.company.article.impl under /src folder in project with following content .

package com.company.service.article.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.company.dao.ArticleDao;
import com.company.model.Article;
import com.company.service.article.IArticleService;

@Service("articleService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class ArticleServiceImpl implements IArticleService {

@Autowired
private ArticleDao articleDao;

public ArticleServiceImpl() {
}

@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addArticle(Article article) {
articleDao.save(article);
}

public List<Article> listArticles() {
return articleDao.listArticles();
}

}

Step 24 : Create file LoginServiceImpl.java .com.company.login.impl under /src folder in project with following content .

package com.company.service.login.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.company.dao.LoginDao;
import com.company.model.Login;
import com.company.service.login.ILoginService;

@Service("loginService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class LoginServiceImpl implements ILoginService {

@Autowired
private LoginDao loginDao;

public LoginServiceImpl() {
}

@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addLogin(Login login) {
loginDao.save(login);
}

@Override
public List<Login> listLogin() {
return loginDao.listUser();
}

}

Step 25 :
 Create folder
 js under /WebContent folder in project .

Step 26 : Download file jquery-latest.js and paste it under /WebContent/js/ folder in project .

Step 27 : Create folder view under /WebContent/WEB-INF/ folder in project .

Step 28 : Create file addArticle.jsp  under /WebContent/WEB-INF/view/ folder in project with following content .

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<script src="./js/jquery-latest.js" type="text/javascript"></script>

<html>
<head>
<script type="text/javascript">
function helloAJAX(id){
var data = $("#" + id).serialize();
$.ajax(
{
url: "./save.do",
data: data,
dataType: 'text',
type: 'post',
success: function(oResponse)
{
location.href = "./list.do";
/* hideProcessingLayer();
if(oResponse["ResponseCode"] == "Success")
success_callback(oResponse["Data"], oResponse["Html"]);
else
error_callback(oResponse["ResponseCode"] + " : " + oResponse["ErrorMessage"]); */
},
error: function(jqXHR, textStatus, errorThrown)
{
/* hideProcessingLayer();
error_callback(errorThrown); */
}
});
}
</script>

<title>Add Article</title>
</head>
<body bgcolor="#353970">
<h1>Add Article</h1>
<%-- <c:url var="viewArticlesUrl" value="/articles.html" /> --%>
<a href="./list.do">Show All Articles</a>
<br></br>
<%-- <c:url var="saveArticleUrl" value="/articles/save.html" /> --%>
<table id="submitArticalFormTable">
<form:form modelAttribute="article" method="POST" action="./save.do" id ="submitArtical">
<tr>
<td>
<form:label path="articleName">Article Name:</form:label>      
</td>
<td> 
<form:input path="articleName" size="46" />
</td>
</tr>
<tr>
<td>
<form:label path="articleDesc">Article Description:</form:label>
</td>
<td>
<form:textarea path="articleDesc" rows="3" cols="46" />
</td>
</tr>   
<tr>   
<td>             
<input type="submit" value="Save Article" />
</td>
<td>
<input type="button" value="Save Article Using AJAX" onclick="helloAJAX('submitArtical');" />
</td>
</tr>
</form:form>
</table>
</body>
</html>

Step 29 : Create file articlesList.jsp  under /WebContent/WEB-INF/view/ folder in project with following content .

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>All Articles</title>

</head>
<body bgcolor="#353970">
<h1>List Articles</h1>
<a href="add.do">Add Article</a>
<br></br>
<c:if test="${!empty articles}">
<table border="5" width="600">
<tr>
<th>Article ID</th>
<th>Article Name</th>
<th>Article Desc</th>
<th>Added Date</th>
</tr>
<c:forEach items="${articles}" var="article">
<tr>
<td><c:out value="${article.articleId}" /></td>
<td><c:out value="${article.articleName}" /></td>
<td><c:out value="${article.articleDesc}" /></td>
<td><c:out value="${article.addedDate}" /></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>

<!-- <a href="list.do">List of Articles</a>
<br />
<a href="add.do">Add Article</a> -->

Step 30 : Create file login.jsp  under /WebContent/WEB-INF/view/ folder in project with following content .

<html>
<head>
<title>Login</title>
</head>
<body bgcolor="#353970">
<table id="loginFormTable">
<form method="POST" action="./validate.do">
<tr>
<td>
<label>USER ID:</label>
</td>
<td>
<input name="userID" />
</td>
</tr>
<tr>
<td>
<label>Password:</label>
</td>
<td>
<input name="password" />
</td>
</tr>
<tr>
<td>
<input type="submit" value="login"/>
</td>
</tr>
</form>
</table>
</body>
</html>