天天看点

如何搭建一个SSM框架

如何搭建一个空的SSM框架

    • 开始配置
      • web.xml
      • applicationContext.xml
      • applicationContext-mybatis.xml
      • mybatis-config.xml
      • db.properties
      • springmvc.xml
      • 写在最后

这里说的SSM是指 Spring SpringMVC MyBatis

这里写这篇文章的目的是 马上又要开始 一年的毕设季了

开始配置

首先建立以下目录 目录结构 可以自行修改,但一定要同时更改所有配置文件中的路径

如何搭建一个SSM框架

web.xml

<?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"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0">
	<display-name>xss</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>	<!-- 初始页面 -->
	</welcome-file-list>

	<!-- 加载srping容器 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<listener>
		<!-- ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext 的配置信息。 
			因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时, 就会默认执行它实现的方法 -->
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 配置Spring字符编码过滤器 -->
	<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>
		<!-- 设置热部署 -->
		<init-param>
		  	<param-name>development</param-name>
		  	<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- 前端控制器 -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 指定springmvc的核心文件 -->
		<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>

	<servlet-mapping>
     	<servlet-name >default </servlet-name >         
		<url-pattern >*.js</url-pattern>      
	</servlet-mapping >
	<servlet-mapping >
	     <servlet-name >default </servlet-name >             
		 <url-pattern >*.css</url-pattern>        
	</servlet-mapping >
</web-app>
           

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

	<!-- 配置 @Service注解扫描 -->
	<context:component-scan base-package="com.*.service"></context:component-scan>

	<!-- 加载其他配置文件 -->
	<import resource="classpath:applicationContext-mybatis.xml" />

	<!-- 导入属性配置文件 -->
	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<!-- 允许JVM参数覆盖 -->
		<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
		<!-- 忽略没有找到的资源文件 -->
		<property name="ignoreResourceNotFound" value="true" />
		<property name="locations">
			<list>
				<value>classpath*:db.properties</value>
			</list>
		</property>
	</bean>

	<!-- ==================druid连接池 配置================== -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<!-- 基本属性 url、user、password -->
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<!-- 配置初始化大小、最小、最大 -->
		<property name="initialSize" value="${ds.initialSize}" />
		<property name="minIdle" value="${ds.minIdle}" />
		<property name="maxActive" value="${ds.maxActive}" />
		<!-- 配置获取连接等待超时的时间 -->
		<property name="maxWait" value="${ds.maxWait}" />
		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="${ds.timeBetweenEvictionRunsMillis}" />
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="${ds.minEvictableIdleTimeMillis}" />
		<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
		<property name="poolPreparedStatements" value="true" />
		<property name="maxPoolPreparedStatementPerConnectionSize"
			value="20" />

		<!-- JDBC Proxy Driver -->
		<property name="proxyFilters">
			<list>
				<ref bean="stat-filter" />
			</list>
		</property>


	</bean>
	<!-- SQL合并配置, 慢SQL记录 如秘钥方式配置 -->
	<!-- <property name="connectionProperties" value="druid.stat.mergeSql=true,druid.stat.slowSqlMillis=1000;config.decrypt=true;config.decrypt.key=${publicKey}" 
		/> -->
	<bean id="stat-filter" class="com.alibaba.druid.filter.stat.StatFilter">
		<property name="slowSqlMillis" value="1000" />
		<property name="logSlowSql" value="true" />
		<property name="mergeSql" value="true" />
	</bean>

	<!-- 事务声明 -->
	<bean id="txManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<tx:annotation-driven proxy-target-class="false"
		transaction-manager="txManager" />

</beans>
           

applicationContext-mybatis.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

	<!-- mapper配置 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 指定数据库连接池 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 加载mybatis的全局配置文件 -->
		<property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
		<property name="typeAliasesPackage" value="com.xss.pojo"></property><!-- 数据库实体类 -->
		<property name="mapperLocations">
			<list>
				<value>classpath:mybatis/mapper/*.xml</value>
			</list>
		</property>
		<!-- 分页插件 -->
		<property name="plugins">
			<array>
				<bean class="com.github.pagehelper.PageInterceptor">
					<property name="properties">
						<value>
							helperDialect=mysql
							offsetAsPageNum=true
							<!-- 防止出现小于第一页,大于最后一页的异常情况出现。 -->
							reasonable=true
						</value>
					</property>
				</bean>
				<bean class="com.github.abel533.mapperhelper.MapperInterceptor">
					<property name="properties">
						<value>
							<!-- 主键自增回写方法,默认值MYSQL -->
							IDENTITY=MYSQL
							mappers=com.github.abel533.mapper.Mapper
						</value>
					</property>
				</bean>
			</array>
		</property>
	</bean>
	
	<!-- 配置mapper的bean,使用包扫描的方式 批量导入Mapper。这样mybatis所有的配置都交给spring来管理 扫描后 引用时可以直接使用类名,注意首字母小写 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 指定扫描包的全路径。如果有多个,用英文的逗号分开 -->
		<property name="basePackage" value="com.*.mapper"></property>
	</bean>
</beans>

           

mybatis-config.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>

	<!-- 配置mybatis的缓存,延迟加载等等一系列属性 -->
	<settings>
		<!-- 全局映射器启用缓存 -->
		<setting name="cacheEnabled" value="true"/>

		<!-- 查询时,关闭关联对象即时加载以提高性能 -->
		<setting name="lazyLoadingEnabled" value="true"/>

		<!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
		<setting name="multipleResultSetsEnabled" value="true"/>

		<!-- 允许使用列标签代替列名 -->
		<setting name="useColumnLabel" value="true"/>

		<!-- 不允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
		<setting name="useGeneratedKeys" value="false"/>

		<!-- 给予被嵌套的resultMap以字段-属性的映射支持 FULL,PARTIAL -->
		<setting name="autoMappingBehavior" value="PARTIAL"/>

		<!-- Allows using RowBounds on nested statements -->
		<setting name="safeRowBoundsEnabled" value="false"/>

		<!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn. -->
		<setting name="mapUnderscoreToCamelCase" value="true"/>

		<!-- MyBatis uses local cache to prevent circular references and speed up repeated nested queries. By default (SESSION) all queries executed during a session are cached. If localCacheScope=STATEMENT
            local session will be used just for statement execution, no data will be shared between two different calls to the same SqlSession. -->
		<setting name="localCacheScope" value="SESSION"/>

		<!-- Specifies the JDBC type for null values when no specific JDBC type was provided for the parameter. Some drivers require specifying the column JDBC type but others work with generic values
            like NULL, VARCHAR or OTHER. -->
		<setting name="jdbcTypeForNull" value="OTHER"/>

		<!-- Specifies which Object's methods trigger a lazy load -->
		<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>

		<!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指定),不会加载关联表的所有字段,以提高性能 -->
		<setting name="aggressiveLazyLoading" value="false"/>
		<setting name="logImpl" value="STDOUT_LOGGING"/>
	</settings>

	<typeAliases>
		<!-- 注:model表对象配置,请按照model 包中的顺序进行录入,并做好注释. -->
		<!--设置别名-->
		<package name="cn.xss.pojo"/>  
	</typeAliases>
	<plugins>
		<plugin interceptor="com.github.abel533.mapperhelper.MapperInterceptor">
			<!--主键自增回写方法,默认值MYSQL,详细说明请看文档 -->
			<property name="IDENTITY" value="MYSQL" />
			<!--通用Mapper接口,多个通用接口用逗号隔开 -->
			<property name="mappers" value="com.github.abel533.mapper.Mapper" />
		</plugin>
	</plugins>
</configuration>
           

db.properties

jdbc.driver=com.mysql.jdbc.Driver

#\u672C\u5730\u6570\u636E\u5E93
jdbc.url=jdbc:mysql://127.0.0.1:3306/xss?allowMultiQueries=true&useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
##DataSource Global Setting
#\u914D\u7F6E\u521D\u59CB\u5316\u5927\u5C0F\u3001\u6700\u5C0F\u3001\u6700\u5927
ds.initialSize=10
ds.minIdle=5
ds.maxActive=12

#\u914D\u7F6E\u83B7\u53D6\u8FDE\u63A5\u7B49\u5F85\u8D85\u65F6\u7684\u65F6\u95F4
ds.maxWait=60000

#\u914D\u7F6E\u95F4\u9694\u591A\u4E45\u624D\u8FDB\u884C\u4E00\u6B21\u68C0\u6D4B\uFF0C\u68C0\u6D4B\u9700\u8981\u5173\u95ED\u7684\u7A7A\u95F2\u8FDE\u63A5\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2
ds.timeBetweenEvictionRunsMillis=60000

# \u914D\u7F6E\u4E00\u4E2A\u8FDE\u63A5\u5728\u6C60\u4E2D\u6700\u5C0F\u751F\u5B58\u7684\u65F6\u95F4\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2
ds.minEvictableIdleTimeMillis=300000
           

springmvc.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"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        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">

	<!-- 配置@Controller注解 扫描加载 -->
	<context:component-scan base-package="com.*.controller"></context:component-scan>

	<!-- Enables the Spring MVC @Controller programming model -->
	<mvc:annotation-driven />

	<!-- Spring框架来处理静态文件解决后台No mapping found for HTTP request with URI 错误 -->
	<mvc:default-servlet-handler />

	<!-- 支持返回json(避免IE在ajax请求时,返回json出现下载 ) -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" />
			</list>
		</property>
	</bean>
	<bean id="mappingJacksonHttpMessageConverter"
		class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>text/plain;charset=UTF-8</value>
				<value>application/json;charset=UTF-8</value>
			</list>
		</property>
	</bean>

	<!-- FreeMarker视图解析器     默认视图 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>
		<property name="contentType" value="text/html; charset=utf-8"/>
		<property name="requestContextAttribute" value="rc"/>
		<property name="cache" value="false"/>
		<property name="viewNames" value="*.html" />
		<property name="suffix" value=""/>
		<property name="order" value="0"/>
	</bean>

	<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<property name="templateLoaderPath" value="/WEB-INF/page/"/>
		<property name="defaultEncoding" value ="UTF-8"></property>
	</bean>
	
	<!-- 静态资源配置 -->
	<mvc:resources location="/static/" mapping="/static/**"></mvc:resources>

</beans>
           

写在最后

想需要源码的可以来找我喔

关注公众号

【再喝最后一杯珍珠奶茶】

如何搭建一个SSM框架