jpa之hibernate4.2.4之tomcat6.0测试

这里有jpa的很多例子 http://www.objectdb.com/java/jpa/persistence/store 是很好的学习资料

 

开发环境:myeclipse 10.0

服务器:tomcat 6.0

oracle:11g

hibernate版本:4.2.4

 

1.新建名为JpaWeb的web工程 添加依赖的jar包 添加配置文件 详细步骤前面博客已有提到 这里就不说了

persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
        version="2.0">
    <persistence-unit name="under">
        <properties>
        <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="hibernate.connection.username" value="under_test" />
         <property name="hibernate.connection.password" value="under_test" />
         <property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:ganew" />
         <property name="hibernate.hbm2ddl.auto" value="update" />
         <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
        </properties>
    </persistence-unit>
</persistence>


 

 



 

2.修改index.jsp文件  如下:

 

<%@page import="com.bean.Vistor"%>
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript">
	function check()
	{
		if(document.getElementById("nameid").value=="") { alert('姓名不能为空'); return false;}
		if(document.getElementById("hobbyid").value=="") { alert('爱好不能为空'); return false;}
		document.getElementById("vis").submit();
	}
	</script>
  </head>
  
  <body>
     <form method="post" action="<%=request.getContextPath() %>/DealCommit" id="vis"> 
     	姓名:<input type="text" name="name" id="nameid"> <br/>
     	爱好:<input type="text" name="hobby" id="hobbyid"><br/>
     	<input type="button" value="提交" onclick="check();">
     </form>
     <hr/>
     <ol>
     <%
     	List<Vistor> list=(List<Vistor>)request.getAttribute("list");
     	if(list!=null) {
     	for(Vistor vistor:list) { %>
     	  <li><%=vistor %></li>
      <%} 
      }%>
      </ol>
  </body>
</html>


 

 


  上面页面有一个表单 用户可以输入姓名和爱好 提交到servlet之后 会将系统中所有登陆的记录全部显示在界面上

DealCommit的servlet实现

packagecom.undergrowth;

 

importjava.io.IOException;

importjava.io.PrintWriter;

importjava.util.List;

 

importjavax.persistence.EntityManager;

importjavax.persistence.EntityManagerFactory;

importjavax.persistence.Query;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

 

importcom.bean.Vistor;

 

public classDealCommit extends HttpServlet {

 

/**

* Constructor of theobject.

*/

public DealCommit() {

super();

}

 

/**

* Destruction of theservlet. <br>

*/

public void destroy(){

super.destroy(); //Just puts "destroy" string in log

// Put your code here

}

 

/**

* The doGet method ofthe servlet. <br>

*

* This method iscalled when a form has its tag value method equals to get.

*

* @param request therequest send by the client to the server

* @param response theresponse send by the server to the client

* @throwsServletException if an error occurred

* @throws IOExceptionif an error occurred

*/

public voiddoGet(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

request.setCharacterEncoding("gbk");

EntityManagerFactoryfactory=(EntityManagerFactory)getServletContext().getAttribute("factory");

EntityManagermanager=factory.createEntityManager();

try {

Stringname=request.getParameter("name");

Stringhobby=request.getParameter("hobby");

manager.getTransaction().begin();

manager.persist(newVistor(name, hobby));

manager.getTransaction().commit();

 

//获取所有记录

Queryquery=manager.createQuery("select v from Vistor v");

List<Vistor>list=query.getResultList();

request.setAttribute("list",list);

request.getRequestDispatcher("/index.jsp").forward(request,response);

} catch (Exception e){

e.printStackTrace();

}finally{

manager.close();

}

 

 

}

 

/**

* The doPost methodof the servlet. <br>

*

* This method iscalled when a form has its tag value method equals to post.

*

* @param request therequest send by the client to the server

* @param response theresponse send by the server to the client

* @throwsServletException if an error occurred

* @throws IOExceptionif an error occurred

*/

public voiddoPost(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

 

this.doGet(request,response);

}

 

/**

* Initialization ofthe servlet. <br>

*

* @throwsServletException if an error occurs

*/

public void init()throws ServletException {

// Put your code here

}

 

}


在上面的servlet中 从应用程序级别获取了factory对象 因为在应用web启动的时候 注册了一个servletcontextlistener的实现类 这个实现类就是在应用启动时 初始化了一个factory的实例 存入了应用程序的属性中

并且将用户提交的姓名还有爱好存入的数据库中  并且将数据库中已有的对象全部查询出来 返回给index.jsp页面显示

JpaListener的监听器代码如下:

应用启动的时候 获取EntityManagerFactory实例存入application的属性中 应用关闭的时候 关闭EntityManagerFactory的实例

packagecom.undergrowth;

 

importjavax.persistence.EntityManagerFactory;

importjavax.persistence.Persistence;

importjavax.servlet.ServletContextEvent;

importjavax.servlet.ServletContextListener;

 

public classJpaListener implements ServletContextListener {

 

@Override

public voidcontextDestroyed(ServletContextEvent arg0) {

// TODOAuto-generated method stub

EntityManagerFactoryfactory=(EntityManagerFactory)arg0.getServletContext().getAttribute("factory");

factory.close();

}

 

@Override

public voidcontextInitialized(ServletContextEvent arg0) {

// TODO Auto-generatedmethod stub

EntityManagerFactoryfactory=Persistence.createEntityManagerFactory("under");

arg0.getServletContext().setAttribute("factory",factory);

}

 

}

 

当然 还需要在web.xml中加入监听器的配置项  如下:

<listener>

<listener-class>com.undergrowth.JpaListener</listener-class>

</listener>

 

再来看看这里的实体对象 Vistor的实现代码:

package com.bean;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;


@Entity
public class Vistor {
	@Id @GeneratedValue
	private Integer id;
	@Column(length=12,nullable=false)
	private String name;
	@Lob 
	private String hobby;
	@Temporal(TemporalType.TIMESTAMP)
	private Date loginTime=new Date(System.currentTimeMillis());
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getHobby() {
		return hobby;
	}
	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	public Date getLoginTime() {
		return loginTime;
	}
	public void setLoginTime(Date loginTime) {
		this.loginTime = loginTime;
	}
	public Vistor(){}
	public Vistor(String name, String hobby) {
		super();
		this.name = name;
		this.hobby = hobby;
	}
	@Override
	public String toString() {
		return  name + "\t" + hobby
				+ "\t" + loginTime.toLocaleString();
	}
	
}


 

 


 

index.jsp效果图:

 

 

 



 


 


 

 

posted on 2013-10-04 21:56  liangxinzhi  阅读(156)  评论(0编辑  收藏  举报