Tuesday, July 06, 2010

Integration of Portal with SQL using Spring Frame Work and Hibernate


TestPortalSpringHibernateMySQL: This project shows you the usage of Portal, Spring and Hibernate on My-SQL DataBase.

LoginFormController:

package Controller;

import javax.portlet.ActionRequest;

import javax.portlet.ActionResponse;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.datasource.DriverManagerDataSource;

import org.springframework.validation.BindException;

import org.springframework.web.portlet.mvc.SimpleFormController;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.view.RedirectView;

public class LoginFormController extends SimpleFormController {

@Override

public void onSubmitAction(ActionRequest request, ActionResponse response, Object command, BindException errors) throws Exception {

LoginFormData formData = (LoginFormData)command;

if (request.getParameter("Insert") != null) {

// delete object

Insert(command, errors);

} else if (request.getParameter("Update") != null) {

// Update object

Update(command, errors);

} else if (request.getParameter("Delete") != null) {

// Delete object

Delete(command, errors);

}

}

public void Insert(Object command, BindException errors) throws Exception {

/*

LoginFormData formData = (LoginFormData)command;

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost/siddhutest_db");

dataSource.setUsername("root");

dataSource.setPassword("");

JdbcTemplate template = new JdbcTemplate(dataSource);

template.update("insert into test_table (id, name) values (?, ?)", new Object[] {formData.getId(), formData.getName()});

*/

LoginFormData formData = (LoginFormData)command;

Session session = null;

try{

// This step will read hibernate.cfg.xml and prepare hibernate for use

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

session =sessionFactory.openSession();

//Create new instance of Contact and set values in it by reading them from form object

test_table objtest_table = new test_table();

objtest_table.setId(formData.getId());

objtest_table.setName(formData.getName());

session.save(objtest_table);

}catch(Exception e){

e.printStackTrace();

}finally{

// Actual contact insertion will happen at this step

session.flush();

session.close();

}

}

public void Update(Object command, BindException errors) throws Exception {

/*

LoginFormData formData = (LoginFormData)command;

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost/siddhutest_db");

dataSource.setUsername("root");

dataSource.setPassword("");

JdbcTemplate template = new JdbcTemplate(dataSource);

template.update("update test_table set name = ? where id = ?", new Object[] {formData.getName(),formData.getId()});

*/

LoginFormData formData = (LoginFormData)command;

Session session = null;

try {

SessionFactory fact = new Configuration().configure().buildSessionFactory();

session = fact.openSession();

Transaction tr = session.beginTransaction();

test_table objtest_table = (test_table)session.get

(test_table.class, formData.getId());

objtest_table.setName(formData.getName());

session.update(objtest_table);

tr.commit();

session.close();

}

catch(Exception e){

System.out.println(e.getMessage());

} finally{

// Actual contact insertion will happen at this step

session.flush();

session.close();

}

}

public void Delete(Object command, BindException errors) throws Exception {

/*

LoginFormData formData = (LoginFormData)command;

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost/siddhutest_db");

dataSource.setUsername("root");

dataSource.setPassword("");

JdbcTemplate template = new JdbcTemplate(dataSource);

template.update("delete from test_table where id = ?", new Object[] {formData.getId()});

*/

LoginFormData formData = (LoginFormData)command;

Session sess = null;

try {

SessionFactory fact = new Configuration().configure().buildSessionFactory();

sess = fact.openSession();

test_table objtest_table = (test_table)sess.get(test_table.class, formData.getId());

Transaction tr = sess.beginTransaction();

objtest_table.setName(formData.getName());

sess.delete(objtest_table);

tr.commit();

sess.close();

}

catch(Exception e){

System.out.println(e.getMessage());

} finally{

// Actual contact insertion will happen at this step

sess.flush();

sess.close();

}

}

}

LoginFormData:

package Controller;

import java.io.Serializable;

