Java Open Source Framework Springside 3.1.4.3 Development Web Demo Project Combat

Source: Internet
Author: User
Tags connection pooling stub

Original:Java Open source framework Springside 3.1.4.3 Development Web Demo Project actual combat

Source code: Http://www.zuidaima.com/share/1781596496120832.htm


Springside 3.1.4.3 is currently the latest version of Springside, but also a relatively high degree of completion of a version, used to do the actual project development should be no problem. Here's the whole process of developing a simple Web project using this version, and of course, the most important is my own experience. My article is very long, only with the patience of a closer look, to understand the three flavors.

The first step, download Springside 3.1.4.3 all-in-one version. This process is too simple, Springside's official website is www.springside.org.cn, go there can download, All-in-one version of course is the choice of lazy people. Here is a very funny, this version is labeled Springside 3.1.4.3, but after downloading the unzip, Unzip the file is springside-3.1.4.2, this may be a little bit of the south of the small mistake, according to my guess, 3.1.4.3 more 3.1.4.1 progress should be joined Jsp-api.jar this a library, hope white this time not to change this version number on the error and then launch a new version, If you really want to launch a new version, how should I add the multi-database configuration I recently researched.

Step two, install Springside. If a previous version of Springside has been installed, It is best to delete the. M2 folder in the user directory, which is the location of Maven's local repository, although Maven can effectively ensure that the library file does not have a version conflict, but deleting this folder will make the installation process faster, otherwise, the Springside installation process will not stop asking you to overwrite such files. After deleting the. M2 folder, run the Quickstart.bat in the bin directory under the springside-3.1.4.2 directory (as long as you have installed JDK5 or above, if you don't have a JDK on your computer, don't come to Springside's Muddy Waters). Waiting for this file to run, you can see the three sample projects provided by Springside 3 Mini-web, Mini-service, showcase are all running, you can take a look at the Springside implementation of the various features.

Take a closer look at the bin directory of Springside and find that the script provided by this version is more explicit and useful, such as start-db.bat can be used to start the Derby database, Start-selenium.bat to start selenium server, And Start-tomcat.bat then don't say, the earth people know.

If you want to use Springside to build the project, there is a little bit of work to do, which is to add the Maven bin directory to the PATH environment variable, such as:


The third step is to build the project using Springside. Run the New-project.bat in the bin directory, such as:


During the creation of the project, the script raises a number of questions, where GroupID refers to the name of your organization, because the project is purely exemplary for my personal contribution. So I filled in the youxia.personal, so on the 5th question, I chose Personal.you as the name of the package in my project, which is also in line with international practice; Artifactid refers to the name of the project, which is multidatasourceexample , the name is a bit long, as you can see from the name I want to demonstrate the configuration of multiple data sources.

fourth step, start Eclipse, import the project. The resulting project is located in the Tools\generator\generated-project directory under the Springside directory, and the following is Eclipse's:


After the project import is successful, Eclispe Explorer:

  can see that once the project is imported, immediately available, a annoying red fork is not, which is also explained that this version is a revolutionary version of Springside 3, starting from this version, Springside 3 has increased the ease of use more than one grade.

Eclipse recommends the use of version 3.4 and above, because in this version, the management of the Tomcat server is more convenient, you can automatically open the Tomcat server and deploy the project by selecting run on server from the project's shortcut menu, for example:


It is important to note that since the project generated by Springside is using the Derby database by default, you must start the Derby database before you can successfully run the project, remember the previously mentioned Start-db.bat? Run it! Then run the Init-db.jar in the project's Bin directory, placing the project's initialization data in the database.

You can then click Run on server to start the project, and let's see the embedded browser, Tomcat server view, and console view of Eclipse. It's really convenient:


Fifth Step, migrate the database to MySQL. in the project, the statements that create the database and initialize the database exist as SQL files, such as:


But the statement is for Derby, and if you want to apply it to MySQL, you have to make some changes. Modify Schema.sql first, as follows:

