Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The Development of javaWeb Campus Network (2)

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Today, we mainly integrate Spring and Hibernate into CMS and complete simple database queries.

First of all, integrate Spring, first add jar to the web project, there is no requirement for the jar of Spring (preferably more than 3.0), add Spring snooping in web.xml, guide the project to start Spring, and configure the parameter contextConfigLocation to load the configuration file of Spring.

ContextConfigLocation classpath:applicationContext.xml struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 * .do org.springframework.web.context.ContextLoaderListener / public/index.jsp

Now let's take a look at how to configure applicationContext.xml.

⑴ naturally cannot do without database connection configuration in the first place: what you need to note here is that there are several types of data sources, depending on your preferences. I use BasicDataSource here, and I need to introduce commons-dbcp.jar,commons-pool.jar.

This configuration of the data source has two disadvantages, one is that the database password is not encrypted, and the other is that the parameter values are not externally managed.

The so-called externalized management is to save the parameters that the configuration file needs to pass in a separate .properties file.

There is a tag in Spring that does a good job of this. Currently, the applicationContext.xml file is configured as follows:

Jdbc.properties file content: (database configuration according to your own needs)

Jdbc.driverClassName=oracle.jdbc.driver.OracleDriverjdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:orcljdbc.username=cmsjdbc.password=cms

Now there are two ways to integrate Hibernate,Spring integration Hibernate into Spring:

1. Completely use hibernate to write the dao layer, and inject dao into spring to manage the life cycle by spring. The advantage of this approach is that there is no coupling relationship between the dao layer and spring; the disadvantage is that you need to carefully deal with hibernate's session shutdown, exception, transaction.

2. Use HibernateDaoSupport of spring. In this way, the dao layer uses a series of template methods provided by spring, without worrying about session, exception, and transaction management is also handed over to spring. The first way is not to say, there is basically no need to change the Dao layer. You just need to inject dao, just learn the second one.

Configure hibernate in applicationContext.xml, which is mainly divided into three parts:

1. Introduce the data source configuration, that is, dataSource above.

2.hibernate property configuration.

3. There are two ways to load the entity class: either to list it or to read it by the system itself.

Hibernate.dialect=org.hibernate.dialect.OracleDialect hibernate.hbm2ddl.auto=none hibernate.show_sql=true

The above configuration of the database is basically completed, and transaction control is used in the configuration.

Now we can start to complete the simple login, with regard to the acegi configuration in the system is not parsed for the time being, we mainly verify that the database is configured successfully.

Emphasize here, about the jar reference of hibernate, according to the error prompt oneself to go to Baidu, here I will not list which jar is needed.

Let's go back to index.jsp in the previous chapter. We know that the CMS content display system mainly displays some content as soon as the system enters the home page, so here we need to modify the way to enter the index.jsp. Previously, we used welcome-file to go directly to the home page, and now we use the page configured with welcome-file to call action to query the data and return the index.jsp to display the data.

Add toindex.jsp first

Then modify the welcome-file in web.xml to call action in struts2

Toindex.jsp

We mainly check whether hibernate can be used first, so we first make headlines. We add index to struts.xml.

The action,struts.xml is as follows:

Public/index.jsp

With regard to calling action on the home page, I encountered the first bottleneck here, first of all, the following is not configured in struts.xml

So my struts2 request has always been 404, because the result of my previous configuration on struts2 integration is as follows. If it is configured to * .action, there is no need to configure the above constant. Do is because of personal configuration.

Struts2 * .do

