1. 程式人生 > >貼吧專案(struts+hibernate)--邏輯程式碼

貼吧專案(struts+hibernate)--邏輯程式碼

分析:




程式碼:

Reply.java:

public class Reply {
	private Integer rid;
	private String replyContent;	//回覆的內容
	private String ipAddr;			//作者(回覆人)
	private Date createDate;		//回帖時間
	//多對一:多個回覆  屬於 【一個主題】
	private Topic topic;
	

Reply.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!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.itheima.domain">
   	<class name="Reply" table="t_Reply">
   		<id name="rid" column="rid" >
   			<generator class="native"></generator>
   		</id>
   		<property name="replyContent"  type="string" ></property>
   		<property name="ipAddr"  type="string" ></property>
   		<property name="createDate"   >
   			<column name="createDate" sql-type="datetime" ></column>
   		</property>
   		
   		<many-to-one name="topic" class="Topic" column="tid" ></many-to-one>
   	</class>
   </hibernate-mapping>
Topic.java:
//帖子
public class Topic {
	private Integer tid;
	private String title;			//標題
	private String topicContent;	//內容
	private String ipAddr;			//ip地址(作者)
	private Date lastReplyDate;		//最後回覆時間
	private Date createDate;		//發帖時間(建立時間)
	
	
	//一對多: 一個主題 可以擁有 【多個回覆】
	private Set<Reply> replySet = new HashSet<Reply>();

Topic.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!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.itheima.domain">
   	<class name="Topic" table="t_Topic">
   		<id name="tid" column="tid" >
   			<generator class="native"></generator>
   		</id>
   		<property name="title"  type="string" ></property>
   		<property name="topicContent"  type="string" ></property>
   		<property name="ipAddr"  type="string" ></property>
   		<property name="lastReplyDate"  >
   			<column name="lastReplyDate" sql-type="datetime" ></column>
   		</property>
   		<property name="createDate"   >
   			<column name="createDate" sql-type="datetime" ></column>
   		</property>
   
   		<set name="replySet">
   			<key column="tid"></key>
   			<one-to-many class="Reply" />
   		</set>
   	</class>
   </hibernate-mapping>

HibernateUtils:
package com.itheima.utils;

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

public class HibernateUtils {

	private static SessionFactory sf;
	
	static{
		//1載入配置
		Configuration  conf = new Configuration().configure();
		//2 根據Configuration 配置資訊建立 SessionFactory
		sf = conf.buildSessionFactory();
	}
	
	
	public static org.hibernate.Session  openSession(){
				
				//3 獲得session
				Session session = sf.openSession();
				
				return session;
	}
	
	public static org.hibernate.Session  getCurrentSession(){
		//3 獲得session
		Session session = sf.getCurrentSession();
		
		return session;
}
	public static void main(String[] args) {
		getCurrentSession();
	}
}

EncodingFilter:
package com.itheima.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * Servlet Filter implementation class EncodingFilter
 */
public class EncodingFilter implements Filter {

    /**
     * Default constructor. 
     */
    public EncodingFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		response.setContentType("text/html;charset=utf-8");
		//1 建立我們包裝之後的request物件
		ServletRequest req = new MyRequest((HttpServletRequest)request);
		//2放行(放行的request是我們包裝後的)
		chain.doFilter(req, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}

MyRequest:

package com.itheima.web.filter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestWrapper;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
//將已經是亂碼的引數,重新編碼回中文
public class MyRequest extends  HttpServletRequestWrapper{
	
	private Map<String,String[]> params =new HashMap<String, String[]>();
	
	public MyRequest(HttpServletRequest request) {
		super(request);
	// 在構造中獲得封裝引數的map, 將map中所有亂碼解決
	//-----------------------------------------------
		//1 獲得map
		Map<String,String[]> map = super.getParameterMap();
		//2 遍歷map
		if(map!=null && map.size()>0){
			for(Entry<String, String[]> en : map.entrySet()){
				//3 取出每個鍵值對,並解決值得亂碼(逆推法)
				String[] values = en.getValue();
				if(values!=null){
				String[] newValues = new String[values.length];
					for(int i = 0; i < values.length ;i++){
						try {
							newValues[i] = new String(values[i].getBytes("ISO-8859-1"),"UTF-8");
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					}
					//4 將解決的鍵值對 放入新的map
					params.put(en.getKey(), newValues);
					}
			}
		}
		
	}

	@Override
	public String getParameter(String name) {
		String[] values = params.get(name);
		
		if(values==null){//獲得的引數鍵不存在
			return null;
		}
		
		return values[0];
	}

	@Override
	public Map<String,String[]> getParameterMap() {
		
		return params;
	}
	
	@Override
	public String[] getParameterValues(String name) {
		return params.get(name);
	}

	

}

TransactionFilter:

package com.itheima.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.Hibernate;
import org.hibernate.Session;

import com.itheima.utils.HibernateUtils;

public class TransactionFilter implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		Session session  = HibernateUtils.getCurrentSession();
		
