idea搭建ssm框架
idea搭建ssm框架
新建项目
打开idea,点击File→New→Project
选择Maven工程,勾选上Create from archetype,选择webapp,然后Next
填上自己的GroupId和ArtifactId,然后Next
下拉选择自己电脑上配置的Maven仓库位置,核对本地仓库路径是否正确
填写项目名后finish完成创建
右下角会弹出询问Maven projects need to be imported,点击enabled auto import后耐心的等待(idea创建时会耗时很长,因此如果出现某些文件夹未正常显示,请耐心等待idea完成下载)若长时间未出现反应,可以尝试重新创建新项目
配置idea中的jdk版本
点击File箭→Settings
找到下图设置,将version改为自己电脑上安装的jdk版本后应用
点击File→project structure
点击Project栏检查是否为电脑jdk版本
在Modules中检查是否为电脑jdk版本
此时若src仍未正常显示,则鼠标右击项目名,刷新该项目
看见Maven控制台显示build success,则项目部署应该完成了,src就可以正常显示
此时src目录下应该有resources和webapp文件夹,并在webapp下有WEB-INF文件夹和web.xml文件,(其他文件是因为idea之前配置过相关配置而自动生成的)
当然这缺了java文件夹,因此我们得在main中新建java文件夹并且完善其中文件夹结构,如图
此时可发现java文件夹并不是蓝色的,idea未将其作为sources文件夹,因此,我们需要在File→project structure→Modules中找到并选中java文件夹,点击Sources然后ok,idea即可识别java文件
配置pom.xml
在pom.xml中导入以下依赖后等maven自动下载完成
<dependencies>
<!--Junit测试包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 导入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- spring全家桶 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!--解决切面创建失败问题-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<!--文件上传下载-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!--Druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
<!-- springmvc 对json的依赖 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
<!--进行对象转换-->
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<!-- jedis(Redis缓存) -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.3.0</version>
</dependency>
<!-- jstl(jsp标签类) -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!--slf4j日志文件配置-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
当然也可以用properties进行版本控制
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<自定义版本名>版本号</自定义版本名>
<srping.version>5.2.6.RELEASE</srping.version>
<mybatis.version>3.5.3</mybatis.version>
<slf4j.version>1.7.25</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<druid.version>1.1.21</druid.version>
</properties>
然后version中就将其改为
<version>${自定义版本名}</version>
注*:在配置mybatis和spring版本整合时一定要注意版本兼容问题
配置web.xml文件
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<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" metadata-complete="true">
<display-name>ssm</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<!-- 默认匹配所有的请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 跨域请求 -->
<filter>
<filter-name>SimpleCORSFilter</filter-name>
<filter-class>com.wanxi.config.SimpleCORSFilter</filter-class>
<init-param>
<param-name>IsCross</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SimpleCORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置编码过滤器,主要用来解决乱码问题-->
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
配置log4j.properties日志文件
在resources下新建一个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
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
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
配置jdbc.properties数据库文件
在resources下新建一个jdbc.properties文件
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
#jdbc.driverClassName=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://127.0.0.1:3306/ssmdb?characterEncoding=utf-8
jdbc.url=jdbc:mysql://localhost:3306/team_manage?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=root
#------------------------------------------------------------------------------------------
#配置扩展插件 监控统计用filters:stat 日志用filters:log4j 防御sql注入用filters:wall
filters:stat
#最大连接池数量 初始化建立物理连接的个数 获取连接时最长的等待时间 最小连接池数量 maxIdle已经弃用
maxActive:20
initialSize:1
maxWait:60000
minIdle:10
#maxIdle:15
#有两个含义 1.Destroy 线程会检测连接的时间 2.testWhileIdle的判断依据
timeBetweenEvictionRunsMillis:60000
#Destory线程中如果检测到当前连接的最后活跃时间和当前时间的差值大于minEvictableIdleTimeMillis,则关闭当前连接
minEvictableIdleTimeMillis:300000
#用来检测连接是否的sql,要求是一个查询语句。在mysql中通常设置为SELECT 'X'
validationQuery:SELECT 'x'
#申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery连接是否有效
testWhileIdle:true
#申请连接时执行validationQuery检测连接是否有效 这个配置会降低性能
testOnBorrow:false
#归还连接时执行validationQuery检测连接是否有效 这个配置会降低性能
testOnReturn:false
#要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true
maxOpenPreparedStatements:20
#对于建立连接超过removeAbandonedTimeout的连接强制关闭
removeAbandoned:true
#指定连接建立多长就被强制关闭
removeAbandonedTimeout:1800
#指定发生removeabandoned时,是否记录当前线程的堆栈信息到日志中
logAbandoned:true
配置mybatis-config.xml文件
在resources下新建一个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>
<!-- 配置全局属性 -->
<settings>
<!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
<setting name="useGeneratedKeys" value="true" />
<!-- 使用列别名替换列名 默认:true -->
<setting name="useColumnLabel" value="true" />
<!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
</configuration>
配置spring
在resources下新建一个spring文件夹,并在下面创建spring相关配置文件
配置spring-aop.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--配置扫描器必须引入的xmlns 属性: xmlns:context="http://www.springframework.org/schema/context" -->
<!--配置aop的通知必须引入的xmlns 属性: xmlns:aop="http://www.springframework.org/schema/aop" -->
<beans xmlns="http://www.springframework.org/schema/beans"
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/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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop">
<!--========================================== 注解实现通知 ===============================================-->
<!-- 配置扫描器 -->
<context:component-scan base-package="com.wanxi"></context:component-scan>
<!-- 开启注解对AOP的支持 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
配置spring-dao.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置整合mybatis过程 -->
<!-- 1.配置数据库相关参数properties的属性:${url} -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 2.数据库连接池 -->
<!-- 使用DruidDataSource 作为数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="username" value="${jdbc.username}"/>
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="password" value="${jdbc.password}"/>
<property name = "filters" value = "${filters}" />
<!-- 最大并发连接数 -->
<property name="maxActive" value="${maxActive}" />
<!-- 初始化连接数量 -->
<property name="initialSize" value="${initialSize}" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="${maxWait}" />
<!-- 最小空闲连接数 -->
<property name="minIdle" value="${minIdle}" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
<property name="validationQuery" value="${validationQuery}" />
<property name="testWhileIdle" value="${testWhileIdle}" />
<property name="testOnBorrow" value="${testOnBorrow}" />
<property name="testOnReturn" value="${testOnReturn}" />
<property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="${removeAbandoned}" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="${logAbandoned}" />
</bean>
<!--************配置事务*************************-->
<!--1.注册事务管理器(需要依赖数据源)-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--2.配置事务建议(规则) 事务传播特性-->
<tx:advice transaction-manager="transactionManager" id="adviceId">
<tx:attributes>
<!--propagation="REQUIRED"代表支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择-->
<!--propagation="SUPPORTS" 支持当前事务,如果当前没有事务,就以非事务方式执行。 -->
<!--read-only 事务是否只读?-->
<tx:method name="find*" read-only="true"/>
<tx:method name="select*" read-only="true"/>
<tx:method name="add*" read-only="false" propagation="REQUIRED"/>
<tx:method name="save*" read-only="false" propagation="REQUIRED"/>
<tx:method name="update*" read-only="false" propagation="REQUIRED"/>
<tx:method name="delete*" read-only="false" propagation="REQUIRED"/>
<tx:method name="insert*" read-only="false" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置Aop 配置参与事务的类-->
<aop:config>
<!--配置切入点: aop:pointcut 切入点: 标签配置参与事务的类-->
<aop:pointcut id="pointCutId" expression="execution(* com.wanxi.service.impl.*.*(..))"></aop:pointcut>
<!--配置切面 aop:advisor标签就是把上面我们所配置的事务管理两部分属性整合起来作为整个事务管理-->
<aop:advisor advice-ref="adviceId" pointcut-ref="pointCutId"></aop:advisor>
</aop:config>
<!--************配置事务结束**********************-->
<!-- 4.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 扫描pojo包 使用别名 -->
<property name="typeAliasesPackage" value="com.wanxi.model"/>
<!-- 扫描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 5.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.wanxi.mapper"/>
</bean>
</beans>
配置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:context="http://www.springframework.org/schema/context"
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/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">
<!-- 配置SpringMVC -->
<!-- 1.开启SpringMVC注解模式 -->
<!-- 简化配置:
(1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter
(2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持
-->
<mvc:annotation-driven />
<!-- 2.静态资源默认servlet配置
(1)加入对静态资源的处理:js,gif,png
(2)允许使用"/"做整体映射
-->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 显示ViewResolver -->
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<!-- 根据URL中的文件扩展名确定MIME(如userList.xml,userList.json) -->
<property name="favorPathExtension" value="true" />
<!-- 则根据请求参数的值确定MIME类型,默认的请求参数是format,可以通过parameterName属性指定一个自定义的参数 -->
<property name="favorParameter" value="true" />
<!-- 则采用Accept请求报文头的值确定MIME类型。由于不同的浏览器产生的Accept头都是不一样的,所以一般不建议采用Accept确定MIME类型 -->
<property name="ignoreAcceptHeader" value="true" />
<property name="useJaf" value="false" />
<property name="defaultContentType" value="text/html" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
</bean>
<!--<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="contentNegotiationManager" ref="contentNegotiationManager" />
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
<property name="contentType" value="text/html; charset=UTF-8"/>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<!– for application/json –>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
<property name="extractValueFromSingleKeyModel" value="true" />
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
</property>
</bean>
</property>
</bean>
<!– for application/xml –>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<property name="marshaller">
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true"/>
<property name="streamDriver">
<bean class="com.thoughtworks.xstream.io.xml.StaxDriver" />
</property>
</bean>
</property>
</bean>
</list>
</property>
</bean>-->
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="viewResolvers">
<list>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
</bean>
</list>
</property>
</bean>
<!-- 4.扫描web相关的bean -->
<context:component-scan base-package="com.wanxi.controller" />
<context:component-scan base-package="com.wanxi.service" />
<!-- 接口跨域配置-->
<mvc:cors>
<mvc:mapping path="/**" allowed-origins="*"
allowed-methods="POST, GET, OPTIONS, DELETE, PUT"
allowed-headers="Content-Type, Content-Length, Authorization, Accept, X-Requested-With, yourHeaderFeild"
allow-credentials="true" />
</mvc:cors>
</beans>
到这之后,还有一些文件是没有创建的,因此我们得创建出来以解决报错
新建SimpleCORSFilter
在java文件夹中新建一个config文件,并在其文件夹下新建一个SimpleCORSFilter类,继承Filter接口以及里面的方法,该类用于拦截并过滤跨域请求。
package com.wanxi.config;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SimpleCORSFilter implements Filter {
private boolean isCross = false;
public void init(FilterConfig filterConfig) throws ServletException {
String isCrossStr = filterConfig.getInitParameter("IsCross");
isCross = isCrossStr.equals("true") ? true : false;
System.out.println(isCrossStr);
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (isCross) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
System.out.println("拦截请求: " + httpServletRequest.getServletPath());
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
httpServletResponse.setHeader("Access-Control-Max-Age", "0");
httpServletResponse.setHeader("Access-Control-Allow-Headers",
"Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("XDomainRequestAllowed", "1");
}
chain.doFilter(request, response);
}
public void destroy() {
isCross = false;
}
}
最后创建出来后的文件结构应该是这样的
其余文件都可只先暂时创建一个空文件
注:mapper文件夹中需要至少有一个mapper.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="接口类所在文件夹,如com.wanxi.mapper.UserMapper">
</mapper>
配置Tomcat运行环境
点击右上角Add configuration
点击左上角加号,往下滑动找到Tomcat Server→Local
Server栏选择运行时的浏览器以及jdk版本
Deployment中点击右边加号→Artifact
选择带有exploded的文件,将下方context改为斜杠/,应用并关闭
点击运行或者debug启动Tomcat
若出现XX版本过低,会在后面的版本删除等警告信息,则重新回到最开始检查配置idae中的jdk版本,重新配置后再次运行,未出现错误则ssm配置成功!
此时即可开始尝试连接数据库进行测试。
我用的是mysql,因此,在数据库中新建一个数据库,并在其中新建一个usr表,定义属性和字段
填充之前空文件的数据
编写测试类
User.java
package com.wanxi.model;
import java.io.Serializable;
public class User implements Serializable {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserMapper.class(该类是interface接口类)
package com.wanxi.mapper;
import com.wanxi.model.User;
import java.util.List;
public interface UserMapper {
List<User> getUserList();
}
UserService.java(接口类)
package com.wanxi.service;
import com.wanxi.model.User;
import java.util.List;
public interface UserService {
List<User> getUserList();
}
UserServiceImpl.java
package com.wanxi.service.impl;
import com.wanxi.mapper.UserMapper;
import com.wanxi.model.User;
import com.wanxi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public List<User> getUserList() {
return userMapper.getUserList();
}
}
UserMapper.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="com.wanxi.mapper.UserMapper">
<select id="getUserList" resultType="com.wanxi.model.User">
select * from usr
</select>
</mapper>
UserController.java
package com.wanxi.controller;
import com.wanxi.model.User;
import com.wanxi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@GetMapping("/getUserList")
public List<User> getUserList(){
return userService.getUserList();
}
}
运行测试
完成后运行Tomcat,如果有postman,则可以打开postman,
如果没有postman,则直接在浏览器输入请求地址即可
显示出从数据库中提取出来的数据则ssm搭建测试成功!