Now we first write hibernate interface classes, the main function of this class is reuse, we should know that basically simple entity classes have to add, delete, change, check, so we need to extract these methods, according to the transfer parameters to achieve code reuse.

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 Multiplex Class Provide methods that can be reused by all entity classes * @ throws * / public interface IHibernateSupportDao {/ * * @ author zangyn * @ date 2016-11-14 6:15:27 * @ Title: findByExample * @ Description: return type based on sql query result * @ 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 implements IHibernateSupportDao {@ Autowired public SessionFactory sessionFactory @ Transactional @ Override public List findByExample (DetachedCriteria dc) {return dc.getExecutableCriteria (sessionFactory.getCurrentSession ()) .list () }} here we use sessionFactory.getCurrentSession () to get session, and another method is openSession (). These two methods are different, and there are both on the Internet. Here we will encounter a problem. We have to add Spring transaction control to applicationContext.xml, and then add @ Transactional to the Dao layer database method.

In this way, the method of essionFactory.getCurrentSession () can be used, and there is also an explanation on the Internet, and those who have questions can be found.

Entity class 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; / / title private String author; / / author private String source / / Source private Date pubtime=new Date (); / / release time private String content; / / content private Integer viewNum=0; / / number of views private String img; / / News cover picture private Integer status=1 / / News status 1 is normal, 2 recommended, 3 headlines, 4 homepage flash Photo News @ 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 layer 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;@Servicepublic class NewService {@ Autowired private NewDao newDao; public List getNewList (DetachedCriteria newsBigImgdc) {return newDao.findByExample (newsBigImgdc);}}

DAO layer NewDao.java

Package com.dao;import com.bean.NewsEntity;public interface NewDao extends IHibernateSupportDao {}

NewDaoImpl.java

Package com.dao.impl;import org.springframework.stereotype.Repository;import com.bean.NewsEntity;import com.dao.NewDao;@Repositorypublic class NewDaoImpl extends IHibernateSupportDaoImpl 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;@Controllerpublic class LoginAction extends ActionSupport {@ Autowired private NewService service Private List newsBigImgList; public List getNewsBigImgList () {return newsBigImgList;} public void setNewsBigImgList (List 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;}}

In the above code, we can see that I used @ AutoWired automatic injection. Here I encounter the second entangled problem, that is, bean is already in the container, but it can't be injected here. After looking up a lot of information, we found that we have to introduce the jar package struts2-spring-plugin-2.1.8.1.jar, which is used for the integration of spring and struts2.

Now we create tables and add data in the database

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,', 'Campus Network', 4, 'freshman Beauty freshman report', 'admin' To_date ('27-04-2013 17 3315), 'dd-mm-yyyy hh34:mi:ss'), 0,' 20060502213355913.jpghammer, 3) Insert into news (ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID) values (12,', '', 4, 'this campus news 1, you know.' , 'admin', to_date (' 27-04-2013 1715) 35V 24th, 'dd-mm-yyyy hh34:mi:ss'), 0,200812201116135572.jpgboat, 3); insert into news (ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID) values (13,', , 2, 'this campus news 2, you know.' , 'admin', to_date (' 27-04-2013 17 null, 'dd-mm-yyyy hh34:mi:ss'), 0, null, 3); insert into news (ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID) values (14,', , 1, 'this campus news 1, you know.' , 'admin', to_date (' 27-04-2013 17 ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID) values (15,', , 1, 'this campus elegant demeanor news 1, you know.' , 'admin', to_date (' 27-04-2013 17 null 37 dd-mm-yyyy hh34:mi:ss'), 0, null, 4); insert into news (ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID) values (16,', '', 2, 'this campus demeanor news 2, you know.' , 'admin', to_date (' 27-04-2013 17 null), 'dd-mm-yyyy hh34:mi:ss'), 0, null, 4); insert into news (ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID) values (17,', , 2, 'this campus elegant demeanor news 2, you know.' , 'admin', to_date (' 27-04-2013 17 null), 'dd-mm-yyyy hh34:mi:ss'), 0, null, 4); insert into news (ID, CONTENT, SOURCE, STATUS, TITLE, AUTHOR, PUBTIME, VIEWNUM, IMG, MENUID) values (18,', '', 2, 'this campus style news 1, you know.' , 'admin', to_date (' 27-04-2013 17 null 37 null 27), 'null, 4)

At this time, when we enter the home page, we will query the table and display it. Pay attention to this part of the index.jsp page, cycle through the queried list, and then poll the display. We can learn from this later.

Var focus_width=300; var focus_height=230; var swf_height = focus_height Var picPath='$ {cms} / paired pictures; var pics='' Var links=''; pics+=picPath+' |' Links+= "|" Pics=pics.substring (0pics. Pictures 1) Links=links.substring (0magic links.expresthMur1); var flash_path='' [xss_clean] ('); [xss_clean] ('') [xss_clean] ('); [xss_clean] ('') [xss_clean] ('); [xss_clean] ('')

Let's take a look at the current effect picture:

At present, the integration between SSH3 frameworks has been initially completed, and the rest is to add other functions. We need to focus on permission control later. I upload the code of this section to 51, address: http://down.51cto.com/data/2259941.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report