SSM(Spring+Spring MVC+Mybatis)环境框架搭建与配置详解
来源:互联网 发布:mac外服加速器 编辑:程序博客网 时间:2024/06/05 22:52
版权声明:本文为博主原创文章,未经博主允许不得转载。
一、简介
使用SSM框架做了一些项目,一直都是使用别人已经搭建好的框架。于是自己尝试着搭建了一下框架,并研究了一下配置文件。
基本的组织结构和用法就不用多说了,各种官方文档上比较全面
二、环境与框架
开发环境MyEclipse+JDK1.7+Tomcat7
开发环境配置请查阅博客
本文按照开发环境搭建,完整的结构框架如下
三、配置文件详解
1.web.xml
web.xml应该是整个项目中最重要的配置文件了,配置方式与普通的servlet基本相似
<span style="font-size:14px;"> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:resources/spring-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping></span>
servlet 配置前端控制器,其中
ContextconfigLocation配置配置springmvc加载的配置文件适配器、处理映射等等
url-pattern中 .* :访问以.*结尾 由DispatcherServlet进行解析
/ :所有访问由DispatcherServlet进行解析
配置Spring容器:
<span style="font-size:14px;"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:resources/spring-mvc.xml</param-value> </context-param></span>配置日志文件:
<span style="font-size:14px;"> <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></span>
配置监听器:
<span style="font-size:14px;"> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener></span>
<span style="font-size:14px;"> <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></span>
配置处理错误页面:
<span style="font-size:14px;"><error-page><span style="white-space:pre"></span><exception-type>java.lang.Throwable</exception-type><span style="white-space:pre"></span><location>/error.jsp</location></error-page><error-page><span style="white-space:pre"></span><error-code>404</error-code><span style="white-space:pre"></span><location>/error.jsp</location></error-page><error-page><span style="white-space:pre"></span><error-code>500</error-code><span style="white-space:pre"></span><location>/error.jsp</location></error-page></span>
完整的web.xml文件如下:
<span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5" id="WebApp_1473651077644"> <error-page><exception-type>java.lang.Throwable</exception-type><location>/error.jsp</location></error-page><error-page><error-code>404</error-code><location>/error.jsp</location></error-page><error-page><error-code>500</error-code><location>/error.jsp</location></error-page> <distributable/> <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> <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> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:resources/spring-mvc.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:resources/spring-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <session-config> <session-timeout>60</session-timeout> </session-config></web-app></span>
2.spring-mvc.xml
<span style="font-size:14px;"><?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:c="http://www.springframework.org/schema/c" xmlns:util="http://www.springframework.org/schema/util"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"xmlns:task="http://www.springframework.org/schema/task"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsdhttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"default-autowire="byName"> <!-- scan all spring supported annotation, but exclude controller here --><context:component-scan base-package="com.changhong.lyc"></context:component-scan> <mvc:annotation-driven /> <!-- 使用util properties 避免多mybatis配置时参数初始化问题 --> <util:properties id="dataSourceProps" location="classpath:resources/jdbc.properties"/><!-- define datasource --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"><property name="driverClassName" value="#{dataSourceProps['jdbc.driver']}" /><property name="url" value="#{dataSourceProps['jdbc.url']}" /><property name="username" value="#{dataSourceProps['jdbc.user']}" /><property name="password" value="#{dataSourceProps['jdbc.password']}" /><property name="maxActive" value="#{dataSourceProps['jdbc.maxActive']}" /> <property name="initialSize" value="5" /><!--maxIdle: 最大空闲连接 --><property name="maxIdle" value="10" /><!--minIdle: 最小空闲连接 --><property name="minIdle" value="5" /><!--removeAbandoned: 是否自动回收超时连接 --><property name="removeAbandoned" value="true" /><!--removeAbandonedTimeout: 超时时间(以秒数为单位) --><property name="removeAbandonedTimeout" value="180" /><!--maxWait: 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 --><property name="maxWait" value="3000" /></bean><!-- 事务配置 --> <bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource" /></bean><!-- 扫描mybatis mapper --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="mapperLocations" value="classpath:resources/mybatis/*Mapper.xml" /></bean> <!-- 扫描所有dao --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.changhong.lyc.dao" /><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /></bean> <tx:annotation-driven transaction-manager="transactionManager" /><tx:advice id="txAdvice" transaction-manager="transactionManager" ><tx:attributes><tx:method name="del*" propagation="REQUIRED" rollback-for="java.lang.Exception" no-rollback-for="java.lang.RuntimeException" /><tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception" /><tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception" /><tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Exception" /><tx:method name="insertWorkflow*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception" /><tx:method name="updateWorkflow*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception" /><tx:method name="find*" propagation="SUPPORTS" read-only="true" /><tx:method name="check*" propagation="SUPPORTS" read-only="true"/><tx:method name="get*" propagation="SUPPORTS" read-only="true"/><tx:method name="search*" propagation="SUPPORTS" read-only="true"/><tx:method name="query*" propagation="SUPPORTS" read-only="true"/><tx:method name="*" propagation="SUPPORTS" read-only="true"/></tx:attributes></tx:advice><aop:config><aop:advisor pointcut="execution(* com.changhong.lyc.dao.*Dao.*(..))" advice-ref="txAdvice" /></aop:config><bean id="exceptionResolver"class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"><property name="exceptionMappings"><props><prop key="org.springframework.security.access.AccessDeniedException">error/access-denied</prop><prop key="net.yingzhuo.me.exception.NonEmptyGroupException">error/non-empty-group</prop></props></property><property name="warnLogCategory" value="以下为警告信息" /><property name="defaultErrorView" value="error" /><property name="defaultStatusCode" value="500" /></bean><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前缀 --><property name="prefix" value="/WEB-INF/jsp/" /><!-- 后缀 --><property name="suffix" value=".jsp" /> </bean></beans></span>
3.spring-servlet.xml
<span style="font-size:14px;"><?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.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"default-autowire="byName"><!-- <context:property-placeholder location="classpath*:resources/*.properties" /> --><!-- scan all controller, but exclude service --><context:component-scan base-package="com.changhong.lyc"><context:include-filter type="annotation"expression="org.springframework.stereotype.Controller" /><context:exclude-filter type="annotation"expression="org.springframework.stereotype.Service" /></context:component-scan><!-- mvc:annotation-driven会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,是spring MVC为@Controllers分发请求所必须的.并提供了:数据绑定支持,@NumberFormatannotation支持, @DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson) --><!-- <mvc:annotation-driven conversion-service="conversion-service" validator="validator"> --><mvc:annotation-driven conversion-service="conversion-service"><mvc:message-converters><beanclass="org.springframework.http.converter.ByteArrayHttpMessageConverter" /><bean class="org.springframework.http.converter.FormHttpMessageConverter" /><beanclass="org.springframework.http.converter.xml.SourceHttpMessageConverter" /><bean class="org.springframework.http.converter.StringHttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/plain;charset=UTF-8</value></list></property></bean><bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"><property name="objectMapper"><bean class="org.codehaus.jackson.map.ObjectMapper"><property name="serializationInclusion"><value type="org.codehaus.jackson.map.annotate.JsonSerialize$Inclusion">NON_NULL</value></property></bean></property></bean></mvc:message-converters></mvc:annotation-driven><mvc:default-servlet-handler /><bean id="conversion-service"class="org.springframework.format.support.FormattingConversionServiceFactoryBean"></bean></beans> </span>
4.jdbc.properties与log4j.properties
1.jdbc.properties
<span style="font-size:14px;">jdbc.driver =com.mysql.jdbc.Driverjdbc.url = jdbc\:mysql\://yourUrl\:3306/test?createDatabaseIfNotExist\=true&useUnicode\=true&characterEncoding\=UTF-8jdbc.user =yourNamejdbc.password = yourPwdjdbc.maxActive=20</span>
2.log4j.properties
<span style="font-size:14px;">log4j.rootLogger=DEBUG,stdout,Elog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=[%-5p]%d{yyyy-MM-dd HH:mm:ss}[%c]:%m%nlog4j.logger.java.sql.Connection=DEBUGlog4j.logger.java.sql.Statement=DEBUGlog4j.logger.com.mchange.v2.c3p0=OFFlog4j.logger.com.mchange.v2=OFFlog4j.logger.org.springframework=OFFlog4j.logger.org.mybatis=OFFlog4j.logger.org.apache.ibatis=OFFlog4j.logger.org.apache.http=OFF# errorlog4j.appender.E = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.E.File = D\:/logs/error.log log4j.appender.E.Append = truelog4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayoutlog4j.appender.E.layout.ConversionPattern =[%-5p]%d{yyyy-MM-dd HH\:mm\:ss}[%c]\:%m%n</span>
四、架构详解
base:定义基础操作和基础类,一般具体操作和几次实体都继承自此结构下的接口
controller:控制层
dao:数据库持久层
handler:定义具体逻辑与操作
schema:实体,一般与数据库中各表的具体字段对应
util:工具类
resource:配置工具,包含mybatis的mapper映射文件,对数据库具体操作在此文件中
五、测试
数据库中保存如下数据
mapper映射文件如下:
<span style="font-size:14px;"><?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="com.changhong.lyc.dao.TestDao"><resultMap id="BaseResultMap" type="com.changhong.lyc.schema.TestSchema"><id column="t_id" property="id" jdbcType="VARCHAR"/><result column="t_name" property="name" jdbcType="VARCHAR"/><result column="t_age" property="age" jdbcType="INTEGER"/><result column="t_sex" property="sex" jdbcType="INTEGER"/><result column="t_graduateYear" property="graduateYear" jdbcType="VARCHAR"/><result column="t_collegeName" property="collegeName" jdbcType="VARCHAR"/></resultMap> <select id="selectOneByCondition" resultMap="BaseResultMap">select*fromt_tablewhere<iftest="name != null">t_name = #{name,jdbcType=VARCHAR}</if><iftest="graduateYear != null">and t_graduateYear = #{graduateYear,jdbcType=VARCHAR}</if></select></mapper></span>
使用Postman测试
访问地址在controller视图控制类中定义
返回结果如下:
<span style="font-size:14px;">{ "code": "1000", "data": { "age": 26, "collegeName": "清华大学", "graduateYear": "2015", "id": "1", "name": "张三", "sex": 1 }, "msg": "success"}</span>
2 0
- SSM(Spring+Spring MVC+Mybatis)环境框架搭建与配置详解
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境
- Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架
- idea中ssm(spring-spring mvc-mybatis)框架搭建
- SSM(spring+spring mvc+mybatis)框架搭建
- APE格式及编解码说明
- 关于Recyclerview使用时的一个错误
- 树莓派3 ROS语音包开发之类封装(下)
- SQL性能优化的十条经验
- truncate table reuse storage
- SSM(Spring+Spring MVC+Mybatis)环境框架搭建与配置详解
- 准备将暑假自学.Net开发一部分内容发布到微博上
- 定时任务 + queue队列处理
- Spring入门
- 抽象工厂
- 返利协议批导(BDC+BAPI 参考模板协议复制到不同客户)
- 一次诡异的磁盘空间占用问题排查
- 基于数据库的学生管理系统
- Pixhawk-姿态解算-互补滤波