想试试AOP在spring的web项目上的使用情况,所以想尽快使用idea快速的搭建一个spring的web项目,当然,是maven管理的项目
步骤如下:
1。打开idea 左上角file--->new --->project
2。选择Maven项目
好了,生成出来是下面这个狗样子
3.好了,新建web相关目录
建完把webapp目录设置成web的根目录,并且将web生成的web.xml文件放在WEB-INF位置下,往下看,操作就行
完了就是下面的狗样子
4.完善pom.xml文件
如果你是用的默认的maven本地仓库,也就是在本地的C:Users自己PC的用户名.m2下的仓库的话,就不用更改什么,直接完善pom.xml文件。
如果你使用了自定义的maven仓库,那需要先设置一下本项目所作用的maven的setting.xml文件。
然后完善pom.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.sxd</groupId> <artifactId>aopExample</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.1.4.RELEASE</spring.version> <hibernate.version>4.3.8.Final</hibernate.version> <jackson.version>2.5.0</jackson.version> </properties> <dependencies> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</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-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <!-- 使用SpringMVC需配置 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- spring cglib 代理 --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency> <!-- 关系型数据库整合时需配置 如hibernate jpa等 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <!-- hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernate.version}</version> </dependency> <!-- 二级缓存ehcache --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.9.0</version> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- mysql连接 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <!-- c3p0数据源 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5-pre10</version> </dependency> <!-- json --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- aop --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.4</version> </dependency> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> </project>
5.接下来,是各个配置文件的配置,之前有在myecplise上配置过,配置是一样的
可以参考:【http://www.cnblogs.com/sxdcgaq8080/p/5606827.html】
再resources目录下,分别创建如下文件:
config.properties
#jdbc c3p0 config jdbc.driver = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/orderdiscount?useUnicode=true&characterEncoding=utf-8 jdbc.username = root jdbc.password = root #hibernate config hibernate.dialect = org.hibernate.dialect.MySQLDialect hibernate.show_sql = true hibernate.format_sql = false hibernate.hbm2ddl.auto = update hibernate.cache.use_second_level_cache = true hibernate.cache.use_query_cache = true hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory hibernate.cache.provider_configuration_file_resource_path =ehcache.xml
log4j.properties
### set log levels ###
log4j.rootLogger = INFO , C , D , E
### console ###
log4j.appender.C = org.apache.log4j.ConsoleAppender
log4j.appender.C.Target = System.out
log4j.appender.C.layout = org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern = [aopExample][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
### log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ../logs/springmvc_hibernate_demo.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = [aopExample][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
### exception ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = ../logs/aopExample_error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern =[aopExample][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
spring-hibernate.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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd "> <!-- 自动扫描@Controller注入为bean --> <context:property-placeholder location="classpath:config.properties"/> <!-- 配置数据源 c3p0 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 请求超时时间 --> <property name="checkoutTimeout" value="30000" /> <!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 --> <property name="idleConnectionTestPeriod" value="30" /> <!-- 连接数据库连接池最大空闲时间 --> <property name="maxIdleTime" value="30" /> <!-- 连接池初始化连接数 --> <property name="initialPoolSize" value="5" /> <property name="minPoolSize" value="5" /> <property name="maxPoolSize" value="20" /> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 --> <property name="acquireIncrement" value="5" /> </bean> <!-- 配置hibernate的SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 注入数据源 相关信息看源码 --> <property name="dataSource" ref="dataSource" /> <!-- hibernate配置信息 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!-- 开启二级缓存 ehcache --> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path} </prop> </props> </property> <!-- 扫描hibernate注解配置的entity --> <property name="packagesToScan" value="com.sxd.entity" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"> <diskStore path="D:/ehcache" /> <!-- DefaultCache setting. --> <defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="1000000" overflowToDisk="true" memoryStoreEvictionPolicy="LRU"> </defaultCache> <!-- Special objects setting. --> <cache name="org.andy.work.entity.AcctUser" maxElementsInMemory="2" memoryStoreEvictionPolicy="LRU" eternal="true" diskPersistent="false" overflowToDisk="false" maxElementsOnDisk="1000000" /> </ehcache>
spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- 自动扫描@Controller注入为bean --> <context:component-scan base-package="com.sxd" > </context:component-scan> <!-- 标明注解事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 以下为SpringMVC配置 --> <mvc:annotation-driven> <!-- 返回json数据,@response使用 --> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/views" /> <property name="suffix" value=".jsp" /> </bean> <!--Spring aop事务管理 <aop:config proxy-target-class="true"> 配置切入点 指定这个aop:pointcut去引用上面规定的advice,也就是说规定下面的这个expression指定的路径下的service.impl下的所有的方法,都按照上面advice中的规定去执行,碰上什么操作,事务就是什么类型的,这就是事务管理器的好处了 解释一下,为什么这个要指定在service层:因为在同一个事务中,可能要对多张表进行多个不同的操作,才是一个完整的逻辑,例如淘宝上买东西,你转账之后你的钱减少了,对方的钱应该增加了,这两个操作在一起才是一个完整的操作,而如果这两个操作不在一个事务中,也就是如果将事务的操作指定在Dao层【MVC的设计模式:Dao层就是对数据库进行最简单的增删改查操作,而service层是进行逻辑处理的,一个完整的逻辑处理就要涉及到多次操作】事务操作失败,发生回滚,那你的帐减少了,对方的帐并没有增加,这样就不美丽的,因此,将事务的管理,指定在了service层 <aop:pointcut id="transactionPointcut" expression="execution(* com.it.service..*Impl.*(..))" />expression中表达式所指意思: 所有的文件下的 com.it.service开头的包,以Impl结尾的类下的所有的方法,都执行上面advice的规定 指定在txAdvice切入点应用txAdvice事务增强处理 <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> --> </beans>
6.完善java中的包controller,并建立一个页面跳转MainController.java
MainController.java
package com.sxd.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class MainController { @ResponseBody @RequestMapping("do") public String doSomething(){ return "Just for what"; } }
7.最恶心的一步,也是不同与ecplise的步骤,为本项目部署一个Tomcat
选上自己的项目即可
8.最后一步,完善web.xml文件
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!-- web容器是web项目的大脑 --> <!-- 在web.xml中,执行顺序是:1.先执行listener 2。再执行filter 3.最后执行servlet 这就是执行顺序 就像spring-hibernate.xml文件是在执行Listener的时候加载的,那注意这几个配置文件在web.xml中的加载顺序,因为资源文件是在配置文件【xml文件】中加载的,肯定是先加载的资源文件【properties文件】,才能在配置文件中调用资源文件中的变量的值使用 --> <display-name>aopExample</display-name> <!-- web容器,首先需要引入spring,让spring管理各个框架,并将其注入为bean --> <!-- 这个相当于定一个 变量在web.xml中,在下面的listener org.springframework.web.context.ContextLoaderListener中,加载这个spring-hibernate.xml文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-hibernate.xml</param-value> </context-param> <!-- 配置控制层的filter信息 --> <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- openSessionInView配置 作用是延迟session关闭到view层 --> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <!-- 监听servletContext,启动contextConfigLocation中的spring配置信息 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止spring内存溢出监听器 可用可不用--> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- 类似与servlet 需要在web.xml中都需要配置一样,spring的思想是让这些servlet【controller也是servlet】继承了一个基础的servlet,那就只需在web.xml中配置一个servlet即可。 --> <!-- 这个servlet和下面的servlet-mapping相配合使用,注明了所有的以.htmls结尾的请求都被截取到,去到servlet中去找相对应的方法 进行处理 --> <servlet> <description>spring mvc servlet</description> <servlet-name>rest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!-- 此处配置的是SpringMVC的配置文件 --> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 配置了springmvc拦截的url为以.hmls结尾的请求 --> <servlet-mapping> <servlet-name>rest</servlet-name> <url-pattern>*.htmls</url-pattern> </servlet-mapping> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置session超时时间,单位分钟 --> <session-config> <session-timeout>30</session-timeout> </session-config> <!-- 欢迎界面 默认的项目访问界面 --> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
9.最后,就可以启动了,启动完成之后,浏览器访问地址:
========================================================================================
好啦!!!