Struts2+Hibernate+Freemarker实现【增删改查】生成静态页面!这是一个相对网上较全的案例。支持源码下载哦!
【Dao】
package com.athl.Dao.impl;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.athl.bean.Person;
import com.athl.utils.HibernateUtils;
public class PersonDao {
/**
* 查询所有
* @return
*/
@SuppressWarnings("unchecked")
public List<Person> queryAll(){
Session session=null;
Transaction t=null;
try{
//获取Session
session=HibernateUtils.getSession();
//开启事务
t = session.beginTransaction();
//HQL查询
Query q = session.createQuery("from Person");
return q.list();
}catch(Exception e){
throw new RuntimeException(e);
}finally{
t.commit();
session.close();
HibernateUtils.sfClose();
}
}
/**
* 添加或修改
* @param p
*/
public void save(Person p){
Session session =null;
Transaction t=null;
try{
//获取Session
session = HibernateUtils.getSession();
//开起事务
t = session.beginTransaction();
//执行插入操作
session.saveOrUpdate(p);
}catch(Exception e){
throw new RuntimeException(e);
}finally{
//事务提交,如果不提交不会发送sql到库中
t.commit();
session.close();
HibernateUtils.sfClose();
}
}
/**
* 删除
* @param id
*/
public void delete(Serializable id){
Session session=null;
Transaction t=null;
try{
session = HibernateUtils.getSession();
t = session.beginTransaction();
// 先根据id查询对象,再判断删除
Object obj = session.get(Person.class, id);
if(obj!=null){
session.delete(obj);
}
}catch(Exception e){
throw new RuntimeException(e);
}finally{
t.commit();
session.close();
HibernateUtils.sfClose();
}
}
/**
* 模糊查询
* @param condition
* @return
*/
@SuppressWarnings("unchecked")
public List<Person> queryLike(String condition){
Session session=null;
Transaction t=null;
try{
//获取Session
session=HibernateUtils.getSession();
//开启事务
t = session.beginTransaction();
//HQL查询
Query q = session.createQuery("from Person where name like :name or age like :age");
q.setString("name", "%"+condition+"%");
q.setString("age", "%"+condition+"%");
return q.list();
}catch(Exception e){
throw new RuntimeException(e);
}finally{
t.commit();
session.close();
HibernateUtils.sfClose();
}
}
/**
* 查询一条数据
* @param id
* @return
*/
public Person queryOne(Serializable id){
Session session=null;
Transaction t=null;
try{
//获取Session
session=HibernateUtils.getSession();
//开启事务
t = session.beginTransaction();
//主键查询
return (Person) session.get(Person.class, id);
}catch(Exception e){
throw new RuntimeException(e);
}finally{
t.commit();
session.close();
HibernateUtils.sfClose();
}
}
}
【Action】
package com.athl.action;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.athl.Dao.impl.PersonDao;
import com.athl.bean.Person;
import com.athl.utils.CreateHtml;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import freemarker.template.TemplateException;
public class PersonAction extends ActionSupport implements ModelDriven<Person> {
private static final long serialVersionUID = -814210299977683837L;
private String url,msg;
private Person p;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Person getModel() {
if(p==null){
p= new Person();
}
return p;
}
public String getAll() throws Exception {
CreateHtml createHtml = new CreateHtml();
Map<String, List<Person>> map = new HashMap<String, List<Person>>();
map.put("personlist", new PersonDao().queryAll());
String htmlName = "personList";
String ftl = "list.ftl";
try {
createHtml.init(ftl, htmlName, map);
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
url = "/"+htmlName;
return "list";
}
public String addPage() throws Exception {
CreateHtml createHtml = new CreateHtml();
//Map<String, List<Person>> map = new HashMap<String, List<Person>>();
//map.put("personlist", new PersonDao().query());
String htmlName = "add";
String ftl = "add.ftl";
try {
createHtml.init(ftl, htmlName, null);
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
url = "/"+htmlName;
return "addPage";
}
public String save() throws Exception {
new PersonDao().save(p);
return getAll();
}
public String queryById() throws Exception {
CreateHtml createHtml = new CreateHtml();
Map<String, Person> map = new HashMap<String,Person>();
map.put("person", new PersonDao().queryOne(p.getId()));
String htmlName = "update";
String ftl = "update.ftl";
try {
createHtml.init(ftl, htmlName, map);
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
url = "/"+htmlName;
return "update";
}
/*public String update() throws Exception {
new PersonDao().update(p);
return getAll();
}*/
public String delete() throws Exception {
new PersonDao().delete(p.getId());
return getAll();
}
public String queryLike() throws Exception {
CreateHtml createHtml = new CreateHtml();
Map<String, List<Person>> map = new HashMap<String, List<Person>>();
map.put("personlist", new PersonDao().queryLike(msg));
String htmlName = "personListByLike";
String ftl = "list.ftl";
try {
createHtml.init(ftl, htmlName, map);
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
url = "/"+htmlName;
return "list";
}
}
【hibernate.cfg.xml】
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/athl_ajax?useUnicode=true&characterEncoding=UTF-8</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- 方言,主要区别不同数据库的一些关键字,比如分页时, mysql 是limit,oracle 是rownum-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.show_sql">true</property>
<!-- 告诉hibernate在那个目录,那个文件是映射文件,需要加载 -->
<mapping resource="com/athl/bean/Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
【Person.hbm.xml】
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.athl.bean">
<class name="Person" table="person">
<!-- 主键 ,映射-->
<id name="id" column="id">
<generator class="native" />
</id>
<!-- 非主键,映射 -->
<property name="name" column="name"/>
<property name="age" column="age"/>
</class>
</hibernate-mapping>
【CreateHtml.java】
package com.athl.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class CreateHtml {
/**
* @param ftl 模版名.ftl
* @param htmlName 静态页面的名字
* @param map 数据
* @throws IOException
* @throws TemplateException
*/
@SuppressWarnings("rawtypes")
public void init(String ftl, String htmlName, Map map) throws IOException, TemplateException {
//一、创建负责管理 FreeMarker模板的 Configuration对象
Configuration cfg = new Configuration();
//指定FreeMarker模板文件的位置
cfg.setServletContextForTemplateLoading(ServletActionContext.getServletContext(), "/WEB-INF/template/");
cfg.setEncoding(Locale.getDefault(), "utf-8");
//二、创建Template对象
Template template = cfg.getTemplate(ftl);
template.setEncoding("utf-8");
//三、生成静态页面
//设置文件类型
htmlName=htmlName+".html";
//设置页面保存位置
String path = ServletActionContext.getServletContext().getRealPath("/");
File fileName = new File(path + htmlName);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"));
//将数据与模版整合,生成静态页面
template.process(map, out);
out.flush();
out.close();
}
}