溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

javaWeb校內(nèi)網(wǎng)開發(fā)(二)

發(fā)布時(shí)間:2020-07-14 08:48:29 來源:網(wǎng)絡(luò) 閱讀:1248 作者:zangyanan2016 欄目:數(shù)據(jù)庫

  今天主要將Spring、Hibernate集成進(jìn)CMS中,以及完成簡單的數(shù)據(jù)庫查詢。

     首先集成Spring,首先web項(xiàng)目中加入jar,關(guān)于Spring的jar這里不做要求(最好都用3.0以上的),在web.xml中加入Spring的監(jiān)聽,引導(dǎo)項(xiàng)目啟動(dòng)Spring,配置contextConfigLocation這個(gè)參數(shù)來裝入Spring的配置文件。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <!-- Spring配置文件引入 -->
  <context-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>
  			classpath:applicationContext.xml
  		</param-value>
  </context-param>	
	<!-- Struts2引入 -->
  <filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>*.do</url-pattern>
 </filter-mapping>
  <!-- Spring啟動(dòng)配置 -->
 <listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
</listener>
 <!-- 歡迎頁面 -->
 <welcome-file-list>
    <welcome-file>/public/index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

現(xiàn)在我們來看一下applicationContext.xml應(yīng)該怎么配置?

⑴首先自然不能少了數(shù)據(jù)庫連接配置:這里需要注意的就是數(shù)據(jù)源類型有幾種,根據(jù)個(gè)人喜好。這里我用BasicDataSource,需要引入commons-dbcp.jar,commons-pool.jar。

<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
		<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"></property>
		<property name="username" value="root"></property>
		<property name="password" value="123456"></property>
</bean>

這樣配置數(shù)據(jù)源有2個(gè)缺點(diǎn),一個(gè)是數(shù)據(jù)庫密碼沒有加密,一個(gè)是參數(shù)值沒有外在化管理。

所謂外在化管理,就是將配置文件需要傳遞參數(shù)單獨(dú)用.properties文件保存。

Spring中有個(gè)標(biāo)簽可以很好的完成這項(xiàng)工作。目前applicationContext.xml文件配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

 <context:property-placeholder location="classpath:jdbc.properties" />
  
  <bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}"></property>
		<property name="url" value="${jdbc.url}"></property>
		<property name="username" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
  </bean>


</beans>

jdbc.properties文件內(nèi)容:(數(shù)據(jù)庫配置根據(jù)自己需要配置)

jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
jdbc.username=cms
jdbc.password=cms

現(xiàn)在我們?cè)赟pring中集成Hibernate,Spring集成Hibernate有兩種:

1 .完全使用hibernate編寫dao層,把dao注入到spring由spring來管理生命周期,這種方式的好處是dao層與spring沒有耦合關(guān)系;缺點(diǎn)是需要謹(jǐn)慎處理hibernate的session 關(guān)閉, exception, transaction. 

2 .使用spring的HibernateDaoSupport.這樣的話dao層使用spring提供的一系列模板方法,同時(shí)不用關(guān)心session, exception,事務(wù)管理也交給了spring.第一種方式就不說了,基本無需改變dao層。只需要把dao注入就可以了,就學(xué)習(xí)一下第二種

applicationContext.xml配置hibernate,主要分成3個(gè)部分:

1.引入數(shù)據(jù)源配置,即上面dataSource。

2.hibernate屬性配置。

3.實(shí)體類加載,兩種方法:要么自己列出來,要么要系統(tǒng)自己去讀取。

 <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="hibernateProperties">
            <value>
                <!-- 設(shè)置數(shù)據(jù)庫方言 -->
                hibernate.dialect=org.hibernate.dialect.OracleDialect
                <!-- 設(shè)置自動(dòng)創(chuàng)建|更新|驗(yàn)證數(shù)據(jù)庫表結(jié)構(gòu) -->
                hibernate.hbm2ddl.auto=none
                <!-- 是否在控制臺(tái)顯示sql -->
                hibernate.show_sql=true
            </value>
        </property>
		<property name="packagesToScan" value="com.bean" />
	</bean>

以上關(guān)于數(shù)據(jù)庫的配置基本已經(jīng)完成,關(guān)于事務(wù)控制等用到在配置。

