文章目录

    • 🏴‍☠️SpringMVC简介
        • SpringMVC是什么
        • SpringMVC的基础架构
        • SpringMVC的优点
    • 🏳️‍🌈SpringMVC接管Web
        • 说明
        • 三层框架
        • SpringMVC的简单开发
    • 🚩Spring搭建
    • 🚩Mybatis搭建
    • 🏁 Spring整合Mybatis
    • ✅结语

🌕博客x主页:己不由心王道长🌕!
🌎文章说明:Spring+SpringMVC🌎
✅系列专栏:Spring
🌴本篇内容:使用Spring、SpringMVC对以前做过的项目进行重新整合和介绍。🌴
☕️每日一语:宁愿因做自己而招人厌恶,也不愿为了迎合他人而伪装自己,懂你的人会留下来,不懂你的人,你祈求不来。因为别人活得不快乐,不如为了自己活得更自由。☕️
🕤作者详情:作者是一名双非大三在校生,喜欢Java,欢迎大家探讨学习,喜欢的话请给博主一个三连鼓励。🕤

🏴‍☠️SpringMVC简介

SpringMVC是什么

一、Springmvc是Spring框架的一个模块,是一个基于MVC架构风格的Web层框架
一个应用大概可以分为四个层面应用层、Web层、业务层、持久层
【Spring+SpringMVC+Mybatis】Spring+SpringMVC+Mybatis实现前端到后台完整项目
二、SpringMVC是一种基于Java实现轻量级Web框架,并且可以与Spring无缝契合。
MVC架构: M即model,V是view,C是control;即模型、视图、控制器

SpringMVC的基础架构

一、SpringMVC核心架构图
【Spring+SpringMVC+Mybatis】Spring+SpringMVC+Mybatis实现前端到后台完整项目

二、SpringMVC核心架构具体流程分析
①前端浏览器发送请求首先到达DispatcherServlet,DispatcherServlet收到请求并不做处理;
②DispatcherServlet不做处理,但是会委托HandlerMapping(处理器映射器)进行处理,HandlerMapping会把收到的请求映射HandlerExcutionCha(一个处理器对象和多个拦截器)对象返回给DispatcherServlet;
③DispatcherServlet把(handler)处理器对象发送给处理器适配器包装成适配器;
④处理器适配器去执行Handler;
⑤Handler执行完成给适配器返回ModelAndView;
⑥处理器适配器向前端控制器返回ModelAndView;
⑦前端控制器收到ModelAndView后调用视图解析器对ModelAndView进行解析;
⑧视图解析器解析完成后返回给前端控制器一个View对象;
⑨前端控制器收到View以后解析,并对视图进行渲染;
⑩渲染完成后,前端控制器把视图响应给客户端;

注意:这里的handler说明白点就是我们写的controller层的代码

三、SpringMVC核心架构具体流程组件解析
1、前端控制器DispatcherServlet
作用是接收请求,响应结果,并对各个组件进行调用,减少组件之间的耦合性。

2、处理器映射器HandlerMapping
作用是根据前端请求的url查找对应的Handler。

3、处理器适配器HandlerAdapter
作用是按照特定规则去执行Handler。

4、处理器Handler
由我们程序员编写,执行逻辑要符合处理器适配器HandlerAdapter的要求。

5、视图解析器ViewResolver
作用是进行视图解析,根据逻辑视图名解析成真正的视图。

6、视图View
View是一个接口,实现类支持不同的View类型

SpringMVC的优点

一、 SpringMVC是Spring框架的一部分,可以方便的利用Spring所提供的其他功能。这是一个极大的好处,完美融入了Spring提供的生态圈。
二、SpringMVC灵活性强,易于与其他框架集成。同样也是因为在Spring生态圈中,因为Spring的IOC容器可以便于与其他框架整合,因此,SpringMVC得到了相应的好处。
三、可自动绑定用户输入,并能正确的转换数据类型。在用的SpringMVC时我们会发现,参数的值是SpringMVC帮助绑定注入的。
四、支持多种视图技术。它支持JSP、Velocity和FreeMarker等视图技术。
五、支持国际化。可以根据用户区域显示多国语言。
除上述几个优点外,Spring MVC还有很多其他优点,由于篇幅有限,这里就不一一列举了。主要是我们用的过程中自己去体会。

🏳️‍🌈SpringMVC接管Web

说明

SpringMVC接管Web,其实就是SpringMVC应用,上面介绍了,这里就得进行联系,并且是小项目式的。

三层框架

【Spring+SpringMVC+Mybatis】Spring+SpringMVC+Mybatis实现前端到后台完整项目
值得注意的是mapper层是没有实现类的,因为要用到反射和代理

SpringMVC的简单开发

① 导入SpringMVC相关坐标:去maven的重要仓库,搜索Spring webMVC
:mvnrepository

【Spring+SpringMVC+Mybatis】Spring+SpringMVC+Mybatis实现前端到后台完整项目
导入到项目中:
【Spring+SpringMVC+Mybatis】Spring+SpringMVC+Mybatis实现前端到后台完整项目

②配置SpringMVC核心控制器DispatcherServlet

<?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_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>//表示启动时初始化该servlet
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

③ 创建Controller类和视图页面
Controller类就是handler(处理器),是我们自己编写的,再直白点,就是写在三层架构中的Controller层中的类。
【Spring+SpringMVC+Mybatis】Spring+SpringMVC+Mybatis实现前端到后台完整项目
创建Controller类

package com.bipt.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
 * @author 不止于梦想
 * @date 2022/10/10 20:43
 */
@RequestMapping("/user")
@Controller
public class UserController {
    @RequestMapping("/login")
    public ModelAndView loginController(){
        return null;
    }
    @RequestMapping("/register")
    public ModelAndView registerController(){
        return null;
    }
}

导入视图页面这里的视图还是我的免登录时长两天半所用到的页面

【Spring+SpringMVC+Mybatis】Spring+SpringMVC+Mybatis实现前端到后台完整项目

④使用注解配置Controller类中的业务方法的映射地址

package com.bipt.controller;
import com.bipt.pojo.User;
import com.bipt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
/**
 * @author 不止于梦想
 * @date 2022/10/10 20:43
 */
@RequestMapping("/user")
@Controller
public class UserController {
   @Autowired
   private UserService service;
    @RequestMapping("/login")
    public ModelAndView login(String username, String password,HttpSession httpSession) {
        ModelAndView mv = new ModelAndView();
        //调用查询方法,返回对象
        User user = service.login(username, password);
        if (user != null) {//不为空,专访到欢迎页面
            mv.setViewName("welcome");
            httpSession.setAttribute("user", user);
            return mv;
        }else {
            mv.setViewName("login");
            mv.addObject("error","您输入的账号或密码有错误,请重新输入");
            return mv;
        }
    }
    @RequestMapping("/register")
    public ModelAndView register(String username, String password,HttpSession httpSession){
        ModelAndView mv = new ModelAndView();
        //调用查询方法,返回对象
        int i = service.register(username, password);
        if(i!=1){//i不等于1,表示注册失败
            //跳转到注册界面,并给出提示信息
            mv.addObject("error","不知名错误,注册失败,请重新注册");
            mv.setViewName("register");
            return mv;
        }else {
            mv.setViewName("login");
            return  mv;
        }
    }
}

⑤ 配置SpringMVC核心配置文件spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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 https://www.springframework.org/schema/context/spring-context.xsd">
    <!--配置注解驱动-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--配置静态资源放行-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--设置默认,即在webapp路径下-->
        <property name="prefix" value="/"></property>
        <!--设置后缀为.jsp访问jsp的页面-->
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--配置包扫描,把组件添加到SpringMVC容器中-->
    <context:component-scan base-package="com.bipt.controller"></context:component-scan>
</beans>

🚩Spring搭建

①创建Service层接口并对Web层的方法进行对应的创建

package com.bipt.service;
import com.bipt.pojo.User;
/**
 * @author 不止于梦想
 * @date 2022/10/10 22:30
 */
public interface UserService {
    User login(String username,String password);
    int register(String username,String password);
}

②创建Service层接口的实现类实现接口方法并对方法进行改造

package com.bipt.service.impl;
import com.bipt.mapper.UserMapper;
import com.bipt.pojo.User;
import com.bipt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * @author 不止于梦想
 * @date 2022/10/10 22:34
 */
@Service
public class ImplUserService implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User login(String username, String password) {
        User user = userMapper.select(username, password);
        return user;
    }
    @Override
    public int register(String username, String password) {
       int i = userMapper.insert(username, password);
       return i;
    }
}

创建spring的核心配置文件:applicationContext.xml
配置基本属性,集成Mybatis得先创建Mybatis:

<?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 https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--添加包扫描、并排除Controller-->
    <context:component-scan base-package="com.bipt">
        <context:exclude-filter type="annotation" expression="com.bipt.controller"/>
    </context:component-scan>
    <!--导入配置文件-->
    <context:property-placeholder location=" classpath:config.properties"></context:property-placeholder>
    <!--配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--添加注解驱动-->
   <context:annotation-config></context:annotation-config>
    <!--添加静态资源访问-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>
</beans>

在上面记得添加包扫描,我们用的是注解添加bean的方式。

🚩Mybatis搭建

一、导入Mybatis依赖和Mybatis-spring依赖,因为后面需要在spring中集成Mybatis。
【Spring+SpringMVC+Mybatis】Spring+SpringMVC+Mybatis实现前端到后台完整项目
二、新建Mybatis配置文件,这里比较熟悉可以直接在Spring中配置。不过为了shui,我新建一个。

<?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>
    <!--导入配置文件-->
    <properties resource="config.properties"></properties>
    <!--设置实体类别名-->
    <typeAliases>
        <package name="com.bipt.pojo"/>
    </typeAliases>
    <!--设置环境-->
    <environments default="development">
        <environment id="development">
            <!--事务管理器-->
            <transactionManager type="JDBC"></transactionManager>
            <!--数据源类型-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com/bipt/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

三、编写mapper层接口,编写mapper层接口的映射文件,如mapper接口叫做UserMapper,则xml文件为UserMapper.xml。

package com.bipt.mapper;
import com.bipt.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
/**
 * @author 不止于梦想
 * @date 2022/10/10 22:36
 */
@Repository
public interface UserMapper {
    User select(@Param("username") String username, @Param("password")String password);
    int insert(@Param("username")String username,@Param("password")String password);
}

四、编写mapper层接口的映射文件

<?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.bipt.mapper.UserMapper">
    <select id="select" resultType="user" >
    select username,password from tbl_user where username=#{username} and password=#{password};
    </select>
    <insert id="insert" >
        insert into tbl_user values(username,password);
    </insert>
</mapper>

并在核心配置文件中进行注册。

🏁 Spring整合Mybatis

一、Spring整合Mybatis
整理流程就是把Mybatis的SqlSessionFactory核心对象交给springIOC容器创建和管理。
① 导入配置文件到Spring核心配置文件
添加连接池对象、创建数据源。

【Spring+SpringMVC+Mybatis】Spring+SpringMVC+Mybatis实现前端到后台完整项目

②配置SqlSessionFactoryBean
【Spring+SpringMVC+Mybatis】Spring+SpringMVC+Mybatis实现前端到后台完整项目

③ 添加扫描器
【Spring+SpringMVC+Mybatis】Spring+SpringMVC+Mybatis实现前端到后台完整项目

二、添加事务管理

事务分为声明式事务和编程式事务,编程式事务就是JDBC的事务提交、回滚等等,这样不太方便,我们有很多的方法都要用到事务,不能需要一个就编写一个,这样太重复了。我们可以把事务抽取出来,利用Spring提高的声明式事务管理来处理。
Spring声明式事务是基于AOP(面向切面)实现的
① 配置事务管理器
事务管理器有很多种,不同的数据访问层框架有不同的实现,而Mybatis的事务管理器为:DataSourceTransactionManager
【Spring+SpringMVC+Mybatis】Spring+SpringMVC+Mybatis实现前端到后台完整项目
②配置事务增强/通知(Advice)
【Spring+SpringMVC+Mybatis】Spring+SpringMVC+Mybatis实现前端到后台完整项目
③ 配置切面
【Spring+SpringMVC+Mybatis】Spring+SpringMVC+Mybatis实现前端到后台完整项目

配置代码:

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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">
    <!--添加包扫描、并排除Controller-->
    <context:component-scan base-package="com.bipt.service">
        <context:exclude-filter type="annotation" expression="com.bipt.controller"/>
    </context:component-scan>
    <!--导入配置文件-->
    <context:property-placeholder location=" classpath:config.properties"></context:property-placeholder>
    <!--配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--添加注解驱动-->
   <context:annotation-config></context:annotation-config>
    <!--配置sqlsession工厂对象-->
    <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--导入数据源-->
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:SqlMapconfig.xml"></property>
    </bean>
    <!--4. 扫描映射器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bipt.mapper"></property>
    </bean>
    <!--配置事务管理器-->
    <bean id="transactionManager" class="
    org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置事务增强-->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="login*"  read-only="true"/>
            <tx:method name="register*" propagation="REQUIRED" rollback-for="Exception,RuntimeException" read-only="false"/>
        </tx:attributes>
    </tx:advice>
    <!--配置切面-->
    <aop:config>
        <aop:advisor advice-ref="transactionAdvice" pointcut-ref="transactionPointcut"></aop:advisor>
        <aop:aspect ref="dataSource">
            <aop:pointcut id="transactionPointcut" expression="execution(* com.bipt.service.*.*(..)) "/>
        </aop:aspect>
    </aop:config>
</beans>

✅结语

你被骗了,没有结语

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。