		session.beginTransaction();
		
		try {
			chain.doFilter(request, response);
			
			if(session!=null && session.isOpen()){
				session.getTransaction().commit();
			}
		} catch (Exception e) {
			e.printStackTrace();
			if(session!=null && session.isOpen()){
				session.getTransaction().rollback();
			}
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}

TopicDao:
package com.itheima.dao;

import java.util.List;

import com.itheima.domain.Topic;

public interface TopicDao {
	//儲存帖子
	void save(Topic t);
	//根據條件查詢帖子列表
	List<Topic> getAll(String key);
}

TopicDaoImpl:
package com.itheima.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.itheima.domain.Topic;
import com.itheima.utils.HibernateUtils;

public class TopicDaoImpl implements TopicDao {

	public void save(Topic t) {
		Session session = HibernateUtils.getCurrentSession();
		session.save(t);
	}

	public List<Topic> getAll(String key) {
		
		//1 獲得session
		Session session = HibernateUtils.getCurrentSession();
		//2 建立query物件 
		Query query = session.createQuery("from Topic where title like :key ");
		//3 設定引數
		if(key!=null && !"".equals(key.trim())){//頁面傳條件了
			query.setString("key", "%"+key+"%");
		}else{//頁面沒傳條件=>查詢所有
			query.setString("key", "%");
		}
		//4 查詢 list
		return query.list();
	}

}

TopicAction:
package com.itheima.web.action;

import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.itheima.dao.TopicDao;
import com.itheima.dao.TopicDaoImpl;
import com.itheima.domain.Topic;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class TopicAction extends ActionSupport {

	private TopicDao ud = new TopicDaoImpl();
	private Topic topic;
	private String key;

	//帖子列表
	public String list(){
		//1呼叫dao獲得帖子列表
		List<Topic> list = ud.getAll(key);
		//2 將帖子列表放入ActionContext中
		ActionContext.getContext().put("list", list);
		
		return "list";
	}
	
//------------------------------------------------------
	//發帖
	public String add(){
		
		//1 ip
		topic.setIpAddr(ServletActionContext.getRequest().getRemoteAddr());
		//2 建立/回帖時間
		topic.setCreateDate(new Date());
		topic.setLastReplyDate(topic.getCreateDate());
		//3儲存
		ud .save(topic);
		
		return "toList";
	}
//---------------------------------------------------------------
	
	
	public Topic getTopic() {
		return topic;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public void setTopic(Topic topic) {
		this.topic = topic;
	}

}

hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!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/ee19_tieba
	</property>
	<property name="hibernate.connection.username">root</property>
	<property name="hibernate.connection.password">1234</property>

	<property name="hibernate.dialect">
		org.hibernate.dialect.MySQLDialect
	</property>
	<property name="show_sql">true</property>
	<property name="format_sql">true</property>

	<property name="current_session_context_class">thread</property>

	<property name="hbm2ddl.auto">update</property>
	<mapping resource="com/itheima/domain/Reply.hbm.xml" />
	<mapping resource="com/itheima/domain/Topic.hbm.xml" />
</session-factory>
</hibernate-configuration>

struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<package name="tieba" namespace="/" extends="struts-default" >
		<action name="TopicAction_*" method="{1}" class="com.itheima.web.action.TopicAction" >
			<result name="toList" type="redirectAction">
             <param name="actionName">TopicAction_list</param>
             <param name="namespace">/</param>
         </result>
		<result name="list" >/index.jsp</result>
		</action>
	</package>
</struts>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name></display-name>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
   <filter>
    <filter-name>TransactionFilter</filter-name>
    <filter-class>com.itheima.web.filter.TransactionFilter</filter-class>
  </filter>
  <filter>
    <filter-name>EncodeFilter</filter-name>
    <filter-class>com.itheima.web.filter.EncodingFilter</filter-class>
  </filter>
  
  <filter-mapping>
    <filter-name>EncodeFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>TransactionFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

</web-app>