現(xiàn)在我們可以開始去完成簡單的登錄了,關(guān)于系統(tǒng)中acegi配置暫時(shí)不解析,我們主要驗(yàn)證數(shù)據(jù)庫是否配置成功。

這里強(qiáng)調(diào)一下,關(guān)于hibernate的jar引用,根據(jù)錯(cuò)誤提示自己去百度,這里我就不列舉需要哪些jar了。

我們回到上一章的index.jsp,我們知道CMS內(nèi)容展示系統(tǒng)主要在系統(tǒng)剛進(jìn)入主頁就會(huì)展示一些內(nèi)容,因此這里我們要修改一下進(jìn)入index.jsp的方式,前面我們用welcome-file來直接進(jìn)主頁,現(xiàn)在我們這用welcome-file配置的頁面調(diào)用action來查詢數(shù)據(jù)然后返回index.jsp來展示數(shù)據(jù)。

先新增toindex.jsp

<%@ page language="java" pageEncoding="utf-8"%>
<jsp:forward page="index.do"></jsp:forward>

然后修改web.xml中welcome-file來調(diào)用struts2中的action

 <welcome-file-list>
    <welcome-file>toindex.jsp</welcome-file>
  </welcome-file-list>

我們主要是先檢驗(yàn)hibernate是否能使用,因此先制作新聞?lì)^條這個(gè)功能,我們?cè)趕truts.xml中添加index

這個(gè)action,struts.xml如下:

<?xml version="1.0" encoding="GBK"?>
 <!DOCTYPE struts PUBLIC
     "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
   "http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<constant name="struts.action.extension" value="do" />
   <package name="CMS" extends="struts-default">
      <action name="index" class="com.action.LoginAction" method="toIndex">
          <result name="success">public/index.jsp</result>
      </action>
  </package>
 </struts>

關(guān)于進(jìn)首頁就調(diào)用action,這里我遇到第一個(gè)瓶頸,首先是struts.xml中未配置以下

<constant name="struts.action.extension" value="do" />

那么我的struts2請(qǐng)求一直是404,因?yàn)榍懊骊P(guān)于struts2的集成我的配置結(jié)果如下,如果配置成*.action就不用配置上面常量,do是因?yàn)閭€(gè)人配置。

  <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>*.do</url-pattern>
 </filter-mapping>

現(xiàn)在我們編寫先編寫hibernate接口類,此類的作用主要是復(fù)用,大家應(yīng)該清楚基本上簡單的實(shí)體類都存在增、刪、改、查,因此我們需要將這些方法都提取出來,根據(jù)傳遞參數(shù)不同來實(shí)現(xiàn)代碼的復(fù)用。

IHibernateSupportDao.java

package com.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
/**
 * 
  * @author zangyn
  * @date 2016-11-14 下午6:14:40
  * @Description: hibernate復(fù)用類,提供所有實(shí)體類能夠重復(fù)使用的方法
  * @throws
 */
public interface IHibernateSupportDao<T> {
	/**
	 * 
	  * @author zangyn
	  * @date 2016-11-14 下午6:15:27
	  * @Title: findByExample
	  * @Description: 根據(jù)sql查詢結(jié)果
	  * @return List    返回類型
	  * @throws
	 */
	public abstract List findByExample(DetachedCriteria dc);
}

IHibernateSupportDaoImpl.java

package com.dao.impl;

import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.dao.IHibernateSupportDao;

public class IHibernateSupportDaoImpl<T> implements IHibernateSupportDao<T>{
	@Autowired
	public SessionFactory sessionFactory;
	@Transactional  
	@Override
	public List findByExample(DetachedCriteria dc) {
		return dc.getExecutableCriteria(sessionFactory.getCurrentSession()).list();
	}

}
這里用sessionFactory.getCurrentSession()獲取session,還有一種方法是openSession(),這兩種方法是由區(qū)別的,具體網(wǎng)上都有,這里我們會(huì)遇到一個(gè)問題,我們必須在applicationContext.xml中添加Spring事務(wù)控制,然后在dao層數(shù)據(jù)庫方法上添加@Transactional 這個(gè)注解

 <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory"></property>

</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>   

這樣essionFactory.getCurrentSession()這個(gè)方法才能用,具體網(wǎng)上也有講解,有疑問的可以查找。