drop table if exists resources_authorities; drop table if exists roles_authorities; drop table if exists users_roles; drop table if exists RESOURCES; DROP table if exists authorities; drop table if exists USERS; drop table if exists ROLES;  CREATE TABLE USERS (ID integer primary key auto_increment,login_name varchar) NOT NULL unique, PASSWORD varchar (20 ), NAME varchar (+), EMAIL varchar (30)); Create unique index users_login_name_index on USERS (login_name); CREATE TABLE ROLES (ID integer PRIMARY key auto_increment,name varchar () not null unique); CREATE TABLE Users_roles (user_id integer NOT null, role_id integer NOT NULL, FOREIGN KEY (role_id) references ROLES (ID) , FOREIGN KEY (user_id) references USERS (ID)); CREATE TABLE Authorities (ID Integer primary key auto_increment,name varchar) NOT NULL, display_name varchar (20) Not null);  CREATE TABLE roles_authorities (role_id integer NOT null, authority_id integer NOT NULL, FOREIGN KEY (role_id) references RoLES (ID), FOREIGN KEY (authority_id) references authorities (ID));  CREATE TABLE RESOURCES (ID integer PRIMARY key auto_increment,resource_type varchar () NOT NULL, VALUE varchar (255) Not NULL, order_num float is not null); CREATE TABLE resources_authorities (authority_id integer NOT null, resource_id integer NOT NULL, FOREIGN KEY (authority_i D) references authorities (ID), FOREIGN KEY (resource_id) references RESOURCES (ID));


The modification consists of two places, one with the if exists behind the drop table, and one that modifies the generated always as identity to auto_increment. And Load-data.sql does not need to be modified.

Then, start MySQL, use the above two SQL files in MySQL to create the database and add initialization data, such as:


Then change the database connection and modify the project's Application.properties file as follows:

#jdbcsettingsjdbc. url=jdbc:mysql://localhost:3306/multidatasourceexample?useunicode=true&characterencoding =utf8jdbc.username=youxiajdbc.password=****** #hibernate settingshibernate.show_sql=falsehibernate.format_sql= Falsehibernate.ehcache_config_file=/ehcache/ehcache-hibernate-local.xml


Modify the project's Applicationcontext.xml file, here to modify two places, one for Driverclassname, one for Hibernate.dilect, as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:jee= "Http://www.springframework.org/schema/jee" xmlns:tx= " Http://www.springframework.org/schema/tx "xmlns:context=" Http://www.springframework.org/schema/context "xsi: Schemalocation= "http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/ Spring-beans-2.5.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-2.5.xsd Http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/ Spring-jee-2.5.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-2.5.xsd "default-lazy-init=" true "> <description> Spring Public Profile </description> <!-- Define variables that are susceptible to environmental impact--<bean class= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > <property name="Systempropertiesmodename" value= "System_properties_mode_override"/> <property name= "IgnoreResourceNotFound "Value=" true "/> <property name=" Locations "> <list> <!--standard configuration--<value> classpath*:/appli Cation.properties </value> <!--Local development environment--<value> classpath*:/application.local.properties </ Value> <!--server production environment configuration-<!--<value>file:/var/myapp/application.server.properties</value> -</list> </property> </bean> <!--automatically registers beans with annotation and guarantees @required, @Autowired attributes are injected--&G  T <context:component-scan base-package= "Personal.youxia"/> <!--data source configuration, using an in-app DBCP database connection pool--<bean id= " DataSource "class=" Org.apache.commons.dbcp.BasicDataSource "destroy-method=" Close "> <!--Connection Info-- > <property name= "driverclassname" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value= "${ Jdbc.url} "/> <property name=" username "value=" ${jdbC.username} "/> <property name=" password "value=" ${jdbc.password} "/> <!--Connection Pooling Info--& Lt;property name= "InitialSize" value= "5"/> <property name= "maxactive" value= ""/> <property name= "maxId Le "value=" "/> <property name=" maxwait "value=" + "/> <property name=" poolpreparedstatements "value=" t  Rue "/> <property name=" Defaultautocommit "value=" false "/> </bean> <!--data source configuration, database connection pool using Application Server-- <!--<jee:jndi-lookup id= "DataSource" jndi-name= "Java:comp/env/jdbc/exampledb"/>-<!--hibernate configuration --<bean id= "Sessionfactory" class= " Org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean "> <property name=" DataSource " ref= "DataSource"/> <property name= "Namingstrategy" > <bean class= " Org.hibernate.cfg.ImprovedNamingStrategy "/> </property> <property name=" Hibernateproperties "> < props> <prop key= "Hibernate.dialect"; Org.hibernate.dialect.MySQL5InnoDBDialect </prop> <prop key= "Hibernate.show_sql" >${hibernate.show_ SQL} </prop> <prop key= "Hibernate.format_sql" >${hibernate.format_sql} </prop> <prop key= " Hibernate.cache.provider_class ">org.hibernate.cache.ehcacheprovider </prop> <prop key="  Hibernate.cache.provider_configuration_file_resource_path ">${hibernate.ehcache_config_file} </prop> </props> </property> <property name= "Packagestoscan" value= "personal.youxia.entity.*"/> </bean > <!--transaction manager configuration, single data source transaction--<bean id= "TransactionManager" class= " Org.springframework.orm.hibernate3.HibernateTransactionManager "> <property name=" sessionfactory "ref=" Sessionfactory "/> </bean> <!--transaction Manager configuration, multi-data source JTA transactions--<!--<bean id=" TransactionManager "class=" or G.springframework.transaction.jta.jtatransactionmanageror Weblogicjtatransactionmanager "/>-<!-- Define transactions with annotation-<Tx:annotation-driven transaction-manager= "TransactionManager"/> </beans> 


