Spring+Druid+SpringMVC的搭建(附Demo)
最近公司事情比较少,便想利用这段空闲时间做一个自己的博客。
前端界面已经搞好,感谢杨姐的模板,自己稍微把模板没有的模块给补全了。
今天便开始自己的SSM框架搭建,数据库链接是采用数据库连接池。先上个项目结构图:
这个是基于Maven搭建的ssm框架,我把service层删除了,去掉了dao层接口,业务在需要与数据库交互的时候便直接调用dao层的方法。
1、创建maven项目,maven没有接触过的请自行百度 maven项目在eclisp如何创建。
2、配置 pom.xml 加载jar包
<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.cwj</groupId> <artifactId>MyBlog</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>MyBlog Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本号 --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.2.6</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <!-- DBCP --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.13</version> </dependency> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</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-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</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-jdbc</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-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- 导入java ee jar 包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- 导入Mysql数据库链接jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.36</version> </dependency> <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL标签类 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 日志文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- 格式化对象,方便输出日志 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!-- 映入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 上传组件包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> </dependencies> <build> <finalName>MyBlog</finalName> </build> </project>
3、在src/main/java跟目录下建好需要的包
4、在src/main/resource下创建spring-mvc.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-3.1.xsd 10 http://www.springframework.org/schema/mvc 11 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 12 <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> 13 <context:component-scan base-package="com.cwj.controller" /> 14 <!-- 扩充了注解驱动,可以将请求参数绑定到控制器参数 --> 15 <mvc:annotation-driven/> 16 17 <!-- 静态文件处理 --> 18 <!-- location:表示/assets/目录下(即服务器根目录)的static包下的所有文件 --> 19 <!-- mapping:表示以/static开头的所有请求路径,如/static/a 或者/static/a/b --> 20 <mvc:resources location="/assets/" mapping="/public/**/" /> 21 22 <!--避免IE执行AJAX时,返回JSON出现下载文件 --> 23 <bean id="mappingJacksonHttpMessageConverter" 24 class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> 25 <property name="supportedMediaTypes"> 26 <list> 27 <value>text/html;charset=UTF-8</value> 28 </list> 29 </property> 30 </bean> 31 <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> 32 <bean 33 class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 34 <property name="messageConverters"> 35 <list> 36 <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 --> 37 </list> 38 </property> 39 </bean> 40 41 <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> 42 <bean id="multipartResolver" 43 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 44 <!-- 默认编码 --> 45 <property name="defaultEncoding" value="utf-8" /> 46 <!-- 文件大小最大值 --> 47 <property name="maxUploadSize" value="10485760000" /> 48 <!-- 内存中的最大值 --> 49 <property name="maxInMemorySize" value="40960" /> 50 <!-- 启用是为了推迟文件解析,以便捕获文件大小异常 --> 51 <property name="resolveLazily" value="true"/> 52 </bean> 53 54 <!-- 配置ViewResolver 。可用多个ViewResolver 。使用order属性排序。 InternalResourceViewResolver 放在最后--> 55 <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> 56 <property name="order" value="1"></property> 57 <property name="mediaTypes"> 58 <map> 59 <!-- 告诉视图解析器,返回的类型为json格式 --> 60 <entry key="json" value="application/json" /> 61 <entry key="xml" value="application/xml" /> 62 <entry key="htm" value="text/htm" /> 63 </map> 64 </property> 65 <property name="defaultViews"> 66 <list> 67 <!-- ModelAndView里的数据变成JSON --> 68 <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /> 69 </list> 70 </property> 71 <property name="ignoreAcceptHeader" value="true"></property> 72 </bean> 73 74 <!-- 定义跳转的文件的前后缀 ,视图模式配置--> 75 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 76 <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> 77 <property name="prefix" value="/WEB-INF/view/" /> 78 <property name="suffix" value=".jsp" /> 79 </bean> 80 </beans>
5、配置好web.xml就可以测试刚刚配置的Spring+SpringMVC有没有成功。等会儿,全部配置完,记得把注释给取消掉。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 5 version="3.0"> 6 <display-name>Archetype Created Web Application</display-name> 7 <!-- Spring和mybatis的配置文件 --> 8 <!-- <context-param> 9 <param-name>contextConfigLocation</param-name> 10 <param-value>classpath:spring-mybatis.xml</param-value> 11 </context-param> --> 12 <!-- 编码过滤器 --> 13 <filter> 14 <filter-name>encodingFilter</filter-name> 15 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 16 <async-supported>true</async-supported> 17 <init-param> 18 <param-name>encoding</param-name> 19 <param-value>UTF-8</param-value> 20 </init-param> 21 </filter> 22 <filter-mapping> 23 <filter-name>encodingFilter</filter-name> 24 <url-pattern>/*</url-pattern> 25 </filter-mapping> 26 <!-- Spring监听器 --> 27 <!-- <listener> 28 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 29 </listener> --> 30 <!-- 防止Spring内存溢出监听器 --> 31 <!-- <listener> 32 <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> 33 </listener> --> 34 35 <!-- Spring MVC servlet --> 36 <servlet> 37 <servlet-name>SpringMVC</servlet-name> 38 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 39 <init-param> 40 <param-name>contextConfigLocation</param-name> 41 <param-value>classpath:spring-mvc.xml</param-value> 42 </init-param> 43 <load-on-startup>1</load-on-startup> 44 <async-supported>true</async-supported> 45 </servlet> 46 <servlet-mapping> 47 <servlet-name>SpringMVC</servlet-name> 48 <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> 49 <url-pattern>/</url-pattern> 50 </servlet-mapping> 51 <welcome-file-list> 52 <welcome-file>/index.jsp</welcome-file> 53 </welcome-file-list> 54 55 </web-app>
6、在com.cwj.controller包下创建一个StudentController.java控制器
1 package com.cwj.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @Controller 7 public class StudentController { 8 9 @RequestMapping(value="/test") 10 public String test(){ 11 12 return "com/test"; 13 } 14 }
7、根据配置的路径,创建相应的test.jsp文件,之后在tomcat中运行。
8、接下来就是配置spring-mybatis.首先创建application.properties 配置数据库连接信息
1 jdbc.driver=com.mysql.jdbc.Driver 2 jdbc.url=jdbc\:mysql\://rm-wz92wfb0l40ny7b5jo.mysql.rds.aliyuncs.com\:3306/test 3 jdbc.username=root 4 jdbc.password=CHen123456 5 6 #定义初始连接数 7 jdbc.initialSize=0 8 #定义最大连接数 9 jdbc.maxActive=20 10 #定义最大空闲 11 jdbc.maxIdle=20 12 #定义最小空闲 13 jdbc.minIdle=1 14 #定义最长等待时间 15 jdbc.maxWait=60000 16 17 dbcp.initialSize=15 18 dbcp.maxActive=5000 19 dbcp.maxIdle=0 20 dbcp.maxWait=900000 21 dbcp.defaultAutoCommit=true 22 dbcp.removeAbandoned=true 23 dbcp.removeAbandonedTimeout=30 24 dbcp.whenExhaustedAction=1 25 dbcp.validationQuery=select 1 26 dbcp.testOnBorrow=fasle 27 dbcp.testOnReturn=false
9、配置log4j.properties信息
log4j.rootLogger=INFO,Console,File
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
log4j.appender.File = org.apache.log4j.RollingFileAppender
log4j.appender.File.File = logs/ssm.log
log4j.appender.File.MaxFileSize = 10MB
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
10、配置spring-mybatis.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.cwj" /> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:application.properties" /> </bean> <!-- 数据源配置,使用应用内的DBCP数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="initialSize" value="${dbcp.initialSize}" /> <property name="maxActive" value="${dbcp.maxActive}" /> <property name="maxIdle" value="${dbcp.maxIdle}" /> <property name="maxWait" value="${dbcp.maxWait}" /> <property name="defaultAutoCommit" value="${dbcp.defaultAutoCommit}" /> <property name="removeAbandoned" value="${dbcp.removeAbandoned}" /> <property name="removeAbandonedTimeout" value="${dbcp.removeAbandonedTimeout}" /> <property name="logAbandoned" value="true"></property> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="${dbcp.validationQuery}" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 如果用Oracle,则把poolPreparedStatements配置为true,mysql可以配置为false。分库分表较多的数据库,建议配置为false。--> <property name="poolPreparedStatements" value="false" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <!-- 配置监控统计拦截的filters --> <property name="filters" value="stat" /> </bean> <!-- spring jdbc NamedParameterJdbcTemplate --> <bean id="namedjdbctemp" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <constructor-arg ref="dataSource"/> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <!-- <property name="mapperLocations" value="classpath:com/cwj/mapping/*.xml"></property> --> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.cwj.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
11、最后测试配置是否成功。
数据库表是这样的
DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `id` varchar(32) NOT NULL DEFAULT '', `name` varchar(255) DEFAULT NULL, `age` smallint(6) DEFAULT NULL, `sex` smallint(6) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
12、创建实体类Student.java
package com.cwj.pojo; import javax.persistence.Entity; @Entity public class Student { private String id; private String name; private Integer sex; private Integer age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]"; } }
13、创建StudentDao
package com.cwj.dao; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.cwj.pojo.Student; @Repository public class StudentDao { @Resource private NamedParameterJdbcTemplate namedjdbctemp; @Transactional public Student queryStuById(String id){ String sql = "select * from student where id =:id"; Map<String, Object> map = new HashMap<String, Object>(); map.put("id", id); return namedjdbctemp.queryForObject(sql, map,new BeanPropertyRowMapper<Student>(Student.class)); } }
14修改StudentController
package com.cwj.controller; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.cwj.dao.StudentDao; import com.cwj.pojo.Student; @Controller public class StudentController { private static Logger log=LoggerFactory.getLogger(StudentController.class); @Autowired private StudentDao studentService; @RequestMapping(value="/test") public String test(HttpServletRequest request){ Student student = studentService.queryStuById("2"); request.setAttribute("stu", student); log.info("stu:"+student.toString()); return "com/test"; } }
15、修改test.jsp
1 package com.cwj.controller; 2 3 import javax.servlet.http.HttpServletRequest; 4 5 import org.slf4j.Logger; 6 import org.slf4j.LoggerFactory; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.stereotype.Controller; 9 import org.springframework.web.bind.annotation.RequestMapping; 10 11 import com.cwj.dao.StudentDao; 12 import com.cwj.pojo.Student; 13 14 @Controller 15 public class StudentController { 16 17 private static Logger log=LoggerFactory.getLogger(StudentController.class); 18 19 @Autowired 20 private StudentDao studentService; 21 22 @RequestMapping(value="/test") 23 public String test(HttpServletRequest request){ 24 Student student = studentService.queryStuById("2"); 25 request.setAttribute("stu", student); 26 log.info("stu:"+student.toString()); 27 return "com/test"; 28 } 29 }
16、记得取消web.xml的注释,给张项目结构图便开始测试 因为文件夹被我改了名字。所以在github下载的文件 访问地址是 http://127.0.0.1:8080/MyBlog/test
静态图片也加载成功。
有问题欢迎留言咨询。
贴上github链接:
https://github.com/BeautifulMeet/gitDemo