🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
**1. 引入相关框架** ```xml <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> <spring.version>5.2.9.RELEASE</spring.version> </properties> <dependencies> <!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</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-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.4</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> <version>1.2.8.RELEASE</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.80</version> </dependency> </dependencies> ``` **2. 编写配置文件** (1)数据库信息配置文件`resources/mysql.properties`。 ```properties jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/learndb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai jdbc.username=root jdbc.password=uhg</flEt3dff maxIdle=50 minIdle=45 initialSize=5 maxActive=100 maxWait=100 removeAbandonedTimeout=180 removeAbandoned=true ``` (2)mybatis配置文件`resources/mybatis-config.xml`。 ```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="lazyLoadingEnabled" value="false"/> <setting name="autoMappingBehavior" value="FULL"/> </settings> <typeAliases> <package name="com.learn.springmvc03.pojo"/> </typeAliases> <mappers> <mapper resource="mapper/StudentMapper.xml"/> </mappers> </configuration> ``` (3)Spring配置文件`resources/applicationContext.xml`。 ```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"> <!-- 扫描包 --> <context:component-scan base-package="com.learn.springmvc03"/> <!-- 启用spring的注解 --> <context:annotation-config/> <!-- 引入数据库配置文件 --> <context:property-placeholder location="classpath:mysql.properties"/> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" scope="singleton"> <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="${initialSize}"/> <property name="maxActive" value="${maxActive}"/> <property name="maxIdle" value="${maxIdle}"/> <property name="minIdle" value="${minIdle}"/> <property name="maxWait" value="${maxWait}"/> <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}"/> <property name="removeAbandoned" value="${removeAbandoned}"/> <property name="testWhileIdle" value="true"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="validationQuery" value="select 1"/> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <property name="numTestsPerEvictionRun" value="${maxActive}"/> </bean> <!-- 配置sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 添加对事务管理注解的支持 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 创建dao层 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.learn.springmvc03.dao"/> </bean> </beans> ``` (4)SpringMVC配置文件`resources/springmvc-servlet.xml`。 ```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:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 配置注解驱动 --> <mvc:annotation-driven/> <!-- 扫描controller层 --> <context:component-scan base-package="com.learn.springmvc03.controller"/> <!-- 配置JSP视图解析器 --> <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <!-- prefix和suffix共同决定jsp文件的位置 --> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> <property name="exposeContextBeansAsAttributes" value="true"/> </bean> <!-- 配置消息转换器 --> <mvc:annotation-driven> <mvc:message-converters> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <!-- 设置编码格式,防止中文乱码 --> <value>text/html;charset=UTF-8</value> <!-- 设置响应的数据格式 --> <value>application/json</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> </beans> ``` (5)log4j日志配置文件`resources/log4j.properties`。 ```properties log4j.rootLogger=debug,CONSOLE,file #log4j.rootLogger=ERROR,ROLLING_FILE log4j.logger.cn.smbms=debug log4j.logger.org.apache.ibatis=debug log4j.logger.org.mybatis.spring=debug log4j.logger.java.sql.Connection=debug log4j.logger.java.sql.Statement=debug log4j.logger.java.sql.PreparedStatement=debug log4j.logger.java.sql.ResultSet=debug ###################################################################################### # Console Appender 日志在控制输出配置 ###################################################################################### log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.Threshold=debug log4j.appender.CONSOLE.DatePattern=yyyy-MM-dd log4j.appender.CONSOLE.Target=System.out log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern= - (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n ###################################################################################### # Rolling File 文件大小到达指定尺寸的时候产生一个新的文件 ###################################################################################### #log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender #log4j.appender.ROLLING_FILE.Threshold=INFO #log4j.appender.ROLLING_FILE.File=${baojia.root}/logs/log.log #log4j.appender.ROLLING_FILE.Append=true #log4j.appender.ROLLING_FILE.MaxFileSize=5000KB #log4j.appender.ROLLING_FILE.MaxBackupIndex=100 #log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout #log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n ###################################################################################### # DailyRolling File 每天产生一个日志文件,文件名格式:log2009-09-11 ###################################################################################### log4j.appender.file=org.apache.log4j.DailyRollingFileAppender log4j.appender.file.DatePattern=yyyy-MM-dd log4j.appender.file.File=${SMBMS_C09_04.root}/logs/log.log log4j.appender.file.Append=true log4j.appender.file.Threshold=debug log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern= - (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n #DWR 日志 #log4j.logger.org.directwebremoting = ERROR #显示Hibernate占位符绑定值及返回值 #log4j.logger.org.hibernate.type=DEBUG,CONSOLE #log4j.logger.org.springframework.transaction=DEBUG #log4j.logger.org.hibernate=DEBUG #log4j.logger.org.acegisecurity=DEBUG #log4j.logger.org.apache.myfaces=TRACE #log4j.logger.org.quartz=DEBUG #log4j.logger.com.opensymphony=INFO #log4j.logger.org.apache.struts2=DEBUG log4j.logger.com.opensymphony.xwork2=debug ``` (6)Servlet配置文件`webapp/WEB-INF/web.xml`。 ```xml <?xml version="1.0" encoding="UTF-8"?> <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"> <display-name>Archetype Created Web Application</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置DispatchServlet核心控制器 --> <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-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 引入applicationContext.xml配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/applicationContext.xml</param-value> </context-param> <listener> <!-- ContextLoaderListener组件用来扫描applicationContext.xml文件 --> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置过滤器 --> <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>webAppRootKey</param-name> <param-value>SpringMVC-Mybatis.root</param-value> </context-param> </web-app> ``` **3. pojo实体层** ```java @Data @NoArgsConstructor public class Student { private Integer id; private String name; private Integer age; private String gender; } ``` **4. dao层** ```java public interface StudentDao { Student findById(Integer id); } ``` *`resources/mapper/UserMapper.xml`* ```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.learn.springmvc03.dao.StudentDao"> <select id="findById" parameterType="integer" resultType="student"> select id,`name`,age,gender from `student` where id=#{id} </select> </mapper> ``` **5. controller层** ```java @Controller @RequestMapping("/student") public class StudentController { @Autowired private StudentDao studentDao; @ResponseBody @RequestMapping("/find/{id}") public Student findById(@PathVariable("id")Integer id) { Student student = studentDao.findById(id); System.out.println(student); //Student(id=1, name=张三, age=25, gender=男生) return student; } } ```