實(shí)體類NewsEntity

package com.bean;

import java.io.Serializable;
import java.util.Date;

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

@SuppressWarnings("serial")
@Entity
@Table(name="news")
public class NewsEntity implements Serializable{

	private Integer id;
	private String title;  //標(biāo)題
	private String author;  //作者
	private String source;   //來源
	private Date pubtime=new Date();  //發(fā)布時(shí)間
	private String content;  //內(nèi)容
	private Integer viewNum=0;  //瀏覽數(shù)目
	private String img; //新聞封面圖片
	private Integer status=1; //新聞狀態(tài) 1普通,2推薦, 3欄目頭條, 4首頁flash 圖片新聞
	
	@Id
	@GeneratedValue
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	@Column(name="title",length=50,nullable=false)
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	@Column(name="author",length=10,nullable=true)
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	@Column(name="source",length=20,nullable=true)
	public String getSource() {
		return source;
	}
	public void setSource(String source) {
		this.source = source;
	}
	@Column(name="pubtime")
	public Date getPubtime() {
		return pubtime;
	}
	public void setPubtime(Date pubtime) {
		this.pubtime = pubtime;
	}
	@Column(name="content",length=65535,nullable=false)
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	@Column(name="viewnum")
	public Integer getViewNum() {
		return viewNum;
	}
	public void setViewNum(Integer viewNum) {
		this.viewNum = viewNum;
	}
	@Column(name="img",length=50,nullable=true)
	public String getImg() {
		return img;
	}
	public void setImg(String img) {
		this.img = img;
	}
	@Column(name="status")
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
}

Service層NewService.java

package com.service;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bean.NewsEntity;
import com.dao.NewDao;

@Service
public class NewService {
	
	@Autowired
	private NewDao newDao;
	
	public List<NewsEntity>  getNewList(DetachedCriteria newsBigImgdc){
		return newDao.findByExample(newsBigImgdc);
	}

}

DAO層NewDao.java

package com.dao;

import com.bean.NewsEntity;
public interface NewDao extends IHibernateSupportDao<NewsEntity>{

}

NewDaoImpl.java

package com.dao.impl;

import org.springframework.stereotype.Repository;

import com.bean.NewsEntity;
import com.dao.NewDao;
@Repository
public class NewDaoImpl  extends IHibernateSupportDaoImpl<NewsEntity> implements NewDao{

}

LoginAction.java

package com.action;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.stereotype.Controller;

import com.bean.NewsEntity;
import com.opensymphony.xwork2.ActionSupport;
import com.service.NewService;

@Controller
public class LoginAction extends ActionSupport{
	
	@Autowired
	private NewService service;
	
	private List<NewsEntity> newsBigImgList;


	public List<NewsEntity> getNewsBigImgList() {
		return newsBigImgList;
	}

	public void setNewsBigImgList(List<NewsEntity> newsBigImgList) {
		this.newsBigImgList = newsBigImgList;
	}

	public String toIndex(){
		DetachedCriteria newsBigImgdc = DetachedCriteria.forClass(NewsEntity.class);
		newsBigImgdc.add(Restrictions.eq("status", 4));
		newsBigImgList=service.getNewList(newsBigImgdc);
		return SUCCESS;
	}
}

在上面代碼我們可以看到我用了@AutoWired自動(dòng)注入,這里我遇到第二個(gè)糾結(jié)的問題,就是bean已經(jīng)在容器里了,但是這里一直不能注入,查找了很多資料,后面才發(fā)現(xiàn)我們必須引入struts2-spring-plugin-2.1.8.1.jar這個(gè)jar包,這個(gè)是spring與struts2整合用的包。

現(xiàn)在我們?cè)跀?shù)據(jù)庫創(chuàng)建表和加入數(shù)據(jù)

create table NEWS
(
  id      NUMBER,
  content CLOB,
  source  VARCHAR2(20),
  status  NUMBER,
  title   VARCHAR2(50),
  author  VARCHAR2(10),
  pubtime DATE,
  viewnum NUMBER,
  img     VARCHAR2(50),
  menuid  NUMBER
)

insert into news (ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID)
values (10, '<CLOB>', '校園網(wǎng)', 4, '大一美女新生報(bào)道', 'admin', to_date('27-04-2013 17:33:39', 'dd-mm-yyyy hh34:mi:ss'), 0, '20060502213355913.jpg', 3);

