首页 > 代码库 > maven之ssh项目搭建

maven之ssh项目搭建

1:新建maven-archetupe-webapp项目

2:web.xml配置文件如下

<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <!-- springmvc 上下文监听器 ContextLoaderListener --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/*.xml</param-value></context-param><!-- springmvc 上下文监听器 ContextLoaderListener--><!-- struts过滤器 --><filter> <filter-name>SSH</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>SSH</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- struts过滤器 --><!-- 过滤器 --><filter><filter-name>encodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 过滤器 --><display-name>spring-ssh</display-name></web-app>

3:struts.xml配置如下

<?xml version="1.0" encoding="UTF-8" ?>  <!DOCTYPE struts PUBLIC      "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"      "http://struts.apache.org/dtds/struts-2.0.dtd">  <struts>        <!-- 请求参数的编码方式-->     <constant name="struts.i18n.encoding" value="UTF-8"/>     <!-- 指定被struts2处理的请求后缀类型。多个用逗号隔开-->     <constant name="struts.action.extension" value="action,do,htm,html"/>     <!-- 当struts.xml改动后,是否重新加载。默认值为false(生产环境下使用),开发阶段最好打开  -->     <constant name="struts.configuration.xml.reload" value="true"/>     <!-- 是否使用struts的开发模式。开发模式会有更多的调试信息。默认值为false(生产环境下使用),开发阶段最好打开  -->     <constant name="struts.devMode" value="false"/>       <!-- 设置浏览器是否缓存静态内容。默认值为true(生产环境下使用),开发阶段最好关闭  -->     <constant name="struts.serve.static.browserCache" value="false" />     <!-- 指定由spring负责action对象的创建      -->     <constant name="struts.objectFactory" value="spring" />         <!--         不用注解模式     <package name="book" namespace="/" extends="struts-default">          <action name="login" class="struts2.LoginAction" method="login">              <result name="success">../views/login.jsp</result>          </action>      </package>       -->    <!-- 是否开启动态方法调用-->     <constant name="struts.enable.DynamicMethodInvocation" value="false"/>  </struts>  

4:spring.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"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:util="http://www.springframework.org/schema/util"    xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:aop="http://www.springframework.org/schema/aop"    xsi:schemaLocation="http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd        http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd        http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.2.xsd        http://www.springframework.org/schema/util         http://www.springframework.org/schema/util/spring-util-3.2.xsd        http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"        default-lazy-init="true">            <mvc:annotation-driven />    <context:component-scan base-package="com.xiaoji.ssh">             <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>             <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>      </context:component-scan>         <context:property-placeholder location="classpath:property/jdbc.properties"/>        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">        <property name="driverClass" value="${database.driverClassName}" />        <property name="jdbcUrl" value="${database.url}" />        <property name="user" value="${database.username}" />        <property name="password" value="${database.password}" />           <!--连接池中保留的最大连接数。默认值: 15 -->           <property name="maxPoolSize" value="20"/>          <!-- 连接池中保留的最小连接数,默认为:3-->          <property name="minPoolSize" value="2"/>          <!-- 初始化连接池中的连接数,取值应在minPoolSize与maxPoolSize之间,默认为3-->          <property name="initialPoolSize" value="2"/>          <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。默认值: 0 -->           <property name="maxIdleTime" value="60"/>        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->            <property name="acquireIncrement" value="2"/>          <!--定义在从数据库获取新连接失败后重复尝试的次数。默认值: 30 ;小于等于0表示无限次-->            <property name="acquireRetryAttempts" value="0"/>           <!--重新尝试的时间间隔,默认为:1000毫秒-->            <property name="acquireRetryDelay" value="1000" />           <!--如果为false,则获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常,但是数据源仍有效保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。默认: false-->            <property name="breakAfterAcquireFailure" value="false"/>      </bean>        <!--定义Hibernate的SessionFactory -->      <!-- SessionFactory使用的数据源为上面的数据源 -->      <!-- 指定了Hibernate的映射文件和配置信息 -->      <bean id="sessionFactory"          class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">          <property name="dataSource" ref="dataSource"/>          <property name="annotatedClasses">               <list>                 <value>com.xiaoji.ssh.entity.Book</value>               </list>          </property>          <property name="annotatedPackages">            <list>                <value>com.xiaoji.ssh.entity</value>            </list>        </property>        <property name="hibernateProperties">              <props>                  <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>                  <prop key="show_sql">true</prop>                  <prop key="hibernate.jdbc.batch_size">20</prop>              </props>          </property>      </bean>        <bean id="transactionManager"          class="org.springframework.orm.hibernate3.HibernateTransactionManager">          <property name="sessionFactory" ref="sessionFactory" />      </bean>    <!--   REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。     SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。     MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。     REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。     NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。     NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。     NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。    -->  <tx:advice id="txAdvice" transaction-manager="transactionManager">        <tx:attributes>            <tx:method name="add*" propagation="REQUIRED" />            <tx:method name="delete*" propagation="REQUIRED" />            <tx:method name="update*" propagation="REQUIRED" />            <tx:method name="save*" propagation="REQUIRED" />            <!-- <tx:method name="*" propagation="true" />-->          </tx:attributes>  </tx:advice>    <aop:config>        <aop:pointcut id="allManagerMethod"            expression="execution(* com.xiaoji.ssh.service.*.*(..))" />        <aop:advisor advice-ref="txAdvice"            pointcut-ref="allManagerMethod" />  </aop:config>    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">      <property name="sessionFactory" ref="sessionFactory" /> </bean>     </beans>    

 

 

5:jdbc.properties代码如下

#c3p0jdbcdatabase.driverClassName=com.mysql.jdbc.Driverdatabase.url=jdbc:mysql://127.0.0.1:3306/springtest?useUnicode=true&characterEncoding=UTF-8database.username=rootdatabase.password=root

 

6:sql建表

CREATE TABLE `book` (  `book_id` int(11) NOT NULL auto_increment,  `name` varchar(50) default NULL,  `description` varchar(100) default NULL,  PRIMARY KEY  (`book_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

7:创建entity,使用hibernate-jpa注解实现数据层

package com.xiaoji.ssh.entity;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import static javax.persistence.GenerationType.IDENTITY;import javax.persistence.Id;import javax.persistence.Table;/** * Book entity. @author MyEclipse Persistence Tools */@Entity@Table(name = "book", catalog = "springtest")public class Book implements java.io.Serializable {    // Fields    private Integer bookId;    private String name;    private String description;    // Constructors    /** default constructor */    public Book() {    }    /** full constructor */    public Book(String name, String description) {        this.name = name;        this.description = description;    }    // Property accessors    @Id    @GeneratedValue(strategy = IDENTITY)    @Column(name = "book_id", unique = true, nullable = false)    public Integer getBookId() {        return this.bookId;    }    public void setBookId(Integer bookId) {        this.bookId = bookId;    }    @Column(name = "name", length = 50)    public String getName() {        return this.name;    }    public void setName(String name) {        this.name = name;    }    @Column(name = "description", length = 100)    public String getDescription() {        return this.description;    }    public void setDescription(String description) {        this.description = description;    }}

 

8:创建dao

接口:

package com.xiaoji.ssh.dao;import java.util.List;import com.xiaoji.ssh.entity.Book;public interface BookDao{    public List<Book> getBookList();        public void saveBook(Book book);        public void deleteBook(int bookId);        public void updateBook(Book book);        public Book getBookByBookId(int bookId);}

 

实现类:

package com.xiaoji.ssh.dao.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.orm.hibernate3.HibernateTemplate;import org.springframework.stereotype.Repository;import com.xiaoji.ssh.dao.BookDao;import com.xiaoji.ssh.entity.Book;@Repositorypublic class BookDaoImpl  implements BookDao {        private HibernateTemplate hibernateTemplate;        public HibernateTemplate getHibernateTemplate() {        return hibernateTemplate;    }    @Autowired    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {        this.hibernateTemplate = hibernateTemplate;    }    public List<Book> getBookList() {        List<Book> list = (List<Book>)getHibernateTemplate().find("From Book");        return list;    }    public void saveBook(Book book) {        getHibernateTemplate().save(book);            }    public void deleteBook(int bookId) {        getHibernateTemplate().delete(getBookByBookId(bookId));            }    public void updateBook(Book book) {        // TODO Auto-generated method stub        getHibernateTemplate().update(book);    }    public Book getBookByBookId(int bookId) {        Book book = (Book)getHibernateTemplate().get(Book.class, bookId);        return book;    }    }

 

9:创建service

接口:

package com.xiaoji.ssh.service;import java.util.List;import com.xiaoji.ssh.entity.Book;public interface BookService {public List<Book> getBookList();        public void saveBook(Book book);        public void deleteBook(int bookId);        public void updateBook(Book book);        public Book getBookByBookId(int bookId);}

 

实现类:

package com.xiaoji.ssh.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.xiaoji.ssh.dao.BookDao;import com.xiaoji.ssh.entity.Book;import com.xiaoji.ssh.service.BookService;@Servicepublic class BookServiceImpl implements BookService{    @Autowired    private BookDao bookDao;    @Override    public List<Book> getBookList() {        return bookDao.getBookList();    }    @Override    public void saveBook(Book book) {        bookDao.saveBook(book);            }    @Override    public void deleteBook(int bookId) {        bookDao.deleteBook(bookId);    }    @Override    public void updateBook(Book book) {        bookDao.updateBook(book);            }    @Override    public Book getBookByBookId(int bookId) {        return bookDao.getBookByBookId(bookId);    }        }

10:action类源码如下

package com.xiaoji.ssh.action;import org.apache.struts2.convention.annotation.Action;import org.apache.struts2.convention.annotation.ExceptionMapping;import org.apache.struts2.convention.annotation.ExceptionMappings;import org.apache.struts2.convention.annotation.Namespace;import org.apache.struts2.convention.annotation.ParentPackage;import org.apache.struts2.convention.annotation.Result;import org.apache.struts2.convention.annotation.Results;import com.opensymphony.xwork2.ActionSupport;/**  * Struts2基于注解的Action配置 *  ParentPackage 继承父包 *  Namespace命名空间 *  Results跳转页面 *  Action访问方法 */   @ParentPackage("struts-default") @Namespace("/book") @Results( { @Result(name = "success", location = "/views/main.jsp"),         @Result(name = "error", location = "/views/error.jsp") }) @ExceptionMappings( { @ExceptionMapping(exception = "java.lange.RuntimeException", result = "error") }) public class BookAction extends ActionSupport{    private String username;            public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    @Action(value="test")    public String test(){        this.setUsername("strutsTest");        return SUCCESS;    }            @Action(value = "bookView", results = { @Result(name = "success", location = "/index.jsp") })      public String bookView(){        return SUCCESS;    }}

11:pom.xml源码

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>com.xiaoji.ssh</groupId>  <artifactId>spring-ssh</artifactId>  <packaging>war</packaging>  <version>0.0.1-SNAPSHOT</version>  <name>spring-ssh Maven Webapp</name>  <url>http://maven.apache.org</url>     <properties>      <spring.version>3.2.8.RELEASE</spring.version>          <jdk.version>1.6</jdk.version>      <hibernate.version>3.5.4-Final</hibernate.version>  </properties>    <dependencies>      <!-- spring -->     <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-context</artifactId>        <version>${spring.version}</version>     </dependency>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-test</artifactId>        <version>${spring.version}</version>    </dependency>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-web</artifactId>        <version>${spring.version}</version>    </dependency>        <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-webmvc</artifactId>        <version>${spring.version}</version>    </dependency>    <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-tx</artifactId>        <version>${spring.version}</version>    </dependency>    <dependency>        <groupId>org.aspectj</groupId>        <artifactId>aspectjweaver</artifactId>        <version>1.7.4</version>    </dependency>     <!-- spring -->     <!-- hibernate -->     <dependency>        <groupId>org.hibernate</groupId>        <artifactId>hibernate-core</artifactId>        <version>3.5.4-Final</version>    </dependency>     <dependency>        <groupId>org.hibernate.javax.persistence</groupId>        <artifactId>hibernate-jpa-2.1-api</artifactId>        <version>1.0.0.Final</version>    </dependency>    <dependency>    <groupId>springframework</groupId>    <artifactId>spring-hibernate</artifactId>    <version>1.2.6</version></dependency><dependency>    <groupId>org.hibernate</groupId>    <artifactId>hibernate-annotations</artifactId>    <version>3.5.4-Final</version></dependency>     <!-- 连接池包 -->  <dependency>    <groupId>c3p0</groupId>    <artifactId>c3p0</artifactId>    <version>0.9.1.2</version>    </dependency><!-- 链接池包 -->    <!--hibernate  -->    <!--struts  -->    <dependency>        <groupId>org.apache.struts</groupId>        <artifactId>struts2-core</artifactId>        <version>2.3.16</version>    </dependency>    <dependency>        <groupId>org.apache.struts</groupId>        <artifactId>struts2-spring-plugin</artifactId>        <version>2.3.16</version>    </dependency>    <dependency>        <groupId>org.apache.struts</groupId>        <artifactId>struts2-convention-plugin</artifactId>        <version>2.3.16</version>    </dependency>    <dependency>              <groupId>javassist</groupId>              <artifactId>javassist</artifactId>              <version>3.12.1.GA</version>      </dependency>    <dependency>         <groupId>com.sun</groupId>        <artifactId>tools</artifactId>        <version>1.5.0</version>    </dependency>    <!--struts  -->    <!-- jsp  servlet -->   <dependency>        <groupId>org.apache.tomcat</groupId>        <artifactId>jsp-api</artifactId>        <version>6.0.41</version>    </dependency>  <!-- jsp  servlet -->     <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.11</version>      <scope>test</scope>    </dependency>    <dependency>    <groupId>org.slf4j</groupId>    <artifactId>slf4j-api</artifactId>    <version>1.7.5</version></dependency>  <!-- mysql -->    <dependency>        <groupId>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>        <version>5.1.30</version>    </dependency>  <!-- mysql -->  </dependencies>  <build>      <plugins>          <plugin>            <groupId>org.apache.maven.plugins</groupId>            <artifactId>maven-compiler-plugin</artifactId>            <version>3.1</version>            <configuration>              <source>${jdk.version}</source>              <target>${jdk.version}</target>            </configuration>          </plugin>      </plugins>  </build></project>

 

12:忘记了还有个测试类

package com.xiaoji.ssh.dao;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.xiaoji.ssh.entity.Book;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"classpath:spring/*.xml" })  public class BookDaoTest {    @Autowired    private BookDao bookDao;        @Test    public void testGetBookList(){        System.out.println("xiaoji");    }        @Test    public void testSaveBookList(){        System.out.println(bookDao.getBookList());    }    @Test    public void testUpdateBookList(){        Book book = new Book();        book.setName("ssh3");        book.setDescription("ssh3");        bookDao.saveBook(book);        System.out.println("ok");    }}

 

注解:在src/main/webapp下面建立个view目录,并新建main.jsp和error.jsp.如果觉的此文对你有帮助,请回复一下鼓励下我,以后我会发布更多类似文章。

下面贴上目录结构图:

 

源码下载地址

http://files.cnblogs.com/520liping/spring-ssh.zip