This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Object Relational Mapping and the fly likes Hibernate and JSP Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Hibernate and JSP" Watch "Hibernate and JSP" New topic
Author

Hibernate and JSP

Zoran Roncevic
Greenhorn

Joined: Nov 17, 2011
Posts: 13

Hello,

I learned some Hibernate and I would like to putt it to use with my knowledge of JSP. I would like to make a web page and try to make something bigger out of it.
Can somebody help me?
I know how to map the entity class and I make a configuration xml, that part is ok. But the problem that's bugging me is the class that get's the object and passes it to JSP. I can't seem to get the JSP to show it.
Can somebody give me a simple example, please?

Btw. I didn't know where to post this question, so I decided here, because it deals more with Hibernate than with JSP
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

There are two steps.

(1) Get the data from Hibernate into a Java object.

(2) Put that object into some context where the JSP can access it.

So now I don't understand the question. You say you can't make the JSP work. So that's step (2). But you put the question here because you think it's about Hibernate? That's step (1). So which of those two is your problem?
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1012
    
    5

Hi Zoran

Post your code/configuration and explain the error/problem in more detail with reference to the code.
Zoran Roncevic
Greenhorn

Joined: Nov 17, 2011
Posts: 13

This is my code:
UserDetails class:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

public class UserDetail {

@Entity
public class UserDetails {

@Id @GeneratedValue (strategy=GenerationType.AUTO)
private int userId;
private String userName;


public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}

}

Class Pokusaj to get the object:
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Pokusaj {

Session session = null;

public List getActorsByID(){
List<UserDetail> actorList = null;

try {

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();

Query query = session.createQuery("from UserDetails");
query.setCacheable(true);
actorList = query.list();

session.getTransaction().commit();
session.close();


} catch (Exception e) {
e.printStackTrace();
}

return actorList;
}
}

and JSP dohvat.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.List"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="net.artofz.hibernate.Pokusaj"%>
<%@ page import="net.artofz.test.JdbcDemo"%>
<!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>Insert title here</title>
</head>
<body>

<%
Pokusaj pokusaj = new Pokusaj();
List list = pokusaj.getActorsByID();
request.setAttribute("database", list);

%>


<table border=1>
<c:forEach var="row" items="${database}">
<tr>
<td><cut value="${row.userId}"/></td>
<td><cut value="${row.userName}"/></td>
</tr>
</c:forEach>
</table>

</body>
</html>

Configuration class:
<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>
<property name="connection.username">postgres</property>
<property name="connection.password">9999</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>


<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>

<!-- Names the annotated entity class -->
<mapping class="net.artofz.hibernate.UserDetail"/>

</session-factory>

</hibernate-configuration>
--------------------------------------------------------
I found in some article that when you work with Hibernate and JSP you can't access the object directly in the jsp, so you have to put in a list and pass to a setAttribute. Is that true? Because I already have a list that was created when obtaining the object, that would be putting a list in a list?
This is the error/exception I get. It basically means that I'm missing a class??? Can somebody please help me, I will be so thankful. It's driving me crazy and it must be some rookie mistake


type: Exception report

org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/hibernate/Session
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:534)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:442)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

root Cause:
javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/hibernate/Session
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:911)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:840)
org.apache.jsp.dohvat_jsp._jspService(dohvat_jsp.java:99)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

java.lang.NoClassDefFoundError: org/hibernate/Session
org.apache.jsp.dohvat_jsp._jspService(dohvat_jsp.java:78)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722

java.lang.ClassNotFoundException: org.hibernate.Session
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
org.apache.jsp.dohvat_jsp._jspService(dohvat_jsp.java:78)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)


Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

So you didn't put the Hibernate jar into your application's classpath -- in other words, you didn't put it into the application's WEB-INF/lib folder. Do that and then redeploy the application.
Zoran Roncevic
Greenhorn

Joined: Nov 17, 2011
Posts: 13

Paul Clapham wrote:So you didn't put the Hibernate jar into your application's classpath -- in other words, you didn't put it into the application's WEB-INF/lib folder. Do that and then redeploy the application.