insert into news (ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID)
values (12, '<CLOB>', '哈哈', 4, '這個(gè)校園動(dòng)態(tài)新聞1,你懂的。', 'admin', to_date('27-04-2013 17:35:24', 'dd-mm-yyyy hh34:mi:ss'), 0, '200812201116135572.jpg', 3);

insert into news (ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID)
values (13, '<CLOB>', '哈哈', 2, '這個(gè)校園動(dòng)態(tài)新聞2,你懂的。', 'admin', to_date('27-04-2013 17:35:42', 'dd-mm-yyyy hh34:mi:ss'), 0, null, 3);

insert into news (ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID)
values (14, '<CLOB>', '哈哈', 1, '這個(gè)校園動(dòng)態(tài)新聞1,你懂的。', 'admin', to_date('27-04-2013 17:36:34', 'dd-mm-yyyy hh34:mi:ss'), 0, null, 3);

insert into news (ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID)
values (15, '<CLOB>', '哈哈', 1, '這個(gè)校園風(fēng)采新聞1,你懂的。', 'admin', to_date('27-04-2013 17:37:10', 'dd-mm-yyyy hh34:mi:ss'), 0, null, 4);

insert into news (ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID)
values (16, '<CLOB>', '哈哈', 2, '這個(gè)校園風(fēng)采新聞2,你懂的。', 'admin', to_date('27-04-2013 17:37:19', 'dd-mm-yyyy hh34:mi:ss'), 0, null, 4);

insert into news (ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID)
values (17, '<CLOB>', '哈哈', 2, '這個(gè)校園風(fēng)采新聞2,你懂的。', 'admin', to_date('27-04-2013 17:37:19', 'dd-mm-yyyy hh34:mi:ss'), 0, null, 4);

insert into news (ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID)
values (18, '<CLOB>', '哈哈', 2, '這個(gè)校園風(fēng)采新聞1,你懂的。', 'admin', to_date('27-04-2013 17:37:27', 'dd-mm-yyyy hh34:mi:ss'), 0, null, 4);

這時(shí)候我們進(jìn)入首頁就會(huì)查詢這張表并展示,注意index.jsp頁面的這一塊,循環(huán)遍歷查詢到的list,然后輪詢展示,這個(gè)以后遇到了可以借鑒。

<div >
									<script type=text/javascript>
										var focus_width=300;
										var focus_height=230;
										var swf_height = focus_height;
										var picPath='${cms}/p_w_picpaths/';
										var pics='';
										var links='';
										<c:forEach items="${newsBigImgList}" var="nb">
										pics+=picPath+'<c:out value="${nb.img}"/>|';
										links+="<c:url value="/news/see.do?id=${nb.id}"/>|";
										</c:forEach>
										pics=pics.substring(0,pics.length-1);
										links=links.substring(0,links.length-1);
										var flash_path='<c:url value="/p_w_picpaths/s_flash.swf"/>';
										document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+ focus_width +'" height="'+ swf_height +'">');
										document.write('<param name="allowScriptAccess" value="sameDomain"><param name="movie" value="'+flash_path+'"><param name="quality" value="high"><param name="bgcolor" value="#F0F0F0">');
										document.write('<param name="menu" value="false"><param name=wmode value="opaque">');
										document.write('<param name="FlashVars" value="pics='+pics+'&links='+links+'&borderwidth='+focus_width+'&borderheight='+focus_height+'">');
										document.write('<embed src="'+flash_path+'" wmode="opaque" FlashVars="pics='+pics+'&links='+links+'&borderwidth='+focus_width+'&borderheight='+focus_height+'" menu="false" bgcolor="#F0F0F0" quality="high" width="'+ focus_width +'" height="'+ swf_height +'" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');		
										document.write('</object>');
									</script>
								</div>

我們看一下現(xiàn)在的效果圖:

javaWeb校內(nèi)網(wǎng)開發(fā)(二)

目前已經(jīng)初步完成了SSH3個(gè)框架之間的集成,剩下的就是添加其他的功能,關(guān)于權(quán)限的控制我們后面需要重點(diǎn)做,這節(jié)的代碼我上傳到51,地址:http://down.51cto.com/data/2259941

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI