ssm整合开发的相关步骤和增删改查
一、环境搭建
我的目录是:
1)创建一个maven web项目,并配置对应的依赖;
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.seecen</groupId> <artifactId>ssm</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ssm Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <!--properties中配置版本信息--> <properties> <!--编码格式--> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!--编译版本--> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <junit.version>4.12</junit.version> <spring.version>5.0.3.RELEASE</spring.version> <druid.version>1.1.2</druid.version> <jstl.version>1.2</jstl.version> <servlet-api.version>4.0.0</servlet-api.version> <jsp-api.version>2.3.1</jsp-api.version> <commons-fileupload.version>1.3.3</commons-fileupload.version> <ehcache.version>2.10.4</ehcache.version> <oracle.version>11.2.0.3.0</oracle.version> <slf4j.version>1.7.25</slf4j.version> <mybatis.version>3.4.5</mybatis.version> <pagehelper.version>5.1.4</pagehelper.version> <mybatis-ehcache.version>1.0.0</mybatis-ehcache.version> <mybatis-generator-core.version>1.3.5</mybatis-generator-core.version> <maven-plugin-api.version>3.5.0</maven-plugin-api.version> <mybatis.spring.version>1.3.1</mybatis.spring.version> <jackson.version>2.9.0</jackson.version> <shiro.version>1.4.0</shiro.version> </properties> <dependencies> <!--org.aspectj aop注解--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.13</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.10</version> </dependency> <!-- 缓存 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>${ehcache.version}</version> </dependency> <!-- oracle --> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>${oracle.version}</version> </dependency> <!-- JSP相关 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet-api.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>${jsp-api.version}</version> <scope>provided</scope> </dependency> <!-- 文件上传组件 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <!--单元测试jar--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!--spring mvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring web依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring整合ORM框架依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <!--spring websocket 模块--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>${spring.version}</version> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- 日志处理 log4j--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- Mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-ehcache</artifactId> <version>${mybatis-ehcache.version}</version> </dependency> <!--mybatis spring 集成jar--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!-- mybatis反向建模 --> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-plugin-api</artifactId> <version>${maven-plugin-api.version}</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>${mybatis-generator-core.version}</version> </dependency> <!--json处理--> <!--实际上为三个包,但是导入databind会自动导入其他两个包--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!--mybatis分页插件--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>${pagehelper.version}</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.2.12</version> </dependency> <!-- Shiro权限管理 --> <!-- <dependency>--> <!-- <groupId>org.apache.shiro</groupId>--> <!-- <artifactId>shiro-web</artifactId>--> <!-- <version>${shiro.version}</version>--> <!-- </dependency>--> <!-- <dependency>--> <!-- <groupId>org.apache.shiro</groupId>--> <!-- <artifactId>shiro-spring</artifactId>--> <!-- <version>${shiro.version}</version>--> <!-- </dependency>--> <!-- <dependency>--> <!-- <groupId>org.apache.shiro</groupId>--> <!-- <artifactId>shiro-ehcache</artifactId>--> <!-- <version>${shiro.version}</version>--> <!-- </dependency>--> <!-- <dependency>--> <!-- <groupId>org.apache.shiro</groupId>--> <!-- <artifactId>shiro-quartz</artifactId>--> <!-- <version>${shiro.version}</version>--> <!-- </dependency>--> <!-- <dependency>--> <!-- <groupId>org.codehaus.jackson</groupId>--> <!-- <artifactId>jackson-mapper-asl</artifactId>--> <!-- <version>1.9.13</version>--> <!-- </dependency>--> </dependencies> <build> <finalName>ssm</finalName> <plugins> <!--mybatis代码生成插件--> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> <resources> <resource> <!-- 配置打war时候的要打的文件路径 --> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>*.properties</include> <include>*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build> </project>
二、
1)Web.xml中配置springmvc的前端控制器,spring的监听器,spring编码过滤器;
web.xml文件为:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>ssm</display-name> <!--编码过滤器--> <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> <!--log4j 日志配置--> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath*:log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!--配置spring--> <!--指定spring的配置文件路径--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext*.xml</param-value> </context-param> <!-- 配置spring监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置shiro--> <!--<filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <!–配置shiro过滤器的bean的名称–> <param-name>targetBeanName</param-name> <param-value>shiroFilter</param-value> </init-param> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>--> <!--springmvc--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
2)配置spring,springmvc,mybatis配置文件
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" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--设置扫描包,扫描对应包下的注解--> <context:component-scan base-package="mapper,service"> </context:component-scan> <!-- 配置数据库连接池 此处使用阿里的druid连接池,功能强大,性能优秀 c3p0 也是一种连接池,以前项目用的比较多。 数据库连接池的作用: --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close" > <!--${url}为引用jdbc.properties中的url配置--> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property> <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property> <property name="username" value="sc2001"></property> <property name="password" value="sun"></property> <!--初始连接大小--> <property name="initialSize" value="5"></property> <!--最小连接数,连接池至少需要保持的连接数--> <property name="minIdle" value="5"></property> <!--最大连接数--> <property name="maxActive" value="20"></property> <!--配置最大等待时间--> <property name="maxWait" value="60000"></property> <!--最大空闲时间--> <property name="minEvictableIdleTimeMillis" value="300000"/> <!--连接空闲时间超过最大空闲时间时,执行validationQuery验证连接是否可用--> <property name="testWhileIdle" value="true"></property> <!--验证连接是否可用--> <property name="validationQuery" value="select 1 from dual"/> </bean> <!--整合mybatis--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--注入数据源--> <property name="dataSource" ref="dataSource"></property> <!--指定mybatis主配置文件路径--> <property name="configLocation" value="classpath:mybatis.xml"/> <!--指定mapper.xml文件路径--> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> </bean> <!-- 整合mybatis 配置dao层接口,交由spring创建对象--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--指定mybatis dao层接口目录--> <property name="basePackage" value="mapper"/> <!--注入sqlsessionFactory--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--配置datasource--> <property name="dataSource" ref="dataSource"/> </bean> <!--配置事务传播特性和 事务隔离级别--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!--配置事务传播特性 method为方法名, propagation配置事务传播特性 isolation="" 指定事务隔离级别--> <!-- name:指定切入点的方法名,匹配的方法才能够指定到事务传播特性和隔离级别--> <tx:method name="save*" propagation="REQUIRED" isolation="READ_COMMITTED" /> <tx:method name="insert*" propagation="REQUIRED" isolation="SERIALIZABLE"/> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <!--查询操作 配置read-only=true,标识为只读事务。--> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="select*" propagation="REQUIRED" read-only="true" /> </tx:attributes> </tx:advice> <!--aop配置事务--> <aop:config> <!--切入点,将事务切入到service层方法--> <aop:pointcut id="pointcut" expression="execution(* service.*.*(..))"/> <!--<aop:advisor>配置事务切面--> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/> </aop:config> <!-- <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy> --> </beans>
a. Spring配置文件
1) 配置扫描包
2)配置dataSource 数据源
3)配置mybatis的sqlSessionFactory
4) 配置mybatisMapper接口扫描
5)事务管理器
6)配置事务传播特性和事务隔离级别
7)配置事务AOP
log4j.properties文件(日志文件)为:
#生产环境使用info #log4j.rootLogger = info,stdout,logfile #开发环境使用debug log4j.rootLogger = info,stdout,logfile log4j.logger.com.seecen.system.aop.advice = trace,aop log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %p [%C].%M(%L) --> %m%n log4j.appender.logfile = org.apache.log4j.DailyRollingFileAppender log4j.appender.logfile.Threshold = ERROR log4j.appender.logfile.DatePattern='.'yyyy-MM-dd log4j.appender.logfile.File = D:/ssmlogfile.log log4j.appender.logfile.layout = org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %p [%C].%M(%L) --> %m%n log4j.appender.logfile.Append=true log4j.appender.aop = org.apache.log4j.DailyRollingFileAppender log4j.appender.aop.File = D:/ssmlogfileAOP.log log4j.appender.aop.layout = org.apache.log4j.PatternLayout log4j.appender.aop.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} %m%n log4j.appender.aop.Append=true
log4j配置说明.properties文件为:
################################################################################ #①配置根Logger,其语法为: # #log4j.rootLogger = [level],appenderName,appenderName2,... #level是日志记录的优先级,分为OFF,TRACE,DEBUG,INFO,WARN,ERROR,FATAL,ALL ##Log4j建议只使用四个级别,优先级从低到高分别是DEBUG,INFO,WARN,ERROR #通过在这里定义的级别,您可以控制到应用程序中相应级别的日志信息的开关 #比如在这里定义了INFO级别,则应用程序中所有DEBUG级别的日志信息将不被打印出来 #appenderName就是指定日志信息输出到哪个地方。可同时指定多个输出目的 ################################################################################ ################################################################################ #②配置日志信息输出目的地Appender,其语法为: # #log4j.appender.appenderName = fully.qualified.name.of.appender.class #log4j.appender.appenderName.optionN = valueN # #Log4j提供的appender有以下几种: #1)org.apache.log4j.ConsoleAppender(输出到控制台) #2)org.apache.log4j.FileAppender(输出到文件) #3)org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件) #4)org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件) #5)org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方) # #1)ConsoleAppender选项属性 # -Threshold = DEBUG:指定日志消息的输出最低层次 # -ImmediateFlush = TRUE:默认值是true,所有的消息都会被立即输出 # -Target = System.err:默认值System.out,输出到控制台(err为红色,out为黑色) # #2)FileAppender选项属性 # -Threshold = INFO:指定日志消息的输出最低层次 # -ImmediateFlush = TRUE:默认值是true,所有的消息都会被立即输出 # -File = C:\log4j.log:指定消息输出到C:\log4j.log文件 # -Append = FALSE:默认值true,将消息追加到指定文件中,false指将消息覆盖指定的文件内容 # -Encoding = UTF-8:可以指定文件编码格式 # #3)DailyRollingFileAppender选项属性 # -Threshold = WARN:指定日志消息的输出最低层次 # -ImmediateFlush = TRUE:默认值是true,所有的消息都会被立即输出 # -File = C:\log4j.log:指定消息输出到C:\log4j.log文件 # -Append = FALSE:默认值true,将消息追加到指定文件中,false指将消息覆盖指定的文件内容 # -DatePattern='.'yyyy-ww:每周滚动一次文件,即每周产生一个新的文件。还可以按用以下参数: # '.'yyyy-MM:每月 # '.'yyyy-ww:每周 # '.'yyyy-MM-dd:每天 # '.'yyyy-MM-dd-a:每天两次 # '.'yyyy-MM-dd-HH:每小时 # '.'yyyy-MM-dd-HH-mm:每分钟 # -Encoding = UTF-8:可以指定文件编码格式 # #4)RollingFileAppender选项属性 # -Threshold = ERROR:指定日志消息的输出最低层次 # -ImmediateFlush = TRUE:默认值是true,所有的消息都会被立即输出 # -File = C:/log4j.log:指定消息输出到C:/log4j.log文件 # -Append = FALSE:默认值true,将消息追加到指定文件中,false指将消息覆盖指定的文件内容 # -MaxFileSize = 100KB:后缀可以是KB,MB,GB.在日志文件到达该大小时,将会自动滚动.如:log4j.log.1 # -MaxBackupIndex = 2:指定可以产生的滚动文件的最大数 # -Encoding = UTF-8:可以指定文件编码格式 ################################################################################ ################################################################################ #③配置日志信息的格式(布局),其语法为: # #log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class #log4j.appender.appenderName.layout.optionN = valueN # #Log4j提供的layout有以下几种: #5)org.apache.log4j.HTMLLayout(以HTML表格形式布局) #6)org.apache.log4j.PatternLayout(可以灵活地指定布局模式) #7)org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串) #8)org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息) #9)org.apache.log4j.xml.XMLLayout(以XML形式布局) # #5)HTMLLayout选项属性 # -LocationInfo = TRUE:默认值false,输出java文件名称和行号 # -Title=Struts Log Message:默认值 Log4J Log Messages # #6)PatternLayout选项属性 # -ConversionPattern = %m%n:格式化指定的消息(参数意思下面有) # #9)XMLLayout选项属性 # -LocationInfo = TRUE:默认值false,输出java文件名称和行号 # #Log4J采用类似C语言中的printf函数的打印格式格式化日志信息,打印参数如下: # %m 输出代码中指定的消息 # %p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL # %r 输出自应用启动到输出该log信息耗费的毫秒数 # %c 输出所属的类目,通常就是所在类的全名 # %t 输出产生该日志事件的线程名 # %n 输出一个回车换行符,Windows平台为“\r\n”,Unix平台为“\n” # %d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式 # 如:%d{yyyy年MM月dd日 HH:mm:ss,SSS},输出类似:2012年01月05日 22:10:28,921 # %l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数 # 如:Testlog.main(TestLog.java:10) # %F 输出日志消息产生时所在的文件名称 # %L 输出代码中的行号 # %x 输出和当前线程相关联的NDC(嵌套诊断环境),像java servlets多客户多线程的应用中 # %% 输出一个"%"字符 # # 可以在%与模式字符之间加上修饰符来控制其最小宽度、最大宽度、和文本的对齐方式。如: # %5c: 输出category名称,最小宽度是5,category<5,默认的情况下右对齐 # %-5c:输出category名称,最小宽度是5,category<5,"-"号指定左对齐,会有空格 # %.5c:输出category名称,最大宽度是5,category>5,就会将左边多出的字符截掉,<5不会有空格 # %20.30c:category名称<20补空格,并且右对齐,>30字符,就从左边交远销出的字符截掉 ################################################################################ ################################################################################ #④指定特定包的输出特定的级别 #log4j.logger.org.springframework=DEBUG ################################################################################ #OFF,systemOut,logFile,logDailyFile,logRollingFile,logMail,logDB,ALL log4j.rootLogger =ALL,systemOut,logFile,logDailyFile,logRollingFile,logMail,logDB #输出到控制台 log4j.appender.systemOut = org.apache.log4j.ConsoleAppender log4j.appender.systemOut.layout = org.apache.log4j.PatternLayout log4j.appender.systemOut.layout.ConversionPattern = [%-5p][%-22d{yyyy/MM/dd HH:mm:ssS}][%l]%n%m%n log4j.appender.systemOut.Threshold = DEBUG log4j.appender.systemOut.ImmediateFlush = TRUE log4j.appender.systemOut.Target = System.out #输出到文件 log4j.appender.logFile = org.apache.log4j.FileAppender log4j.appender.logFile.layout = org.apache.log4j.PatternLayout log4j.appender.logFile.layout.ConversionPattern = [%-5p][%-22d{yyyy/MM/dd HH:mm:ssS}][%l]%n%m%n log4j.appender.logFile.Threshold = DEBUG log4j.appender.logFile.ImmediateFlush = TRUE log4j.appender.logFile.Append = TRUE log4j.appender.logFile.File = ../Struts2/WebRoot/log/File/log4j_Struts.log log4j.appender.logFile.Encoding = UTF-8 #按DatePattern输出到文件 log4j.appender.logDailyFile = org.apache.log4j.DailyRollingFileAppender log4j.appender.logDailyFile.layout = org.apache.log4j.PatternLayout log4j.appender.logDailyFile.layout.ConversionPattern = [%-5p][%-22d{yyyy/MM/dd HH:mm:ssS}][%l]%n%m%n log4j.appender.logDailyFile.Threshold = DEBUG log4j.appender.logDailyFile.ImmediateFlush = TRUE log4j.appender.logDailyFile.Append = TRUE log4j.appender.logDailyFile.File = ../Struts2/WebRoot/log/DailyFile/log4j_Struts log4j.appender.logDailyFile.DatePattern = '.'yyyy-MM-dd-HH-mm'.log' log4j.appender.logDailyFile.Encoding = UTF-8 #设定文件大小输出到文件 log4j.appender.logRollingFile = org.apache.log4j.RollingFileAppender log4j.appender.logRollingFile.layout = org.apache.log4j.PatternLayout log4j.appender.logRollingFile.layout.ConversionPattern = [%-5p][%-22d{yyyy/MM/dd HH:mm:ssS}][%l]%n%m%n log4j.appender.logRollingFile.Threshold = DEBUG log4j.appender.logRollingFile.ImmediateFlush = TRUE log4j.appender.logRollingFile.Append = TRUE log4j.appender.logRollingFile.File = ../Struts2/WebRoot/log/RollingFile/log4j_Struts.log log4j.appender.logRollingFile.MaxFileSize = 1MB log4j.appender.logRollingFile.MaxBackupIndex = 10 log4j.appender.logRollingFile.Encoding = UTF-8 #用Email发送日志 log4j.appender.logMail = org.apache.log4j.net.SMTPAppender log4j.appender.logMail.layout = org.apache.log4j.HTMLLayout log4j.appender.logMail.layout.LocationInfo = TRUE log4j.appender.logMail.layout.Title = Struts2 Mail LogFile log4j.appender.logMail.Threshold = DEBUG log4j.appender.logMail.SMTPDebug = FALSE log4j.appender.logMail.SMTPHost = SMTP.163.com log4j.appender.logMail.From = xly3000@163.com log4j.appender.logMail.To = xly3000@gmail.com #log4j.appender.logMail.Cc = xly3000@gmail.com #log4j.appender.logMail.Bcc = xly3000@gmail.com log4j.appender.logMail.SMTPUsername = xly3000 log4j.appender.logMail.SMTPPassword = 1234567 log4j.appender.logMail.Subject = Log4j Log Messages #log4j.appender.logMail.BufferSize = 1024 #log4j.appender.logMail.SMTPAuth = TRUE #将日志登录到MySQL数据库 log4j.appender.logDB = org.apache.log4j.jdbc.JDBCAppender log4j.appender.logDB.layout = org.apache.log4j.PatternLayout log4j.appender.logDB.Driver = com.mysql.jdbc.Driver log4j.appender.logDB.URL = jdbc:mysql://127.0.0.1:3306/xly log4j.appender.logDB.User = root log4j.appender.logDB.Password = 123456 log4j.appender.logDB.Sql = INSERT INTOT_log4j(project_name,create_date,level,category,file_name,thread_name,line,all_category,message)values('Struts2','%d{yyyy-MM-ddHH:mm:ss}','%p','%c','%F','%t','%L','%l','%m')
mybatis.xml文件为:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!--配置日志实现--> <setting name="logImpl" value="STDOUT_LOGGING" /> <!--一级缓存二级缓存--> <!--开启二级缓存--> <setting name="cacheEnabled" value="true"/> </settings> <!--mybatis分页插件--> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!--pageSize=0时,是否查询出全部结果,默认为false--> <property name="pageSizeZero" value="true" /> <!--分页合理化参数,默认文false;pageNum<=0,查询第一页;pageNum>总页数,查询最后一页--> <property name="reasonable" value="true" /> <property name="params" value="pageNum=pageHelperStart;pageSize=pageHelperRows;" /> <property name="supportMethodsArguments" value="false" /> <property name="returnPageInfo" value="none" /> </plugin> </plugins> </configuration>
springmvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--开启注解驱动--> <mvc:annotation-driven></mvc:annotation-driven> <!--配置扫描包--> <context:component-scan base-package="controller"/> <!--配置视图解析器--> <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">--> <!--<!–配置视图的前缀–>--> <!--<property name="prefix" value="/WEB-INF/pages" />--> <!--<!–配置视图后缀–>--> <!--<property name="suffix" value=".jsp" />--> <!--</bean>--> <!--配置文件上传--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--设置文件编码格式--> <property name="defaultEncoding" value="UTF-8"/> <!--设置最大上传大小--> <property name="maxUploadSize" value="10240000" /> </bean> <!--开启默认servlet,用以处理静态资源文件--> <mvc:default-servlet-handler/> <!--配置注解式AOP支持--> <!-- <aop:aspectj-autoproxy ></aop:aspectj-autoproxy> <aop:aspectj-autoproxy proxy-target-class="true"/>--> <!-- <!–设置启用shiro注解–> <aop:config proxy-target-class="true"></aop:config> <!–配置shiro 权限拦截器–> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"></property> </bean>--> <!-- <!–配置springmvc异常处理机制–> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <!–异常映射规则–> <property name="exceptionMappings"> <props > <!–key指定异常类–> <prop key="org.apache.shiro.authz.UnauthorizedException"> nopermission.jsp </prop> </props> </property> </bean>--> </beans>
三、 写Cotroller service dao 页面,进行增删改查操作;
ClassService.java文件为:
package service; import entity.Class; import java.util.List; import java.util.Map; public interface ClassService { //查询所有数据 List<Class> findByMap(Map<String,Object> map); //删除数据 int delete(Integer id); //通过id查找数据 Class selectById(Integer id); //修改数据,增加数据 int saveOrUpdate(Class classes); }
ClassServiceImpl.java文件为:
package service; import entity.Class; import jdk.internal.dynalink.support.ClassMap; import mapper.ClassMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public class ClassServiceImpl implements ClassService{ @Autowired private ClassMapper classMapper; @Override public List<Class> findByMap(Map<String, Object> map) { List<Class> classes=classMapper.selectByMap(map); return classes; } @Override public int delete(Integer id) { int i=classMapper.delete(id); return i; } @Override public Class selectById(Integer id) { Class classes=classMapper.selectById(id); return classes; } @Override public int saveOrUpdate(Class classes) {
//通过判断是否存在id,如果存在id,则进行修改操作,不存在id,则进行增加操作; if (null==classes.getId()){ return classMapper.insert(classes); } return classMapper.update(classes); } }
ClassMapper.java文件为:
package mapper; import entity.Class; import java.util.List; import java.util.Map; public interface ClassMapper { List<Class> selectByMap(Map<String, Object> map); int delete(Integer id); Class selectById(Integer id); int insert(Class classes); int update(Class classes); }
ClassMapper.xml文件为:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="mapper.ClassMapper"> <insert id="insert"> insert into h_class (id,name,city) values (seq_t_class.nextval,#{name},#{city}) </insert> <update id="update" parameterType="entity.Class"> update h_class set name =#{name},city=#{city} where id=#{id} </update> <delete id="delete"> delete from h_class where id=#{id} </delete> <select id="selectByMap" resultType="entity.Class"> select * from h_class <where> <if test="name!=null and name!=''"> <bind name="nameLike" value="'%'+name+'%'"></bind> name like #{nameLike} </if> <if test="city!=null and city!=''"> and city=#{city} </if> </where> </select> <select id="selectById" resultType="entity.Class"> select * from h_class where id=#{id} </select> </mapper>
list.jsp文件为:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>用户列表页面</title> </head> <body> <form action="${pageContext.request.contextPath}/user/list"> 名字:<input type="text" name="name"/><br/> 城市:<input type="text" name="city"/><br/> <input type="submit" value="查找"/> </form> <a href="${pageContext.request.contextPath}/user/toadd">新增</a> <table border="1px"> <thead> <tr> <td>ID</td> <td>名字</td> <td>城市</td> <td>操作</td> </tr> </thead> <tbody> <c:forEach var="classe" items="${classes}"> <tr> <td>${classe.id}</td> <td>${classe.name}</td> <td>${classe.city}</td> <td> <a href="${pageContext.request.contextPath}/user/delete?id=${classe.id}">删除</a> <a href="${pageContext.request.contextPath}/user/update?id=${classe.id}">修改</a> </td> </tr> </c:forEach> </tbody> </table> </form> </body> </html>
add.jsp文件为:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>增加页面</title> </head> <body> <form action="${pageContext.request.contextPath}/user/add" method="post"> 名字:<input type="text" name="name"/><br/> 城市:<input type="text" name="city"/><br/> <input type="submit" value="增加"/> </form> </body> </html>
update.jsp文件为:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>修改页面</title> </head> <body> <form action="${pageContext.request.contextPath}/user/save" method="post"> <input type="hidden" name="id" value="${classes.id}"/> 名字:<input type="text" name="name" value="${classes.name}"><br/> 城市:<input type="text" name="city" value="${classes.city}"><br/> <input type="submit" value="修改"/> </form> </body> </html>
最后,通过控制层调用service层方法;
AdminController文件为:
package controller; import entity.Class; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import service.ClassService; import java.util.HashMap; import java.util.List; @Controller @RequestMapping("/user") public class AdminController { @Autowired private ClassService classService; @RequestMapping("/list") public String list(ModelMap modelMap, @RequestParam HashMap<String,Object> map){ List<Class> classes = classService.findByMap(map); modelMap.put("classes",classes); return "list.jsp"; } @RequestMapping("/delete") public String delete(Integer id){ classService.delete(id); return "redirect:list"; } @RequestMapping("/update") public String update(Integer id,ModelMap modelMap){ Class classes=classService.selectById(id); modelMap.put("classes",classes); return "update.jsp"; } @RequestMapping("/save") public String saveOrUpdate(Class classes){ int i=classService.saveOrUpdate(classes); return "redirect:list"; } @RequestMapping("/add") public String add(Class classes){ classService.saveOrUpdate(classes); return "redirect:list"; } @RequestMapping("/toadd") public String toadd(){ return "add.jsp"; } }
浏览器页面效果为: