Spring阶段一总结练习一(环境搭建和角色信息查询展示)

Spring阶段一总结练习一(环境搭建和角色信息查询展示),第1张

Spring阶段一总结练习 1、练习环境搭建
  1. 创建MaverWeb项目工程(spring_oneTest)

  2. 导入静态页面

    可联系获取

  3. 导入需要坐标

    <dependencies>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.32version>
        dependency>
        <dependency>
            <groupId>c3p0groupId>
            <artifactId>c3p0artifactId>
            <version>0.9.1.2version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.10version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.0.5.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>5.0.5.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <version>5.0.5.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.0.5.RELEASEversion>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.0.1version>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>javax.servlet.jsp-apiartifactId>
            <version>2.2.1version>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-coreartifactId>
            <version>2.9.0version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.9.0version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-annotationsartifactId>
            <version>2.9.0version>
        dependency>
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.3.1version>
        dependency>
        <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.3version>
        dependency>
        <dependency>
            <groupId>commons-logginggroupId>
            <artifactId>commons-loggingartifactId>
            <version>1.2version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>1.7.7version>
        dependency>
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.0.5.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>5.0.5.RELEASEversion>
        dependency>
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
    
    dependencies>
    
  4. 创建包结构(controller、service、dao、domain、utils)

    三层架构加实体对象包

  5. 导入数据库脚本

    创建数据库test执行下面的sql语句生成数据库表:角色表:sys_role、用户表:sys_user、用户角色关系表sys_user_role

    /*
    SQLyog Ultimate v12.09 (64 bit)
    MySQL - 5.7.24-log : Database - test
    *********************************************************************
    */
    
    /*!40101 SET NAMES utf8 */;
    
    /*!40101 SET SQL_MODE=''*/;
    
    /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
    /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
    /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
    /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
    CREATE DATABASE /*!32312 IF NOT EXISTS*/`test` /*!40100 DEFAULT CHARACTER SET utf8 */;
    
    USE `test`;
    
    /*Table structure for table `sys_role` */
    
    DROP TABLE IF EXISTS `sys_role`;
    
    CREATE TABLE `sys_role` (
      `id` bigint(20) NOT NULL AUTO_INCREMENT,
      `roleName` varchar(50) DEFAULT NULL,
      `roleDesc` varchar(50) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
    
    /*Data for the table `sys_role` */
    
    insert  into `sys_role`(`id`,`roleName`,`roleDesc`) values (1,'院长','负责全面工作'),(2,'研究员','课程研发工作'),(3,'讲师','授课工作'),(4,'助教','协助解决学生的问题');
    
    /*Table structure for table `sys_user` */
    
    DROP TABLE IF EXISTS `sys_user`;
    
    CREATE TABLE `sys_user` (
      `id` bigint(20) NOT NULL AUTO_INCREMENT,
      `username` varchar(50) DEFAULT NULL,
      `email` varchar(50) DEFAULT NULL,
      `password` varchar(80) DEFAULT NULL,
      `phoneNum` varchar(20) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
    
    /*Data for the table `sys_user` */
    
    insert  into `sys_user`(`id`,`username`,`email`,`password`,`phoneNum`) values (1,'zhangsan','zhangsan@itcast.cn','123','13888888888'),(2,'lisi','lisi@itcast.cn','123','13999999999'),(3,'wangwu','wangwu@itcast.cn','123','18599999999');
    
    /*Table structure for table `sys_user_role` */
    
    DROP TABLE IF EXISTS `sys_user_role`;
    
    CREATE TABLE `sys_user_role` (
      `userId` bigint(20) NOT NULL,
      `roleId` bigint(20) NOT NULL,
      PRIMARY KEY (`userId`,`roleId`),
      KEY `roleId` (`roleId`),
      CONSTRAINT `sys_user_role_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `sys_user` (`id`),
      CONSTRAINT `sys_user_role_ibfk_2` FOREIGN KEY (`roleId`) REFERENCES `sys_role` (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    /*Data for the table `sys_user_role` */
    
    insert  into `sys_user_role`(`userId`,`roleId`) values (1,1),(1,2),(2,2),(2,3);
    
    /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
    /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
    /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
    /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
    
    
  6. 创建POJO类

    创建User用户实体类

    package com.zcl.domain;
    
    public class User {
    
        private Long id;
        private String username;
        private String email;
        private String password;
        private String phoneNum;
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public String getPhoneNum() {
            return phoneNum;
        }
    
        public void setPhoneNum(String phoneNum) {
            this.phoneNum = phoneNum;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", username='" + username + '\'' +
                    ", email='" + email + '\'' +
                    ", password='" + password + '\'' +
                    ", phoneNum='" + phoneNum + '\'' +
                    '}';
        }
    }
    
    

    创建Role角色实体类

    package com.zcl.domain;
    
    public class Role {
    
        private Long id;
        private String roleName;
        private String roleDesc;
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getRoleName() {
            return roleName;
        }
    
        public void setRoleName(String roleName) {
            this.roleName = roleName;
        }
    
        public String getRoleDesc() {
            return roleDesc;
        }
    
        public void setRoleDesc(String roleDesc) {
            this.roleDesc = roleDesc;
        }
    
        @Override
        public String toString() {
            return "Role{" +
                    "id=" + id +
                    ", roleName='" + roleName + '\'' +
                    ", roleDesc='" + roleDesc + '\'' +
                    '}';
        }
    }
    
    
  7. 创建配置文件(applicationContext.xml、spring-mvc.xml、jdbc.properties、log4j.properties)

    resources包下创建log4j.properties日志配置文件

    ### direct log messages to stdout ###
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.out
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    
    ### direct messages to file mylog.log ###
    log4j.appender.file=org.apache.log4j.FileAppender
    log4j.appender.file.File=c:/mylog.log
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    
    ### set log levels - for more verbose logging change 'info' to 'debug' ###
    
    log4j.rootLogger=info, stdout
    
    

    resources包下创建jdbc.properties

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql:///test
    jdbc.username=root
    jdbc.password=1234
    

    resources包下创建applicationContext.xml核心spring配置文件

    
    <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 http://www.springframework.org/schema/context/spring-context.xsd
    ">
    
        
        <context:property-placeholder location="classpath:jdbc.properties"/>
    
        
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driver}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        bean>
    
        
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"/>
        bean>
    beans>
    

    resources包下创建spring-mvc.xml核心配置文件

    
    <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"
           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
    ">
    
        
        <mvc:annotation-driven/>
    
        
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            
            <property name="prefix" value="/pages/"/>
            
            <property name="suffix" value=".jsp"/>
        bean>
        
        <mvc:default-servlet-handler/>
    beans>
    

    创建了springspringMVC框架想要集中到web项目中需要配置web.xml

    ==配置webapp.WEB-INF文件下的web.xml

    
    <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">
    
        
        
        <context-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:applicationContext.xmlparam-value>
        context-param>
        
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
        listener>
    
    
        
        <servlet>
            <servlet-name>DispatcherServletservlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
            <init-param>
                <param-name>contextConfigLocationparam-name>
                <param-value>classpath:spring-mvc.xmlparam-value>
            init-param>
            <load-on-startup>2load-on-startup>
        servlet>
        <servlet-mapping>
            <servlet-name>DispatcherServletservlet-name>
            <url-pattern>/url-pattern>
        servlet-mapping>
    web-app>
    
2、角色列表的展示步骤分析
  1. 点击角色管理菜单发送请求到服务器端(修改角色管理菜单的u地址)

  2. 创建RoleController和list方法【web层】

    com.zcl.controller包下创建RoleController方法

    通过@RequestMapping来指定访问的路径

    注入的RoleService层代码是还没有写的,先写Web层代码会报红,后面再从com.zcl.service包下创建相应的RoleService接口

    package com.zcl.controller;
    
    import com.zcl.domain.Role;
    import com.zcl.service.RoleService;
    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 java.util.List;
    
    /**
     * 项目名称:Spring_oneTestPro
     * 描述:角色服务器
     *
     * @author zhong
     * @date 2022-05-02 23:08
     */
    @RequestMapping("/role")
    @Controller
    public class RoleController {
        /**
         * com.zcl.controller.RoleController.()
         * 注入Service层的代码
         *
         * @author zhong
         * @date 2022/5/2 23:15
         * @param  null
         * @return
         */
        @Autowired
        private RoleService roleService;
    
        /**
         * com.zcl.controller.RoleController.list()
         * 请求转发视图查询角色数据展示
         *
         * @author zhong
         * @date 2022/5/2 23:12
         * @param
         * @return org.springframework.web.servlet.ModelAndView
         */
        @RequestMapping("/list")
        public ModelAndView list(){
            System.out.println("请求成功");
            ModelAndView modelAndView = new ModelAndView();
            List<Role> roleList = roleService.list();
            // 设置视图模型数据
            modelAndView.addObject("roleList",roleList);
            // 设置跳转的视图
            modelAndView.setViewName("role-list");
            System.out.println("输出查询列表:"+roleList);
            return modelAndView;
        }
    }
    
    
  3. 创建RoleService和list方法【Service层】

    com.zcl.service包下创建RoleService接口

    解决web层的RoleService报红

    package com.zcl.service;
    
    import com.zcl.domain.Role;
    
    import java.util.List;
    
    /**
     * 项目名称:Spring_oneTestPro
     * 描述:这是一个Service接口
     *
     * @author zhong
     * @date 2022-05-02 23:13
     */
    public interface RoleService {
        public List<Role> list();
    }
    
    

    在此包下创建impl包并创建接口的实现类RoleServiceImpl

    package com.zcl.service.impl;
    
    import com.zcl.dao.RoleDao;
    import com.zcl.domain.Role;
    import com.zcl.service.RoleService;
    
    import java.util.List;
    
    /**
     * 项目名称:Spring_oneTestPro
     * 描述:实现RoleService接口的实现类
     *
     * @author zhong
     * @date 2022-05-02 23:14
     */
    public class RoleServiceImpl implements RoleService {
        private RoleDao roleDao;
        public void setRoleDao(RoleDao roleDao) {
            this.roleDao = roleDao;
        }
    
        /**
         * com.zcl.service.impl.RoleServiceImpl.list()
         * 重新接口方法,调用dao层的代码查询角色数据,返回列表集合
         *
         * @author zhong
         * @date 2022/5/2 23:17
         * @param
         * @return java.util.List
         */
        @Override
        public List<Role> list() {
            List<Role> roleList = roleDao.findAll();
            return roleList;
        }
    }
    
    

    在实现类里面会出现报RoleDao红,原因是还没有写Dao层的对应代码

  4. 创建RoleDao和findAll方法【Dao层】

    com.zcl.dao包下创建RoleDao接口

    package com.zcl.dao;
    
    import com.zcl.domain.Role;
    
    import java.util.List;
    
    /**
     * 项目名称:Spring_oneTestPro
     * 描述:dao层的接口
     *
     * @author zhong
     * @date 2022-05-02 23:18
     */
    public interface RoleDao {
        List<Role> findAll();
    }
    
    

    在此包下创建impl包并在包中创建实现类RoleDaoImpl

    package com.zcl.dao.impl;
    
    import com.zcl.dao.RoleDao;
    import com.zcl.domain.Role;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    
    import java.util.List;
    
    /**
     * 项目名称:Spring_oneTestPro
     * 描述:实现RoleDao接口类
     *
     * @author zhong
     * @date 2022-05-02 23:19
     */
    public class RoleDaoImpl implements RoleDao {
        /**
         * com.zcl.dao.impl.RoleDaoImpl.()
         * Dao注入JdbcTemplate模板
         *
         * @author zhong
         * @date 2022/5/2 23:22
         * @param  null
         * @return
         */
        private JdbcTemplate jdbcTemplate;
        public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }
    
        /**
         * com.zcl.dao.impl.RoleDaoImpl.findAll()
         * 调用JdbcTemplate模板里面的query()方法查询所有的角色信息
         *
         * @author zhong
         * @date 2022/5/2 23:22
         * @param
         * @return java.util.List
         */
        @Override
        public List<Role> findAll() {
            List<Role> roleList = jdbcTemplate.query("select * from sys_role",new BeanPropertyRowMapper<Role>(Role.class));
            return roleList;
        }
    }
    
    
  5. 使用JdbcTemplate?完成查询 *** 作

    请看步骤4

  6. 将查询数据存储到Modeli中

    请看步骤步骤2

  7. 转发到role-list,jsp页面进行展示

    请看步骤2

  8. 配置实现

    web层、Service层、Dao层都需要放到Spring容器当中

    web层

    1. spring-mvc.xml配置文件中配置包扫描

      需要导入相关的context引用和依赖

      xmlns:context="http://www.springframework.org/schema/context"
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
      

      配置包扫描controller

      
      <context:component-scan base-package="com.zcl.controller"/>
      
    2. com.zcl.controller包下的RoleController类上使用如下@Controller注解完成创建bean

      @RequestMapping("/role")
      @Controller
      public class RoleController {
          /**
           * 注入Service层
           */
          @Autowired
          private RoleService roleService;
          // 因为service的注入在applicationContext.xml里面注入了所以可以省略下面的代码
          /*public void setRoleService(RoleService roleService) {
              this.roleService = roleService;
          }*/
      }
      

      需要使用到@Autowired注解注入

      因为下面的service层通过了applicationContext.xml参数注入所以上面的代码可以注释,否则报错

    service层

    1. applicationContext.xml配置

      复制RoleService的全限定名到applicationContext.xml配置文件中配置

      
      <bean id="roleService" class="com.zcl.service.impl.RoleService">
          <property name="roleDao" ref="roleDao"/>
      bean>
      

      service层是注入dao层的代码

    dao层

    1. applicationContext.xml配置

      复制RoleDaoImpl的全限定名到applicationContext.xml配置文件中配置

      
      <bean id="roleDao" class="com.zcl.dao.impl.RoleDaoImpl">
          <property name="jdbcTemplate" ref="jdbcTemplate"/>
      bean>
      

      dao层的代码是注入jdbcTemplate模板

  9. 修改role-list.jsp页面获取模型数据并展示

    在页面的顶部引入如下

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    

    找到数据表的内容部分修改,循环遍历模型里面的存储的角色列表数据

    
    	
    		
    			
                ${role.id}
                ${role.roleName}
                ${role.roleDesc}
                
                	删除
                
    		
    		
    
    
  10. 启动页面查看

    如果出现了下图的服务器启动错误,启动不了服务器的重新建一个工程一步一步来完成并启动测试,我也没找出是什么原因,可评论回复

    成功的访问页面效果

GitHub远程仓库源码地址

https://github.com/ZhongChunle/Spring_oneTestPro.git

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/794054.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-06
下一篇 2022-05-06

发表评论

登录后才能评论

评论列表(0条)

保存