龙空技术网

Spring整合Mybatis、SpringMVC

java程序员面试 58

前言:

此刻姐妹们对“jsbean”大概比较关心,你们都想要学习一些“jsbean”的相关知识。那么小编在网络上网罗了一些对于“jsbean””的相关文章,希望大家能喜欢,我们快快来了解一下吧!

记录配置的过程。

SSM框架整合首先是配置Mybatis

新建maven项目

在pom.xml引入需要依赖的包

<?xml version="1.0" encoding="UTF-8"?><project xmlns=";         xmlns:xsi=";         xsi:schemaLocation=" ;>    <modelVersion>4.0.0</modelVersion>    <groupId>com.wtl</groupId>    <artifactId>ssmbuild</artifactId>    <version>1.0-SNAPSHOT</version>    <properties>        <maven.compiler.source>8</maven.compiler.source>        <maven.compiler.target>8</maven.compiler.target>    </properties><!--    javaweb支持-->    <dependencies>        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>servlet-api</artifactId>            <version>2.5</version>        </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><!--        spring-->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-webmvc</artifactId>            <version>5.1.9.RELEASE</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context</artifactId>            <version>5.1.9.RELEASE</version>        </dependency>        <dependency>            <groupId>org.aspectj</groupId>            <artifactId>aspectjweaver</artifactId>            <version>1.9.4</version>        </dependency><!--        lombok-->        <dependency>            <groupId>org.projectlombok</groupId>            <artifactId>lombok</artifactId>            <version>1.16.10</version>        </dependency><!--        json解析-->        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-databind</artifactId>            <version>2.10.0</version>        </dependency><!--        数据库-->        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis</artifactId>            <version>3.5.2</version>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>8.0.19</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-jdbc</artifactId>            <version>5.1.9.RELEASE</version>        </dependency>        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis-spring</artifactId>            <version>2.0.2</version>        </dependency><!--        单元测试-->        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>4.7</version>        </dependency><!--        数据库连接池-->        <dependency>            <groupId>com.mchange</groupId>            <artifactId>c3p0</artifactId>            <version>0.9.5.2 </version>        </dependency><!--        日志-->        <dependency>            <groupId>log4j</groupId>            <artifactId>log4j</artifactId>            <version>1.2.17</version>        </dependency>    </dependencies><!--    静态资源-->    <build>        <resources>            <resource>                <directory>src/main/resources</directory>                <includes>                    <include>**/*.properties</include>                    <include>**/*.xml</include>                </includes>                <filtering>true</filtering>            </resource>            <resource>                <directory>src/main/java</directory>                <includes>                    <include>**/*.properties</include>                    <include>**/*.xml</include>                </includes>                <filtering>true</filtering>            </resource>        </resources>    </build></project>

加载包

加载完成

新建mybatis-config.xml、spring-dao.xml、applicationContext.xml

mybatis-config.xml

数据库链接相关配置转移到了spring-dao.xml去配置,这里只配置settings

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"        ";><configuration>    <settings>        <setting name="logImpl" value="LOG4J"/>        <setting name="mapUnderscoreToCamelCase" value="true"/>        <setting name="cacheEnabled" value="true"/>    </settings></configuration>

spring-dao.xml

这里配置自动注入sqlsession、填充接口imp、mapper。

<?xml version="1.0" encoding="UTF-8"?><beans xmlns=";       xmlns:xsi=";       xmlns:aop=";       xsi:schemaLocation="                     ;>    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>        <property name="url" value="jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=CST"></property>        <property name="username" value="root"></property>        <property name="password" value="bzm00000"></property>    </bean>    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=CST"></property>        <property name="user" value="root"></property>        <property name="password" value="bzm00000"></property>        <property name="maxPoolSize" value="30"></property>        <property name="minPoolSize" value="10"></property>        <property name="autoCommitOnClose" value="false"></property>        <property name="checkoutTimeout" value="10000"></property>        <property name="acquireRetryAttempts" value="2"></property>    </bean>    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <property name="dataSource" ref="dataSource"></property>        <property name="configLocation" value="classpath:mybatis-config.xml"></property>        <property name="mapperLocations" value="classpath:com/wtl/dao/BookMapper.xml"></property>    </bean>    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">        <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>    </bean>    <!--        自动装填impl-->    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>        <property name="basePackage" value="com.wtl.dao"></property>    </bean>    <aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>

applicationcontext.xml

配置的总文件,在web.xml文件中依赖它,就依赖了所有的xml文件。起一个类似汇总.h文件的作用。

<?xml version="1.0" encoding="UTF-8"?><beans xmlns=";       xmlns:xsi=";       xmlns:aop=";       xsi:schemaLocation="                     ;>    <import resource="spring-dao.xml"></import>    <import resource="spring-service.xml"></import>    <import resource="spring-mvc.xml"></import>    <aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>

配置上下文

idea链接数据库

测试连通性

勾选要链接的database

提交,可以看到表的结构

构建基本的包结构

使用lombok注解,省去写getter/setter以及有参无参构造函数

编写接口和mapper

BookMapper.xml