Since Springside does not provide the JDBC driver for MySQL, it is necessary to download it to the official MySQL website and copy the downloaded Mysql-connector-5.*.jar to the Lib directory in the project's Web-inf. Then run the project successfully. At this point, the project is successfully migrated to MySQL.

Sixth step, add data table, write entity class, write DAO class, manager class, and do unit test. as an example of the article publishing system mentioned in previous articles, each article corresponds to several comments, so it is necessary to create articles and comments two data tables in the library, as follows:

CREATE table articles (ID int primary key auto_increment,subject varchar () not NULL, content text); CREATE table comments (ID int primary KEY auto_increment,content varchar (255), article_id int not NULL, FOREIGN key (art icle_id) references articles (ID));


Before I write Java code, I have to do a little bit of work, what work? That is to create a separate source folder for my own project, because Src\main\java this folder has been placed in the Jiangnan white in too many package, and because it involves security, so the level is not obvious, operation is not convenient, find code to also not fast enough. Here's what I did after I created my own source folder:

In my own source folder, only four package is created, which represents four levels from bottom to top, so it's much easier to find code.

First, the entity layer, the Article.java code is as follows:

Package personal.youxia.entity; Import Java.util.LinkedHashSet; Import Java.util.Set; Import Javax.persistence.CascadeType; Import javax.persistence.Entity; Import Javax.persistence.JoinColumn; Import Javax.persistence.OneToMany; Import Javax.persistence.OrderBy; Import javax.persistence.Table; Import Org.hibernate.annotations.Cache; Import Org.hibernate.annotations.CacheConcurrencyStrategy; Import Org.hibernate.annotations.Fetch;  Import Org.hibernate.annotations.FetchMode; @Entity//The table name is redefined when the table name differs from the class name.  @Table (name= "articles")//default cache policy. @Cache (usage= cacheconcurrencystrategy.read_write) public class article extends IdEntity {private String subject; privat e String content; Private set<comment> comments=new linkedhashset<comment> (); Public String Getsubject () {return subject;} public void Setsubject (String subject) {this.subject=subject;} public Str ing getcontent () {return content;} public void SetContent (String content) {this.content=content;} @OneToMany (Cascade={Cascadetype.all}) @JoinColumn (name= "article_id")//FECTH policy definition @Fetch (fetchmode.subselect)//collection sorted by ID. The cache of the object ID in the @OrderBy ("id")//collection. @Cache (usage=cacheconcurrencystrategy.read_write) public set<comment> getcomments () {return comments; void Setcomments (set<comment> comments) {this.comments=comments;}}


Comment.java as follows:

