參考別人例子Hibernate 的例子
第一步,我們要建立一個表 結構如下
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | MUL | NULL | auto_increment |
| title | varchar(400) | YES | | NULL | |
| content | text | YES | | NULL | |
| time | datetime | YES | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
第二步,在Eclipse中建立一個JAVA項目(我在項目中用到的包名是cn.com.nick.hbm)。編寫News.java類,這個類對應了資料庫中的表
package cn.com.nick.hbm;
import java.util.Date;
public class News
{
private int id;
private String title;
private String content;
private Date date;
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getContent()
{
return content;
}
public void setContent(String content)
{
this.content = content;
}
public Date getDate()
{
return date;
}
public void setDate(Date date)
{
this.date = date;
}
}
第三步,配置對應關係 儲存為News.hbm.xml檔案 與News類在同一目錄下(並不是一定要在同一目錄下,為了方便暫時先放在這裡)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!-- 這裡說明了cn.com.nick.hbm.News這個類對應了NEWS表,數據庫裱中的欄位和表名不區分大小寫 -->
<class name="cn.com.nick.hbm.News" table="NEWS">
<!-- 從這裡開始配置了News類中的屬性對應到表中的那個欄位,以及這個欄位的類型 -->
<id name="id" column="id">
<generator class="native" />
</id>
<!--
資料庫中的表名和欄位名都是不區分大小寫,所以這些欄位可以大寫也可以小寫column="title"
-->
<property name="title" type="string" column="title" />
<property name="content" type="string" column="content" />
<property name="date" type="timestamp" column="time" />
</class>
</hibernate-mapping>
第四步,配置hibernate.cfg.xml 注意這個名字不能改,並且要放到SRC的跟路徑下(這裡要注意,如果放錯地方樣本中的方法是找不到這個檔案的)
<?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 name="java:/hibernate/HibernateFactory">
<property name="show_sql">true</property><!-- 這裡配置成顯示SQL語句,方便調試 -->
<property name="connection.driver_class">
com.microsoft.jdbc.sqlserver.SQLServerDriver<!-- 這裡是sql2000的JDBC driver class名 -->
</property>
<property name="current_session_context_class">thread</property><!-- 配置上下文 -->
<property name="connection.url">
jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test<!-- 這裡是sql2000的hibernate_test資料庫URL -->
</property>
<property name="connection.username">sa</property><!-- 使用者名稱 -->
<property name="connection.password"></property>
<!-- 密碼 -->
<property name="dialect">
org.hibernate.dialect.SQLServerDialect<!-- 這裡是sql2000的Dialect -->
</property>
<property name="myeclipse.connection.profile">my</property>
<mapping resource="cn/com/nick/hbm/News.hbm.xml" /><!-- 指定News的對應檔 -->
</session-factory>
</hibernate-configuration>
最後建立一個測試類別 Test.java 代碼如下,裡邊有注釋說明
package cn.com.nick.hbm;
import java.util.Date;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
public class Test {
private static final SessionFactory sessionFactory;
static {
try {
// 這裡建立了SessionFactory 將hibernate.cfg.xml檔案放到SRC的跟路徑下
// Hibernate會自己找到
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void main(String[] args) {
// 執行個體化一個新的News對象,並填充內容
News news = new News();
news.setId(2);
news.setTitle("金春");
news.setContent("金春天天開心");
news.setDate(new Date());
Test t = new Test();
// 調用Test類下的儲存方法,相當於執行INSERT語句
t.Save(news);
// 調用查詢方法,顯示資料庫的內容
System.out.println("wwww");
t.select();
// 調用更新方法
// t.update();
// 調用刪除
// t.delete();
}
/**
* 一個簡單的添加資料方法
*
* @param news
* news對象,這個對象將被添加到庫中
*/
public void Save(News news) {
try {
// 擷取hibernate的session
Session session = Test.getSessionFactory().getCurrentSession();
session.beginTransaction();
// 這裡只需要調用save方法把news對象傳進去就插入成功了!
session.save(news);
session.getTransaction().commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 查詢方法
*/
public void select() {
try {
Session session = Test.getSessionFactory().getCurrentSession();
session.beginTransaction();
// 注意!!!這裡的 News 不是表名稱! 是對象名所以要注意大小寫
String sql = " from News";
// 帶條件的查詢
// String sql="from News where id=1";
// 用session.createQuery()執行HQL查詢語句
List<News> l = session.createQuery(sql).list();
// 在控制台迴圈輸出
for (News n : l) {
System.out.println(n.getId());
System.out.println(n.getTitle());
System.out.println(n.getContent());
System.out.println(n.getDate());
System.out.println("==============");
}
session.getTransaction().commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 更新方法
*/
public void update() {
try {
Session session = Test.getSessionFactory().getCurrentSession();
session.beginTransaction();
// 定義了要裝載對象的ID
Integer id = 1;
// 用load方法裝載一個對象進來
News n = (News) session.load(News.class, new Integer(id));
// 重新設定這個對象的標題
n.setTitle("更新後標題");
// 用update方法更新這個對象
session.update(n);
session.getTransaction().commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void delete() {
try {
Session session = Test.getSessionFactory().getCurrentSession();
session.beginTransaction();
// 定義了要裝載對象的ID
Integer id = 6;
// 用load方法裝載一個對象進來
News n = (News) session.load(News.class, new Integer(id));
// 用delete方法刪除這個對象
session.delete(n);
session.getTransaction().commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void delete1() {
Session session = Test.getSessionFactory().getCurrentSession();
session.beginTransaction();
Integer id = 6;
News n = (News) session.load(News.class, new Integer(id));
session.delete(n);
session.getTransaction().commit();
}
}
jsp上傳和下載較為複雜的例子
1upload,jsp檔案如下:
<form action="servlet/Upload" method="post">
<input type="file" name="file1">
<br>
<input type="file" name="file2">
<br>
<input type="file" name="file3">
<input type="submit" value="upload" />
<br>
<br>
<a href="servlet/down?downFile=入門教程.doc">down</a>
</form>
2、在servlet(Upload.java)中的dopost中寫代碼如下:
response.setContentType("text/html; charset=gb2312");
// 要下載的檔案名稱
// 之所以這樣處理,主要是因為檔案名稱的中文化問題,這樣處理的話,中文檔案名稱也會正常顯示
String aa=new String((request.getParameter("file1"))
.getBytes("iso8859-1"), "gb2312");
String bb=new String((request.getParameter("file2"))
.getBytes("iso8859-1"), "gb2312");
String cc=new String((request.getParameter("file3"))
.getBytes("iso8859-1"), "gb2312");
List<String> list = new ArrayList<String>();
if(aa!=null || !aa.equals(""))
list.add(aa);
if(!bb.equals("") || bb!=null)
list.add(bb);
if(cc!=null || !cc.equals(""))
list.add(cc);
// 建立上傳檔案存放的路徑
File uploadPath = new File(request.getRealPath("/downloadPath") );
System.out.println(uploadPath );
if (!uploadPath.exists()) {
uploadPath.mkdirs();
}
for (int i = 0; i < list.size(); i++) {
String fileName[] = new String[list.size()];
String exFileName[] = new String[list.size()];
// 檔案路徑
String filePath = list.get(i);
// 取上傳的檔案名稱
fileName[i] = filePath.substring(filePath.lastIndexOf("//") + 1,
filePath.length());
// 取檔案的副檔名稱
// exFileName[i] = filePath.substring(filePath.lastIndexOf("." + 1,
// filePath.length()));
// 在存放的目錄下建立檔案
File uploadFileName = new File(uploadPath, fileName[i]);
if (!uploadFileName.exists()) {
uploadFileName.createNewFile();
}
FileInputStream fin=new FileInputStream(filePath);
// 向伺服器寫入檔案
java.io.FileOutputStream fos = new java.io.FileOutputStream(uploadPath + "/" + fileName[i]);
int c = fin.read();
while (c != -1) {
fos.write((char)c);
c=fin.read();
}
fin.close();
fos.close();
}
4、下載servlet(down.java)的doget方法下代碼如下:
response.setContentType("text/html; charset=gb2312");
HttpSession session = request.getSession();
// 要下載的檔案名稱
String downloadfile = new String((request.getParameter("downFile"))
.getBytes("iso8859-1"), "gb2312");
ServletContext context = getServletContext();
ServletConfig config = getServletConfig();
// 擷取要下載檔案所在的目錄,這裡是對應於伺服器上的實體路徑
// 目錄的格式是這樣的:
// 根目錄(WEB主目錄所對應的實際物理目錄)
// +虛擬目錄(下載檔案存放的子目錄)
String downloadpath = context.getRealPath(File.separator)
+ "downloadPath" + File.separator;
System.out.println(downloadpath);
// 構建下載檔案的對象
java.io.File file = new java.io.File(downloadpath + downloadfile);
// 獲得檔案的長度
long filesize = file.length();
// 設定輸出格式
response.addHeader("content-type", "application/x-msdownload;");
response.addHeader("Content-Disposition", "attachment; filename="
+ response.encodeURL(downloadfile));//你要在儲存視窗中顯示的儲存檔案名稱
response.addHeader("content-length", Long.toString(filesize));
// 向用戶端寫入檔案
java.io.FileInputStream fin = new java.io.FileInputStream(file);
byte[] b = new byte[1];
int j = 0;
while ((j = fin.read(b)) > 0) {
response.getOutputStream().write(b);
}
fin.close();
3、web.xml檔案配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>Upload</servlet-name>
<servlet-class>com.Upload</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>down</servlet-name>
<servlet-class>com.down</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/servlet/Upload</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>down</servlet-name>
<url-pattern>/servlet/down</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>