Simple Blog type web-application using Struts+Hibernate+MySql

  1. Create table in database “mahendra”

create table blogEntry

(

blogid int primary key auto_increment,

username varchar(35)not null,

emailid varchar(60)not null,

message varchar(1000),

edate timestamp default now()

);

  1. Create new Dynamic Web Application using eclipse.
  2. Add required libraries into “lib” folder.
  3. Modify “web.xml” fileà add following lines:

<filter>

<filter-name>mahendra</filter-name>

<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>

</filter>

<filter-mapping>

<filter-name>mahendra</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

  1. Create new JSP page inside “WebContent”à index.jsp
  2. Run your application for testing
  3. Create new “Source Folder” with name : “resources”
  4. Add new File with name: log4j.properties with following contents:

log4j.rootLogger = DEBUG, CA, FA

log4j.appender.CA = org.apache.log4j.ConsoleAppender

log4j.appender.CA.layout = org.apache.log4j.PatternLayout

log4j.appender.CA.ConversionPattern=%-5p %c %x {%m} %n

log4j.appender.FA = org.apache.log4j.FileAppender

log4j.appender.FA.layout = org.apache.log4j.PatternLayout

log4j.appender.FA.File=./sample.log

log4j.appender.FA.ConversionPattern=%-4r [%t] %-5p %c %x – %m%n

  1. Add new XML file with name “struts.xml” with following contents

<!DOCTYPE struts PUBLIC

“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”

http://struts.apache.org/dtds/struts-2.0.dtd&#8221;

>

<struts>

<package name=“default” extends=“struts-default” namespace=“”>

<action name=“review” class=“com.mahendra.ReviewsAction” method=“list”>

<result>/WEB-INF/pages/reviews.jsp</result>

<result name=“error”>/WEB-INF/pages/reviews.jsp </result>

</action>

<action name=“add_review” class=“com.mahendra.ReviewsAction” method=“add”>

<result name=“success” type=“chain”>review</result>

<result name=“error”>/WEB-INF/pages/reviews.jsp </result>

</action>

</package>

</struts>

  1. Create new class called “Reviews” (Model component)

package com.mahendra;

import java.sql.Timestamp;

import javax.persistence.*;

@Entity

@Table(name=”blogentry”)

public class Reviews implements java.io.Serializable{

private static final long serialVersionUID = 1L;

private int blogid;

private String username;

private String emailid;

private String message;

private Timestamp edate;

@Id

@GeneratedValue

public int getBlogid() {

return blogid;

}

public void setBlogid(int blogid) {

this.blogid = blogid;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getEmailid() {

return emailid;

}

public void setEmailid(String emailid) {

this.emailid = emailid;

}

public String getMessage() {

return message;

}

public void setMessage(String message) {

this.message = message;

}

public Timestamp getEdate() {

return edate;

}

public void setEdate(Timestamp edate) {

this.edate = edate;

}

public Reviews(int blogid, String username, String emailid, String message

) {

super();

this.blogid = blogid;

this.username = username;

this.emailid = emailid;

this.message = message;

}

public Reviews() {

super();

}

}

  1. Create new class called “HibernateUtils” :

package com.mahendra;

import org.hibernate.*;

import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtils {

private static SessionFactory sessionFactory = buildFactory();

private static SessionFactory buildFactory(){

try{

return new AnnotationConfiguration().configure().buildSessionFactory();

}catch(Exception ex){

throw new ExceptionInInitializerError(“Unable to initialize session factory”);

}

}

public static SessionFactory getSessionFactory(){

return sessionFactory;

}

public static Session getSession()

{

return sessionFactory.getCurrentSession();

}

}

  1. Create new class “ReviewsManager”

package com.mahendra;

import java.util.List;

import org.hibernate.HibernateException;

import org.hibernate.*;

public class ReviewsManager {

@SuppressWarnings(“unchecked”)

public List<Reviews> getAllReviews(){

Session session = HibernateUtils.getSession();

List<Reviews> list = null;

Transaction tran = null;

try{

tran = session.beginTransaction();

list = (List<Reviews>)session.createQuery(“from Reviews”).list();

tran.commit();

}catch(HibernateException he){

tran.rollback();

throw new MyException(“Unable to retrieve list of Reviews”,he.getMessage());

}

return list;

}

public void addReview(Reviews review){

Session session = HibernateUtils.getSession();

Transaction tran = null;

try{

tran = session.beginTransaction();

session.save(review);

tran.commit();

}catch(HibernateException he){

throw new MyException(“Unable to add your review.”,he.getMessage());

}

}

}