Package personal.youxia.entity.entities; Import Javax.persistence.Column; Import javax.persistence.Entity; Import javax.persistence.Table; Import Org.hibernate.annotations.Cache; Import Org.hibernate.annotations.CacheConcurrencyStrategy; Import personal.youxia.entity.IdEntity; @Entity//The table name is redefined when the table name differs from the class name.  @Table (name= "comments")//default cache policy.  @Cache (usage= cacheconcurrencystrategy.read_write) public class Comment extends IdEntity {private String content; privat e Long ArticleID; public string getcontent () {return content,} public void SetContent (String content) {this. content= content;}  @Column (name= "article_id") public Long Getarticleid () {return articleid;} public void Setarticleid (Long ArticleID) {this. articleid= ArticleID;}}


Write the DAO layer code, Articledao.java as follows:

Package Personal.youxia.dao; Import Org.springside.modules.orm.hibernate.HibernateDao; Import personal.youxia.entity.Article; public class Articledao extends Hibernatedao <article, long> {}


Commentdao.java as follows:

Package Personal.youxia.dao; Import Org.springside.modules.orm.hibernate.HibernateDao; Import personal.youxia.entity.Comment; public class Commentdao extends Hibernatedao <comment, long> {}


As you can see, the above code is inherited from Hibernatedao, and thanks to generic support, there is basically no need to write a single line of code.

Write bussiness layer code, this layer, the package name used in white for service, and the suffix of the class name is the manager, I will learn with him, too lazy to change.
Articlemanager.java as follows:

Package personal.youxia.service; Import org.springframework.beans.factory.annotation.Autowired; Import Org.springside.modules.orm.hibernate.HibernateDao; Import Personal.youxia.dao.ArticleDao; Import personal.youxia.entity.Article;  public class Articlemanager extends Entitymanager <article, long> {@Autowired private Articledao Articledao; void Setarticledao (Articledao articledao) {This.articledao=articledao;} @Override protected Hibernatedao<article, Long> Getentitydao () {//TODO auto-generated method stub return Articledao;}}


Commentmanager.java as follows:

Package personal.youxia.service; Import org.springframework.beans.factory.annotation.Autowired; Import Org.springside.modules.orm.hibernate.HibernateDao; Import Personal.youxia.dao.CommentDao; Import personal.youxia.entity.Comment;  public class Commentmanager extends Entitymanager <comment, long> {@Autowired private Commentdao Commentdao; void Setcommentdao (Commentdao commentdao) {This.commentdao=commentdao;} @Override protected Hibernatedao<comment, Long> Getentitydao () {//TODO auto-generated method stub return Commentdao;}}


The above code is similar in that it inherits from Entitymanager and uses the spring IOC feature to inject the DAO class into the manager class and overloads the Getentitydao method to use the injected DAO. At this point, you can write unit tests to verify that the data access-related layers are working correctly. The code is as follows:

package personal.youxia.test; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; Import Org.springside.modules.test.junit4.SpringTxTestCase; Import personal.youxia.entity.entities.Article; Import personal.youxia.entity.entities.Comment; Import Personal.youxia.service.ArticleManager; Import Personal.youxia.service.CommentManager; public class Dataaccesstest extends Springtxtestcase {@Autowired private articlemanager articlemanager; @Autowired Priva Te Commentmanager Commentmanager; public void Setarticlemanager (Articlemanager articlemanager) {This.articlemanager=articlemanager;} @Test public void Addarticle () {Comment comment=new Comment (); Article article=new article (); Article.setsubject ("test"); Article.setcontent ("test"); Articlemanager.save (article); Comment.setarticleid (Article.getid ()); Commentmanager.save (comment); }}


Unit test run, found three problems, first of all the manager class did not inject a successful error, after checking that all the manager class should use the @service annotation , and then the error is that the DAO class did not inject success, after the inspection found All DAO classes are required to use @repository annotations , and the last error is that the entity class cannot be found, and the entity class cannot be located in the Personal.youxia.entity package and must be in its child package . This is determined by the configuration in the Applicationcontext.xml file, and after the change package name is Personal.youxia.entity.entities, the problem is resolved.

The next step should be to write the action and JSP, because the article is too long, editing in the Blogjava editor is very slow, so only the article is divided into the upper and lower three parts. And look at Tell!

The entire process of developing Web projects using Springside 3.1.4.3 (middle)

Java Open Source Framework Springside 3.1.4.3 Development Web Demo Project Combat

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.