Magazine
 
Integrating Struts and Hibernate

import
javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
import java.util.List;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import
org.apache.struts.action.ActionForward;
import
org.apache.struts.action.ActionMapping;
import roseindia.net.plugin.HibernatePlugIn;
import roseindia.net.dao.hibernate.Tutorial;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.Criteria;
public class SearchTutorialAction extends
Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
Exception{
SearchTutorialActionForm formObj =
(SearchTutorialActionForm)form;
System.out.println(“Getting session
factory”);
/*Get the servlet context */
ServletContext context =
request.getSession().getServletContext();
/*Retrieve Session Factory */
SessionFactory _factory = (SessionFactory)
context.getAttribute
(HibernatePlugIn.SESSION_FACTORY_KEY);
/*Open Hibernate Session */
Session session = _factory.openSession();
//Criteria Query Example
Criteria crit =
session.createCriteria(Tutorial.class);
crit.add(Restrictions.like(“shortdesc”, “%”
+ formObj.getKeyword() +”%”)); //Like

 

condition
//Fetch the result from database
List tutorials= crit.list();
request.setAttribute(“searchresult”,tutorials);
/*Close session */
session.close();
System.out.println(“Hibernate Session
Closed”);
return mapping.findForward(“success”);
}
}

5. Entries into struts-config.xml
Add the following lines into your strutsconfig. xml file.

Form Bean:
<form-bean
name=”TutorialSearch”
type=”roseindia.web.SearchTutorialActionForm”>
</form-bean>
Action Entry:
<action
path=”/searchTutorial”
type=”roseindia.web.SearchTutorialAction”
name=”TutorialSearch”
scope=”request”
validate=”true”
input=”/pages/SearchTutorial.jsp”>
<forward name=”success” path=”/pages/
SearchResultPage.jsp”/>
</action>

Now we have created all the required stuffs for the web client. In the next section we will test our application.

6. Building and Testing Struts Hibernate Plugin Application
In this section we will build and test our Struts Hibernate Integration application. Compiling and packaging application
Since we are using ant build tool, so the compiling and packaging will done by ant tool. To compile and create war file for deployment, open console and go to “C:\Struts-

 
 
Dec 2007 | Java Jazz Up |60
previous
index
next
 
View All Topics
All Pages of this Issue
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 ,

Download PDF