  1. Create new Exception with name “MyException”

package com.mahendra;

public class MyException extends RuntimeException {

String technicalDetails;

public MyException() {

// TODO Auto-generated constructor stub

}

public MyException(String arg0) {

super(arg0);

// TODO Auto-generated constructor stub

}

public MyException(String arg0, String arg1) {

super(arg0);

technicalDetails = arg1;

}

public String getTechnicalDetails(){

return technicalDetails;

}

}

  1. Create “ReviewAction” (Action compoenet)

package com.mahendra;

import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class ReviewsAction extends ActionSupport{

private static final long serialVersionUID = 1L;

private ReviewsManager rman = null;

private Reviews review = null;

private List<Reviews> reviewList = null;

public ReviewsAction(){

rman = new ReviewsManager();

}

public String list()

{

try{

reviewList = rman.getAllReviews();

return “success”;

}catch(ExceptionInInitializerError ex){

addActionMessage(“Could not connect with database”);

addActionError(“ERROR: “+ex.getMessage());

return “error”;

}catch(MyException me){

addActionMessage(me.getMessage());

addActionError(me.getTechnicalDetails());

return “error”;

}

}

public String add(){

try{

rman.addReview(getReview());

return “success”;

}catch(MyException me){

addActionMessage(me.getMessage());

addActionError(me.getTechnicalDetails());

return “error”;

}

}

public Reviews getReview() {

return review;

}

public void setReview(Reviews review) {

this.review = review;

}

public List<Reviews> getReviewList() {

return reviewList;

}

public void setReviewList(List<Reviews> reviewList) {

this.reviewList = reviewList;

}

}

  1. Create new JSP page :  /WEB-INF/pages/reviews.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”&gt;

<%@taglib uri=http://java.sun.com/jsp/jstl/core&#8221;  prefix=“c”%>

<%@taglib uri=“/struts-tags”  prefix=“s”%>

<html>

<head>

<meta http-equiv=“Content-Type” content=“text/html; charset=ISO-8859-1”>

<title>Insert title here</title>

</head>

<body>

list of reviews

<c:if test=${reviewList != null }>

<c:forEach items=${reviewList} var=“review”>

<table border=“1” width=“300” align=“right”>

<tr>

<td width=“100”>${review.blogid}</td>

<td>by ${review.username}</td>

<td>EMail: ${review.emailid}</td>

</tr>

<tr>

<td>Message: </td>

<td colspan=“2”>

${review.message }

</td>

</tr>

<tr>

<td colspan=“3” align=“right”>

recorder at : ${review.edate}

</td>

</tr>

</table> <br/>

</c:forEach>

</c:if>

<c:if test=“{reviewList is empty}”>

No reviews found!<br/>

Be First to add review..!

</c:if>

<s:form action=“add_review” method=“POST”>

<s:textfield name=“review.username” label=“Your name: “>

</s:textfield><br/>

<s:textfield name=“review.emailid” label=“Your Email ID:”></s:textfield><br/>

<s:textarea name=“review.message” label=“Your views:” rows=“4” cols=“40”>

</s:textarea><br/>

<s:submit value=“Submit”></s:submit>

</s:form>

<s:actionmessage/>

<font face=“Tahoma” size=“2” color=“red”>

<s:actionerror/>

</font>

</body>

</html>

  1. Create new JSP page index.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”&gt;

<html>

<head>

<meta http-equiv=“Content-Type” content=“text/html; charset=ISO-8859-1”>

<title>Home page: Mahendra’s Blog</title>

</head>

<body>

<h2>Some topic…..</h2>

<p>

Some details here…..

</p>

<a href=“reviews”>View / Add Reviews</a>

</body>

</html>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s