Like I wrote earlier dumb rookie mistake! I was trying to start a fresh new project and I forgot the jars. I don't get the error now, but my jsp comes as empty, but the table has records. That is my mistake...
Zoran Roncevic
Greenhorn

Joined: Nov 17, 2011
Posts: 13

Zoran Roncevic wrote:
Paul Clapham wrote:So you didn't put the Hibernate jar into your application's classpath -- in other words, you didn't put it into the application's WEB-INF/lib folder. Do that and then redeploy the application.


Like I wrote earlier dumb rookie mistake! I was trying to start a fresh new project and I forgot the jars. I don't get the error now, but my jsp comes as empty, but the table has records. That is my mistake...


I tried doing this:

Pokusaj pokusaj = new Pokusaj();
List list = pokusaj.getActorsByID();
request.setAttribute("database", list);

In a servlet and then redirecting to a jsp. The redirecting part works, but it doesn't print any resoult

Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60752
    
  65

A redirect is incorrect in this case. It creates a new request that does not contain your scoped variable. Is there a reason you cannot forward?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Zoran Roncevic
Greenhorn

Joined: Nov 17, 2011
Posts: 13

Bear Bibeault wrote:A redirect is incorrect in this case. It creates a new request that does not contain your scoped variable. Is there a reason you cannot forward?


Forget about the redirecting, I tried it just in case. My main question is: when I put this code in JSP, why it's not working. It's giving me a blank page
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

You mean you put those three lines of code into a JSP, and expected that something would appear in the generated HTML?
Zoran Roncevic
Greenhorn

Joined: Nov 17, 2011
Posts: 13

Paul Clapham wrote:You mean you put those three lines of code into a JSP, and expected that something would appear in the generated HTML?


I didn't put just that three lines of code and expect to generate something in HTML! :-) I posted the complete JSP, but here it is again:


Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Sorry, I didn't see the original version because it was combined with a huge amount of configuration files which I got tired of scrolling past.

Anyway, two things:

(1) Perhaps you got no output because there was no data in your List.

(2) You are assuming that your scriptlet code will run before your EL code. I wouldn't guarantee that's true -- actually I have no idea whether it is true or not because I wouldn't ever do such a thing. Don't mix scriptlets with EL. In your case you could (and should) put that Java code in the servlet which forwards to this JSP.
Zoran Roncevic
Greenhorn

Joined: Nov 17, 2011
Posts: 13

I'm from Croatia and it's now passed 1am, so I'm a bit tired and I going to sleep now, but tomorrow I will try to figure this thing out.
I already tried the servlet thing with forwarding, but it didn't work.
First thing tomorrow I will try to print the result to a main class to see if I get anything and see what happens
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60752
    
  65

Zoran Roncevic wrote:I already tried the servlet thing with forwarding, but it didn't work.


It's the correct approach. Stick with it until you get it to work.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

One possibility is that your getActorsByID() method throws an exception. All you do is to write that exception to a log somewhere and continue, with an empty List. And since your problem is (or may be) that you have an empty List, that could be the cause. Check your server logs to see if you logged such an exception.
James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 1012
    
    5

Sounds like the ideal scenario to add and analyse some additional log output.
Zoran Roncevic
Greenhorn

Joined: Nov 17, 2011
Posts: 13

Finally got it working!

I have my entity class that I want to get data from UserDetails. I putt hibernate annotations in there.
Then I made a Servlet BookListServlet with the following code in the doGet method:



In the servlet I execute the query and the result is put inside a list named books. The list was set in the request setAttribute. Close the session and redirect to booklist.jsp with the following code:


And it's simple as that :-) Thanks to everyone that helped me along the way to the result! The code is here, you just need basic Hibernate knowledge, and you have your self a small JSP & Hibernate tutorial
 
Consider Paul's rocket mass heater.
 
subject: Hibernate and JSP
 
Similar Threads
JSP Beginner - Need Help
How to make a bean class for rich:dataGrid?
How to show plural charts in one JSP page?
Oracle Varray - Hibernate
How do you access DynaValidatorForm properties in a JSP?