bookMapper要注册到spring-dao.xml中的mapperlocation中

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"        ";><mapper namespace="com.wtl.dao.BookMapper">    <select id="queryBookById" resultType="com.wtl.pojo.Book">        select *from books where book_id = #{id}    </select>    <select id="queryAllBooks" resultType="com.wtl.pojo.Book">        select  *from books    </select>    <insert id="addBook" parameterType="com.wtl.pojo.Book">        insert into books(book_name, book_counts, detail) values(#{bookName}, #{bookCounts}, #{detail});    </insert>    <delete id="deleteBookById" parameterType="int">        delete from books where book_id = #{id}    </delete>    <update id="updateBook" parameterType="com.wtl.pojo.Book">        update books set book_name=#{bookName}, book_counts=#{bookCounts}, detail=#{detail}        where book_id=#{bookId};    </update>    <select id="queryBookByName" parameterType="String" resultType="com.wtl.pojo.Book">        select *from books where book_name like '%${bookName}%';    </select></mapper>

spring会自动填充接口,我们不需要实现bookMapper接口

编写service相关代码

<?xml version="1.0" encoding="UTF-8"?><beans xmlns=";       xmlns:xsi=";       xmlns:context=";       xsi:schemaLocation="                     ;>    <context:component-scan base-package="com.wtl.service"></context:component-scan>    <bean id="BookServiceImp" class="com.wtl.service.BookServiceImp">        <property name="bookMapper" ref="bookMapper"></property>    </bean>    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource"></property>    </bean></beans>

编写测试类,测试dao层

可以配置log4j日志框架,查看执行的sql

在mybatis-config里

在resourece目录下创建log4j.properties

# priority  :debug<info<warn<error#you cannot specify every priority with different file for log4jlog4j.rootLogger=debug,stdout,info,debug,warn,error #consolelog4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern= [%d{yyyy-MM-dd HH:mm:ss a}]:%p %l%m%n#info loglog4j.logger.info=infolog4j.appender.info=org.apache.log4j.DailyRollingFileAppender log4j.appender.info.DatePattern='_'yyyy-MM-dd'.log'log4j.appender.info.File=./src/com/autohome/log/info.loglog4j.appender.info.Append=truelog4j.appender.info.Threshold=INFOlog4j.appender.info.layout=org.apache.log4j.PatternLayout log4j.appender.info.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n#debug loglog4j.logger.debug=debuglog4j.appender.debug=org.apache.log4j.DailyRollingFileAppender log4j.appender.debug.DatePattern='_'yyyy-MM-dd'.log'log4j.appender.debug.File=./src/com/autohome/log/debug.loglog4j.appender.debug.Append=truelog4j.appender.debug.Threshold=DEBUGlog4j.appender.debug.layout=org.apache.log4j.PatternLayout log4j.appender.debug.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n#warn loglog4j.logger.warn=warnlog4j.appender.warn=org.apache.log4j.DailyRollingFileAppender log4j.appender.warn.DatePattern='_'yyyy-MM-dd'.log'log4j.appender.warn.File=./src/com/autohome/log/warn.loglog4j.appender.warn.Append=truelog4j.appender.warn.Threshold=WARNlog4j.appender.warn.layout=org.apache.log4j.PatternLayout log4j.appender.warn.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n#errorlog4j.logger.error=errorlog4j.appender.error = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.error.DatePattern='_'yyyy-MM-dd'.log'log4j.appender.error.File = ./src/com/autohome/log/error.log log4j.appender.error.Append = truelog4j.appender.error.Threshold = ERROR log4j.appender.error.layout = org.apache.log4j.PatternLayoutlog4j.appender.error.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n

至此,mybatis配置完毕。接下来配置SpringMVC

springMVC

添加web支持

在项目结构里添加lib文件夹,引入所有的jar包,否则运行时会报找不到class异常。

在web.xml文件里添加spring的dispatchServlet接管servlet分发

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns=";         xmlns:xsi=";         xsi:schemaLocation=" ;         version="4.0">    <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:applicationContext.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><!--    乱码过滤-->    <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>    <session-config>        <session-timeout>15</session-timeout>    </session-config></web-app>

创建spring-mvc.xml文件

<?xml version="1.0" encoding="UTF-8"?><beans xmlns=";       xmlns:xsi=";       xmlns:aop=";       xmlns:mvc=";       xmlns:context=";       xsi:schemaLocation="                                     ;>    <!--    注解驱动-->    <mvc:annotation-driven></mvc:annotation-driven>    <!--    静态资源过滤-->    <mvc:default-servlet-handler></mvc:default-servlet-handler>    <!--    扫描包-->    <context:component-scan base-package="com.wtl.controller">    </context:component-scan>    <!--    视图解析器-->    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="suffix" value=".jsp"></property>        <property name="prefix" value="/WEB-INF/jsp/"></property>    </bean>    <aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>

默认支持返回资源为 WEB-INF/jsp下的.jsp文件。

可以编写controller了。

@RequestMapping对应访问的路径。

@Controller 由Spring托管生命周期。

返回的hello字符串会访问 /jsp/hello.jsp

我们在此生成一个jsp文件。

配置run config

新增tomocat

点击fix

添加我们的项目到web服务器中

前缀路径

运行,打开

至此,配置完成,可以写一些基础业务

标签: #jsbean