public class LoginFormData implements Serializable{

private String id;

private String name;

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

test_table:

package Controller;

/**

* @author Siddharatha Dhumale

*

*

* Java Class to map to the datbase Contact Table

*/

public class test_table {

private String id;

private String name;

/**

* @return

*/

public String getId() {

return id;

}

/**

* @return

*/

public void setId(String id) {

this.id = id;

}

/**

* @return

*/

public String getName() {

return name;

}

/**

* @return

*/

public void setName(String name) {

this.name = name;

}

}

TestPortalSpringHibernateMySQL:

package testPortalSpringHibernateMySQL;

import java.util.HashMap;

import java.util.Map;

import javax.portlet.ActionRequest;

import javax.portlet.ActionResponse;

import javax.portlet.RenderRequest;

import javax.portlet.RenderResponse;

import org.springframework.web.portlet.ModelAndView;

import org.springframework.web.portlet.mvc.Controller;

public class TestPortalSpringHibernateMySQL implements Controller {

/* (non-Javadoc)

* @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)

*/

/*

@Override

protected void doView(RenderRequest request, RenderResponse response)

throws PortletException, IOException, UnavailableException {

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

writer.write("Hello World!");

writer.close();

}*/

/**

* action method.

*/

public void handleActionRequest(ActionRequest request,

ActionResponse response) throws Exception {

//-- do nothing the Hello World portlet doesn't receive

//-- action requests.

}

/**

* render method.

*/

public ModelAndView handleRenderRequest(RenderRequest request,

RenderResponse response) throws Exception {

Map model = new HashMap();

model.put("helloWorldMessage", "Hello World HelloWorldController");

return new ModelAndView("helloWorld", model);

}

}

hibernate.cfg.xml:

xml version='1.0' encoding='utf-8'?>

DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driverproperty>

<property name="hibernate.connection.url">jdbc:mysql://localhost/siddhutest_dbproperty>

<property name="hibernate.connection.username">rootproperty>

<property name="hibernate.connection.password">property>

<property name="hibernate.connection.pool_size">10property>

<property name="show_sql">trueproperty>

<property name="dialect">org.hibernate.dialect.MySQLDialectproperty>

<property name="hibernate.hbm2ddl.auto">updateproperty>

<mapping resource="test_table.hbm.xml"/>

session-factory>

hibernate-configuration>

test_table.hbm.xml:

xml version="1.0"?>

DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="Controller.test_table" table="test_table">

<id name="id" column="id" >

<generator class="assigned"/>

id>

<property name="name">

<column name="name"/>

property>

class>

hibernate-mapping>

applicationContext.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:p="http://www.springframework.org/schema/p"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

beans>

default-object.xml:

xml version="1.0" encoding="UTF-8"?>

DOCTYPE deployments PUBLIC

"-//JBoss Portal//DTD Portal Object 2.6//EN"

"http://www.jboss.org/portal/dtd/portal-object_2_6.dtd">

<deployments>

<deployment>

<parent-ref>default.defaultparent-ref>

<if-exists>overwriteif-exists>

<window>

<window-name>

TestPortalSpringHibernateMySQLWindow

window-name>

<instance-ref>

TestPortalSpringHibernateMySQLInstance

instance-ref>

<region>centerregion>

<height>1height>

<initial-window-state>maximizedinitial-window-state>

window>

deployment>

deployments>

EnterData.jsp:

<html>

<head>

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

<title>Database Modificationtitle>

head>

<body>

No Action has been done on the Database side please check the DB for more confirmation.

body>

html>

helloWorld.jsp:

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

<%@ page contentType="text/html" isELIgnored="false" %>

<c:out value="${helloWorldMessage}"/>

LogIn.jsp:

<%@page contentType="text/html"%>

<%@page pageEncoding="UTF-8"%>

<%@ taglib prefix="portlet" uri="http://java.sun.com/portlet_2_0" %>

<html>

<body>

<form method="POST" action="<portlet:actionURL/>">

ID:<input type="text" name="id" /><br/>

Name:<input type="text" name="name" /><br/>

<input type="submit" value="Insert1" name="Insert"/>

<input type="submit" value="Update1" name="Update"/>

<input type="submit" value="Delete1" name="Delete"/>

form>

body>

html>

ResultPage.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>

<body>

<h1>Data Base is updated Successfully!h1>

body>

html>

portlet.xml:

xml version="1.0" encoding="UTF-8"?>

<portlet-app

xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd"

version="2.0">

<portlet>

<portlet-name>TestPortalSpringHibernateMySQLportlet-name>

<display-name>TestPortalSpringHibernateMySQLdisplay-name>

<portlet-class>org.springframework.web.portlet.DispatcherPortletportlet-class>

<supports>

<mime-type>text/htmlmime-type>

<portlet-mode>viewportlet-mode>

<portlet-mode>editportlet-mode>

<portlet-mode>helpportlet-mode>

supports>

<portlet-info>

<title>TestPortalSpringHibernateMySQLtitle>

portlet-info>

portlet>

portlet-app>

portlet-instances.xml:

xml version="1.0" encoding="UTF-8"?>

DOCTYPE deployments PUBLIC

"-//JBoss Portal//DTD Portlet Instances 2.6//EN"

"http://www.jboss.org/portal/dtd/portlet-instances_2_6.dtd">

<deployments>

<deployment>

<instance>

<instance-id>

TestPortalSpringHibernateMySQLInstance

instance-id>

<portlet-ref>TestPortalSpringHibernateMySQLportlet-ref>

instance>

deployment>

deployments>

TestPortalSpringHibernateMySQL-portlet.xmlL:

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:p="http://www.springframework.org/schema/p"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<bean id="TestPortalSpringHibernateMySQL" class="testPortalSpringHibernateMySQL.TestPortalSpringHibernateMySQL" />

<bean id="loginFormController" class="Controller.LoginFormController">

<property name="formView" value="LogIn" />

<property name="successView" value="ResultPage" />

<property name="commandName" value="loginData" />

<property name="commandClass" value="Controller.LoginFormData" />

bean>

<bean id="portletModeHandlerMapping"

class="org.springframework.web.portlet.handler.PortletModeHandlerMapping">

<property name="portletModeMap">

<map>

<entry key="view">

<ref bean="loginFormController" />

entry>

<entry key="edit">

<ref bean="loginFormController" />

entry>

map>

property>

bean>

<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="viewClass"

value="org.springframework.web.servlet.view.InternalResourceView" />

<property name="prefix" value="/WEB-INF/jsp/" />

<property name="suffix" value=".jsp" />

bean>

beans>

web.xml:

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>TestPortalSpringHibernateMySQLdisplay-name>

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>

listener>

<servlet>

<servlet-name>view-servletservlet-name>

<servlet-class>org.springframework.web.servlet.ViewRendererServletservlet-class>

<load-on-startup>1load-on-startup>

servlet>

<servlet-mapping>

<servlet-name>view-servletservlet-name>

<url-pattern>/WEB-INF/servlet/viewurl-pattern>

servlet-mapping>

web-app>


No comments: