Day_07 Spring

文章目录

      • 01-事务的传播行为(掌握)
      • 02-事务传播行为演示(掌握)
      • 03-Spring整合MyBatis概述(掌握)
      • 04-Spring整合Mybatis之传统dao方式基础版(掌握)
      • 05-Spring整合Mybatis之传统dao方式优化版(掌握)
      • 06-Spring整合Mybatis之传统dao方式终极版(掌握)
      • 07-Spring整合MyBatis之接口代理方式基础版(掌握)
      • 08-Spring整合MyBatis之接口代理方式优化版(掌握)
      • 09-手撕SpringMVC框架第一版(掌握)
      • 10-手撕SpringMVC框架第二版(掌握)
      • 11-手撕SpringMVC框架第三版(掌握)
      • 12-手撕SpringMVC框架终极版(掌握)
      • 13-SpringMVC概述(掌握)
      • 14-SpringMVC入门案例(掌握)
      • 15-SpringMVC的执行流程(掌握)
      • 16-SpringMVC核心组件说明(掌握)
      • 17-SpringMVC核心组件配置(掌握)
      • 18-静态资源放行(掌握)
      • 19-@RequestMapping注解概述(掌握)
      • 20-@RequestMapping注解之匹配方式(掌握)
      • 21-@RequestMapping注解之窄化请求(掌握)
      • 22-@RequestMapping注解之请求方式(掌握)
      • 23-@RequestMapping注解限制请求参数(掌握 )
      • 24-请求参数绑定概述(掌握)
      • 25-请求参数绑定之简单类型(掌握)
      • 26-@RequestParam注解(掌握)
      • 27-请求参数绑定之实体类(掌握)

01-事务的传播行为(掌握)

  • 概述
    • Day_07 Spring_第1张图片
    • 事务管理员和事务协调员之间的事务的关系.
  • 传播行为
    • Day_07 Spring_第2张图片

02-事务传播行为演示(掌握)

  • 代码实现

    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserDao userDao;
    
        @Autowired
        private LogService logService;
    
    
        /**
         * 事务管理员
         * @param outName : 出账人
         * @param inName : 入账人
         * @param money : 金额
         * @throws Exception
         */
        //@Transactional(readOnly = false)
        public void transfer(String outName, String inName, Double money) throws Exception {
    
            logService.addLog("UserServiceImpl transfer");
    
            //出账
            userDao.outMoney(outName, money);
    
            //System.out.println(1 / 0);
    
            //入账
            userDao.inMoney(inName, money);
    
        }
    }
    
    @Service
    public class LogServiceImpl implements LogService {
    
        @Autowired
        private LogDao logDao;
    
    
        /**
         * 事务协调员
         *
         * @param content
         * @throws Exception
         */
        @Transactional(propagation = Propagation.MANDATORY)
        public void addLog(String content) throws Exception {
            logDao.addLog(content, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            //System.out.println(1 / 0);
        }
    }
    

03-Spring整合MyBatis概述(掌握)

  • Spring整合MyBatis
    • ①传统dao开发
    • ②接口代理开发
  • ①传统dao开发
    • dao接口 + dao实现子类 + mapper映射文件
    • dao实现子类对象交给Spring容器管理
  • ②接口代理开发
    • dao接口 + mapper映射文件
    • dao接口代理对象交给Spring容器管理

04-Spring整合Mybatis之传统dao方式基础版(掌握)

本质 :将dao的实现子类放到spring容器中

  • 开发步骤

    • ①引入依赖
    • ②定义dao接口及其实现子类
    • ③编写spring.xml
      • 扫描注解
      • 将SqlSessionFactory对象放入到IOC容器
        • 加载mybaits-config.xml
        • 注入dataSource
      • 将DruidDataSource对象放入到IOC容器
        • 注入driverClassName,url,username,password
    • ④编写mybatis-config.xml
      • 取别名
      • 加载UserDao.xml
    • ⑤编写UserDao.xml
      • selectUserList
      • addUser
    • ⑥代码测试
  • ①引入依赖

    <dependencies>
    
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.2version>
        dependency>
    
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.22version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>5.3.16version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-beansartifactId>
            <version>5.3.16version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.3.16version>
        dependency>
    
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-expressionartifactId>
            <version>5.3.16version>
        dependency>
    
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>5.3.16version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jclartifactId>
            <version>5.3.16version>
        dependency>
    
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aopartifactId>
            <version>5.3.16version>
        dependency>
    
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aspectsartifactId>
            <version>5.3.16version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.3.16version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.2.8version>
        dependency>
    
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.49version>
        dependency>
    
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.9version>
        dependency>
    
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.7version>
        dependency>
    
    dependencies>
    
  • ②定义dao接口及其实现子类

    @Repository
    public class UserDaoImpl implements UserDao {
    
    
        @Autowired
        private SqlSessionFactory sqlSessionFactory;//由Spring容器传入
    
        public int addUser(User inputUser) throws Exception {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            int addUser = sqlSession.update("addUser", inputUser);
            sqlSession.commit();
            sqlSession.close();
            return addUser;
        }
    
    
        public List<User> selectUserList() throws Exception {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            List<User> userList = sqlSession.selectList("selectUserList");
            sqlSession.close();
            return userList;
        }
    }
    
  • ③编写spring.xml

    
    <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"
           xsi:schemaLocation="
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:component-scan base-package="com.panghu">context:component-scan>
    
        <bean class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource">property>
            
            <property name="configLocation" value="mybatis-config.xml">property>
        bean>
    
        <context:property-placeholder location="jdbc.properties">context:property-placeholder>
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${driverClassName}">property>
            <property name="url" value="${jdbcUrl}">property>
            <property name="username" value="${user}">property>
            <property name="password" value="${password}">property>
        bean>
    
    
    beans>
    
  • ④编写mybatis-config.xml

    
    DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
        <typeAliases>
            <package name="com.panghu.pojo"/>
        typeAliases>
        <mappers>
            
            <mapper resource="com/panghu/dao/UserDao.xml"/>
        mappers>
    
    configuration>
    
  • ⑤编写UserDao.xml

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.panghu.dao.UserDao">
        <select id="selectUserList" resultType="com.panghu.pojo.User">
            select * from t_user
        select>
    
        <insert id="addUser">
            insert into t_user values (null, #{userName},#{userPwd},#{money},#{address});
        insert>
    mapper>
    
  • ⑥代码测试

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:spring.xml")
    public class UserDaoTest {
    
        @Autowired
        private UserDao userDao;
    
        @Test
        public void addUser() {
        }
    
        @Test
        public void selectUserList() throws Exception {
            List<User> userList = userDao.selectUserList();
            System.out.println("userList = " + userList);
        }
    }
    

05-Spring整合Mybatis之传统dao方式优化版(掌握)

  • 代码实现

    @Repository
    public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
    
    
        @Autowired
        @Override
        public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
            //调用SqlSessionDaoSupport的setSqlSessionFactory方法
            super.setSqlSessionFactory(sqlSessionFactory);
        }
    
        public int addUser(User inputUser) throws Exception {
            int addUser = getSqlSession().update("addUser", inputUser);
            return addUser;
        }
    
    
        public List<User> selectUserList() throws Exception {
            List<User> userList = getSqlSession().selectList("selectUserList");
            return userList;
        }
    }
    
    

06-Spring整合Mybatis之传统dao方式终极版(掌握)

  • 代码实现

    public class BaseDao extends SqlSessionDaoSupport {
    
        @Autowired
        @Override
        public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
            //调用SqlSessionDaoSupport的setSqlSessionFactory方法
            super.setSqlSessionFactory(sqlSessionFactory);
        }
    }
    
    
    @Repository
    public class UserDaoImpl extends BaseDao implements UserDao {
    
    
        public int addUser(User inputUser) throws Exception {
            int addUser = getSqlSession().update("addUser", inputUser);
            return addUser;
        }
    
    
        public List<User> selectUserList() throws Exception {
            List<User> userList = getSqlSession().selectList("selectUserList");
            return userList;
        }
    }
    
    

07-Spring整合MyBatis之接口代理方式基础版(掌握)

  • 开发步骤

    • ①引入依赖
    • ②定义dao接口
    • ③编写spring.xml
      • 加载dao接口代理对象
        • 注入mapperInterface
        • 注入sqlSessionFactory
      • 将SqlSessionFactory对象放入到IOC容器
        • 加载mybaits-config.xml
        • 注入dataSource
      • 将DruidDataSource对象放入到IOC容器
        • 注入driverClassName,url,username,password
    • ④编写mybatis-config.xml
      • 取别名
      • 加载UserDao.xml
    • ⑤编写UserDao.xml
      • selectUserList
      • addUser
    • ⑥代码测试
  • ①引入依赖

  • ②定义dao接口

  • ③编写spring.xml

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        
        <bean class="org.mybatis.spring.mapper.MapperFactoryBean">
            
            <property name="mapperInterface" value="com.panghu.dao.UserDao">property>
            <property name="sqlSessionFactory" ref="sqlSessionFactory">property>
        bean>
    
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource">property>
            
            <property name="configLocation" value="mybatis-config.xml">property>
        bean>
    
        <context:property-placeholder location="jdbc.properties">context:property-placeholder>
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${driverClassName}">property>
            <property name="url" value="${jdbcUrl}">property>
            <property name="username" value="${user}">property>
            <property name="password" value="${password}">property>
        bean>
    
    
    beans>
    
    
  • ④编写mybatis-config.xml

    
    DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
        <typeAliases>
            <package name="com.panghu.pojo"/>
        typeAliases>
    
    configuration>
    
    
  • ⑤编写UserDao.xml

  • ⑥代码测试

08-Spring整合MyBatis之接口代理方式优化版(掌握)

  • 代码实现

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        
    
    
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.panghu.dao">property>
        bean>
    
    
    
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource">property>
            
            <property name="configLocation" value="mybatis-config.xml">property>
        bean>
    
        <context:property-placeholder location="jdbc.properties">context:property-placeholder>
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${driverClassName}">property>
            <property name="url" value="${jdbcUrl}">property>
            <property name="username" value="${user}">property>
            <property name="password" value="${password}">property>
        bean>
    
    
    beans>
    
    

09-手撕SpringMVC框架第一版(掌握)

  • 需求

    • 在javaWeb环境中使用Spring框架
  • 代码实现

    @WebServlet("/selectUserList")
    public class UserController extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
            UserService userService = applicationContext.getBean(UserService.class);
            try {
                List<User> userList = userService.selectUserList();
                System.out.println("userList = " + userList);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
    
  • 存在问题

    • 每请求一次UserController就创建一个Application对象.

10-手撕SpringMVC框架第二版(掌握)

  • 概述

  • 代码实现

    public class MyContextLoaderListener implements ServletContextListener {
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            //项目启动,创建ApplicationContext对象,并将其存放到ServletContext域对象中
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
            sce.getServletContext().setAttribute("applicationContext", applicationContext);
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            //项目关闭
        }
    }
    
    
    @WebServlet("/selectUserList")
    public class UserController extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ApplicationContext applicationContext = (ApplicationContext) getServletContext().getAttribute("applicationContext");
            UserService userService = applicationContext.getBean(UserService.class);
            try {
                List<User> userList = userService.selectUserList();
                System.out.println("userList = " + userList);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
    
  • 存在问题

    • ①spring.xml存在字符串的硬编码;
    • ②applicationContext在MyContextLoaderListener和UserController之间存在耦合

11-手撕SpringMVC框架第三版(掌握)

  • 概述

    • ①将spring.xml配置到web.xml中
  • 代码实现

    <web-app>
    
        <context-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring.xmlparam-value>
        context-param>
        <listener>
            <listener-class>com.panghu.listener.MyContextLoaderListenerlistener-class>
        listener>
    
    web-app>
    
    
    /**
    * SpringMVC团队写(oldqiu)
    */
    public class ApplicationContextConstant {
    
        public static final String APPLICATIONCONTEXT_NAME = "applicationContext";
    
    }
    
    
    /**
    * SpringMVC团队写(oldqiu)
    */
    public class MyApplicationContextUtils {
    
    
        public static ApplicationContext getApplicationContext(ServletContext servletContext){
            ApplicationContext applicationContext = (ApplicationContext) servletContext
                    .getAttribute(ApplicationContextConstant.APPLICATIONCONTEXT_NAME);
            return applicationContext;
        }
    
    }
    
    
    /**
    * SpringMVC团队写(oldqiu)
    */
    public class MyContextLoaderListener implements ServletContextListener {
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            //项目启动,创建ApplicationContext对象,并将其存放到ServletContext域对象中
            //获取全局初始化参数contextConfigLocation
            String contextConfigLocation = (String) sce.getServletContext().getInitParameter("contextConfigLocation");
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext(contextConfigLocation);
            sce.getServletContext().setAttribute(ApplicationContextConstant.APPLICATIONCONTEXT_NAME, applicationContext);
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            //项目关闭
        }
    }
    
    
    /**
    * 普通开发者(李冠鱼)
    */
    @WebServlet("/selectUserList")
    public class UserController extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ApplicationContext applicationContext = MyApplicationContextUtils.getApplicationContext(getServletContext());
            UserService userService = applicationContext.getBean(UserService.class);
            try {
                List<User> userList = userService.selectUserList();
                System.out.println("userList = " + userList);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
    
  • 存在问题

    • Servlet会越来越多,难以维护.

12-手撕SpringMVC框架终极版(掌握)

  • 代码实现

    <servlet>
        <servlet-name>mvcservlet-name>
        <servlet-class>com.panghu.controller.base.MyDispatcherServletservlet-class>
    servlet>
    
    <servlet-mapping>
        <servlet-name>mvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
    
    
    public class MyDispatcherServlet extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String requestURI = req.getRequestURI();
            String[] paths = requestURI.split("/");
            System.out.println("paths = " + paths);
            //获取对象名称,根据对象名称获取对应的bean
            String beanId = paths[2];
            ApplicationContext applicationContext = MyApplicationContextUtils.getApplicationContext(getServletContext());
            Object instance = applicationContext.getBean(beanId);
            //获取方法名称,执行对应的方法
            String methodName = paths[3];
            try {
                Method method = instance.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                method.invoke(instance,req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
    
    @Controller("userController")
    public class UserController {
    
    
        @Autowired
        private UserService userService;
    
        public void selectUserList(HttpServletRequest request , HttpServletResponse response) throws Exception {
            List<User> userList = userService.selectUserList();
            System.out.println("userList = " + userList);
        }
    
    
        public void addUser(HttpServletRequest request , HttpServletResponse response) throws Exception {
            userService.addUser(new User(null,"aaaa","aaaa",10000.0,"武汉市"));
        }
    
    }
    
    

13-SpringMVC概述(掌握)

  • 三层架构
    • Day_07 Spring_第3张图片
  • 概述
    • SpringMVC 是一种基于 Java 的实现 MVC 模型的轻量级 Web 框架。
    • SpringMVC 已经成为目前最主流的MVC框架之一,并且随着Spring3.0 的发布,全面超越 Struts2,成为最优秀的 MVC 框架。它通过一套注解,让一个简单的 Java 类成为处理请求的控制 器,而无须实现任何接口。同时它还支持 RESTful 编程风格的请求。

14-SpringMVC入门案例(掌握)

  • 开发步骤

    • ①引入依赖
    • ②编写web.xml,配置DispatcherServlet
      • 加载spring-mvc.xml
    • ③编写spring-mvc.xml
      • 扫描注解
      • 配置ThymeleafViewResolver视图解析器
    • ④定义UserController
    • ⑤编写user-list.html
  • ①引入依赖

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <junit.version>4.13.2junit.version>
        <lombok.version>1.18.22lombok.version>
        <spring.version>5.3.13spring.version>
        <logback.version>1.2.7logback.version>
        <slf4j.version>1.7.32slf4j.version>
        <servlet.version>4.0.1servlet.version>
        <thymeleaf.version>3.0.12.RELEASEthymeleaf.version>
    properties>
    
    <dependencies>
    
        
        <dependency>
            <groupId>org.thymeleafgroupId>
            <artifactId>thymeleaf-spring5artifactId>
            <version>${thymeleaf.version}version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>${servlet.version}version>
        dependency>
        
    
        
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-classicartifactId>
            <version>${logback.version}version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>${slf4j.version}version>
        dependency>
        
    
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>${junit.version}version>
            <scope>testscope>
        dependency>
        
    
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>${lombok.version}version>
        dependency>
        
    
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>${spring.version}version>
        dependency>
    
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aspectsartifactId>
            <version>${spring.version}version>
        dependency>
    
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>${spring.version}version>
        dependency>
        
    
    dependencies>
    
    
  • ②编写web.xml,配置DispatcherServlet

    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>
    
    
        
        <servlet>
            <servlet-name>mvcservlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
            
            <init-param>
                <param-name>contextConfigLocationparam-name>
                <param-value>classpath:spring-mvc.xmlparam-value>
            init-param>
        servlet>
        <servlet-mapping>
            <servlet-name>mvcservlet-name>
            <url-pattern>/url-pattern>
        servlet-mapping>
    
    web-app>
    
    
  • ③编写spring-mvc.xml

    
    <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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
    
        <context:component-scan base-package="com.panghu">context:component-scan>
    
    
        
        <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
            <property name="order" value="1"/>
            <property name="characterEncoding" value="UTF-8"/>
            <property name="templateEngine">
                <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                    <property name="templateResolver">
                        <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
    
                            
                            <property name="prefix" value="/WEB-INF/pages/"/>
    
                            
                            <property name="suffix" value=".html"/>
                            <property name="templateMode" value="HTML5"/>
                            <property name="characterEncoding" value="UTF-8" />
                        bean>
                    property>
                bean>
            property>
        bean>
    
    
    beans>
    
    
  • ④定义UserController

    @Controller
    public class UserController {
    
    
        @RequestMapping("/selectUserList")
        public ModelAndView selectUserList(){
            ModelAndView modelAndView = new ModelAndView();
            List<User> userList = new ArrayList<>();
            userList.add(new User(1,"张三","12345",10000.0,"码头"));
            userList.add(new User(2,"李四","12345",20000.0,"魔都"));
            userList.add(new User(3,"王五","12345",30000.0,"帝都"));
            userList.add(new User(4,"赵六","12345",40000.0,"NewYork"));
            userList.add(new User(5,"田七","12345",40000.0,"WashTon"));
            //相当于放到request域对象
            modelAndView.addObject("userList",userList);
            modelAndView.setViewName("user-list");
            return modelAndView;
        }
    
    }
    
    
  • ⑤编写user-list.html

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>用户列表title>
    head>
    <body>
    
    <ul>
    
        <li th:each="user : ${userList}" th:text="${user.userName}">li>
    
    ul>
    
    
    body>
    html>
    
    

15-SpringMVC的执行流程(掌握)

  • 执行流程
    • Day_07 Spring_第4张图片

16-SpringMVC核心组件说明(掌握)

  • 核心组件
    • ①DispatcherServlet : 前端控制器
      • 负责请求调度
    • ②HandlerMapping : 处理器映射器
      • 负责查询处理器执行链
    • ③HandlerAdaptor : 处理器适配器
      • 负责将请求匹配给对应的处理器
    • ④Handler : 处理器
      • 负责处理请求,并返回响应
    • ⑤ViewResolver : 视图解析器
      • 负责解析视图

17-SpringMVC核心组件配置(掌握)

  • 核心组件配置

    • ①DispatcherServlet : 前端控制器
      • 在web.xml配置
    • ②HandlerMapping : 处理器映射器
      • 系统默认配置
    • ③HandlerAdaptor : 处理器适配器
      • 系统默认配置
    • ④Handler : 处理器
      • 在UserController配置
    • ⑤ViewResolver : 视图解析器
      • 在spring-mvc.xml配置
  • 代码实现1

    
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">bean>
    
    
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">bean>
    
    
  • 代码实现2(推荐)

    <mvc:annotation-driven>mvc:annotation-driven>
    
    

18-静态资源放行(掌握)

  • 概述

    • DispatcherServlet 的 url-pattern 配置的是“/”,url-pattern 配置“/”表示整个 Web 应用范围内所有请求都由 SpringMVC 来处理,现在 images/mi.jpg 请求没有对应的Handler处理器, 所以返回 404
  • 代码实现1

    <mvc:resources mapping="/css/**" location="/css/">mvc:resources>
    <mvc:resources mapping="/html/**" location="/html/">mvc:resources>
    <mvc:resources mapping="/img/**" location="/img/">mvc:resources>
    <mvc:resources mapping="/js/**" location="/js/">mvc:resources>
    
    
  • 代码实现2(推荐)

    <mvc:default-servlet-handler>mvc:default-servlet-handler>
    
    

19-@RequestMapping注解概述(掌握)

  • 源码

    @Target({ElementType.TYPE, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Mapping
    public @interface RequestMapping {
    
    
       String name() default "";
    
       @AliasFor("path")
       String[] value() default {};//设置访问路径
    
    
       @AliasFor("value")
       String[] path() default {};//设置访问路径
    
    
       RequestMethod[] method() default {};//设置请求方式
    
    
       String[] params() default {};//设置请求参数
        
       String[] headers() default {};//设置请求头
    
    
    
    }
    
    
  • 作用

    • ①设置处理器的请求路径
    • ②设置请求方式
    • ③设置请求参数
    • ④窄化请求

20-@RequestMapping注解之匹配方式(掌握)

  • 代码实现

    /**
     * 20-@RequestMapping注解之匹配方式
     * ①精确匹配
     * @return
     */
    @RequestMapping("/request/test1")
    public ModelAndView test1(){
        System.out.println("RequestController test1");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }
    
    /**
     * ②模糊匹配
     * @return
     */
    @RequestMapping("/request/test2/*")
    public ModelAndView test2(){
        System.out.println("RequestController test2");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }
    
    

21-@RequestMapping注解之窄化请求(掌握)

  • 代码实现

    @Controller
    @RequestMapping("/request")
    public class RequestController {
    
    
        /**
         * 20-@RequestMapping注解之匹配方式
         * ①精确匹配
         * @return
         */
        @RequestMapping("/test1")
        public ModelAndView test1(){
            System.out.println("RequestController test1");
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("index");
            return modelAndView;
        }
    
        /**
         * ②模糊匹配
         * @return
         */
        @RequestMapping("/test2/*")
        public ModelAndView test2(){
            System.out.println("RequestController test2");
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("index");
            return modelAndView;
        }
    
    }
    
    

22-@RequestMapping注解之请求方式(掌握)

  • 代码实现

    //@RequestMapping(value = "/request/test3" ,method = RequestMethod.GET)
    @GetMapping("/request/test3")
    public ModelAndView test3(){
        System.out.println("RequestController test3");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }
    
    @RequestMapping(value = "/demo03.html" )
    public ModelAndView toDemo03Page(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("demo03");
        return modelAndView;
    }
    
    

23-@RequestMapping注解限制请求参数(掌握 )

  • 代码实现

    @RequestMapping(value = "/request/test4" ,params = {"username","password"})
    public ModelAndView test4(){
        System.out.println("RequestController test4");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }
    
    

24-请求参数绑定概述(掌握)

  • 概述
    • 表单提交的数据都是k=v格式的 username=haha&password=123
    • SpringMVC的参数绑定过程是把表单提交的请求参数,作为控制器方法的参数进行绑定的
  • 支持的类型
    • 简单类型
    • 实体类型
    • 容器类型

25-请求参数绑定之简单类型(掌握)

  • 需求

    • 完成用户登录
  • 代码实现

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>25-请求参数绑定之简单类型title>
    head>
    <body>
    <form th:action="@{/request/test5}" method="get">
        账户:<input type="text" name="username"><br>
        密码:<input type="text" name="password"><br>
        <button type="submit">提交button>
    
    form>
    
    body>
    html>
    
    
    @RequestMapping("/request/test5")
    public ModelAndView test5(String username , String password){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }
    
    
  • 注意事项

    • 表单中的name属性值必须和处理器方法上的形参名称一致!!!

26-@RequestParam注解(掌握)

  • 源码

    @Target(ElementType.PARAMETER)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface RequestParam {
    
       @AliasFor("name")
       String value() default "";//等价于name
    
    
       @AliasFor("value")
       String name() default "";//设置请求参数名称
    
    
       boolean required() default true;//设置请求参数是否必须
    
    
       String defaultValue() default ValueConstants.DEFAULT_NONE;//设置请求参数默认值
    
    }
    
    
  • 代码实现

    @RequestMapping("/request/test6")
    public ModelAndView test6(
            @RequestParam(name = "username" ,required = false ,defaultValue = "missing") String myUserName ,
            @RequestParam(name = "password",required = false,defaultValue = "missing") String myPassword){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }
    
    

27-请求参数绑定之实体类(掌握)

  • 代码实现

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>27-请求参数绑定之实体类</title>
    </head>
    <body>
    <form th:action="@{/request/test7}" method="get">
        账户:<input type="text" name="userName"><br>
        密码:<input type="text" name="userPwd"><br>
        <button type="submit">提交</button>
    
    </form>
    
    </body>
    </html>
    
    
    @RequestMapping("/demo07.html")
    public ModelAndView toDemo07Page(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("demo07");
        return modelAndView;
    }
    
    @RequestMapping("/request/test7")
    public ModelAndView test7(User inputUser){
        System.out.println("inputUser = " + inputUser);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }
    
    
  • 注意事项

    • 表单中的name属性值必须和实体类中的setXxx方法名保持一致!!!

你可能感兴趣的:(java,tomcat,maven,spring,java-ee)