Spring练习 —— 黑马

Spring练习 —— 黑马,第1张

(还存在需要完善的地方,例如新建新的用户,用户id不是从原表中进行提取)

Spring环境搭建步骤 ① 创建工程(Project&Module) ② 导入静态页面 ③ 添加需要的Maven依赖 ④ 创建包结构(controller、service业务层、dao、domain、utils) ⑤ 导入数据库脚本 ⑥ 创建POJO类(User.java和Role.java) ⑦ 创建配置文件(applicationContext.xml、spring-mvc.xml、jdbc.properties、log4j.properties)  注意:web.xml 需要进行配置



  
  
    CharacterEncodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
      UTF-8
    
  
  
    CharacterEncodingFilter
    /*
  

  
  
    DispatcherServlet
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:spring-mvc.xml
    
    1
  
  
    DispatcherServlet
    /
  


  
  
    contextConfigLocation
    classpath:applicationContext.xml
  

  
  
    org.springframework.web.context.ContextLoaderListener
  


运行Tomcat (  localhost:8080/Spirng_war/ 

首先打开index.jsp页面,但因为写有如下代码,所以直接打开main.jsp

<%
   response.sendRedirect(request.getContextPath()+"/pages/main.jsp");//默认打开main.jsp
%>
角色列表的展示

① 点击角色管理菜单发送请求到服务器端(修改角色管理菜单的url地址)

在main.jsp中发现aside.jsp(导航侧栏 )对其进行修改

  • 角色管理
  • domain —— Role

    package com.zd.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 + '\'' +
                    '}';
        }
    }
    
    ② 创建RoleController
    package com.zd.controller;
    
    import com.zd.domain.Role;
    import com.zd.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;
    
    @RequestMapping("/role")
    @Controller
    public class RoleController {
    
        @Autowired
        private RoleService roleService;
    
    
    
        @RequestMapping("/list")
        public ModelAndView list(){
            ModelAndView modelAndView = new ModelAndView();
            List roleList = roleService.list();
            //设置模型
            modelAndView.addObject("roleList",roleList);
            //设置视图
            modelAndView.setViewName("role-list");//展示列表的地址
            System.out.println(roleList);
            return modelAndView;
        }
    
    }
    
    ③ 创建RoleService
    package com.zd.service;
    
    import com.zd.domain.Role;
    
    import java.util.List;
    
    public interface RoleService {
            public List list() ;
    
            void save(Role role);
    }
    

    service —— impl —— RoleServiceImpl

    package com.zd.service.impl;
    
    import com.zd.dao.RoleDao;
    import com.zd.domain.Role;
    import com.zd.service.RoleService;
    
    import java.util.List;
    
    public class RoleServiceImpl implements RoleService {
        private RoleDao roleDao;
    
        public void setRoleDao(RoleDao roleDao) {
            this.roleDao = roleDao;
        }
    
    
        @Override
        public List list() {
            List roleList = roleDao.findAll();
            return roleList;
        }
    
    }
    
    ④ 创建RoleDao
    package com.zd.dao;
    
    import com.zd.domain.Role;
    
    import java.util.List;
    
    public interface RoleDao {
        List findAll();
    }
    

    dao —— RoleDao —— RoleDaoImpl(使用JdbcTemplate完成查询 *** 作

    package com.zd.dao.impl;
    
    import com.zd.dao.RoleDao;
    import com.zd.domain.Role;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    
    import java.util.List;
    
    public class RoleDaoImpl implements RoleDao {
        private JdbcTemplate jdbcTemplate;
    
        public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }
    
        public List findAll() {
            List roleList = jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper(Role.class));
            return roleList;
        }
    }
    
    ⑥ 将查询数据存储到Model中 ⑦ 转发到role-list.jsp页面进行展示

    配置文件 

    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
    

    jdbc.properties

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

    spring-mvc.xml

    
    
    
        
        
    
        
        
            
            
        
    
        
        
    
        
        
    
    

    applicationContext.xml

    
    
    
        
        
    
        
        
            
            
            
            
        
    
        
        
            
        
    
        
        
            
        
    
        
        
            
        
    
    

    role_list.jsp

    
                                
          
             
             ${role.id}
             ${role.roleName}
             ${role.roleDesc}
             
                删除
             
          
       
    

    错误记录

    错误原因:代码写错

    //源代码
    List roleList = jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper());

    java.lang.IllegalStateException: Mapped class was not specified

    //修改后
    List roleList = jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper(Role.class));
    角色添加 ① 点击列表页面新建按钮跳转到角色添加页面 ② 输入角色信息,点击保存按钮,表单数据提交服务器 ③ 编写RoleController的save()方法
     @RequestMapping("/save")
        public String save(Role role){
            roleService.save(role);
            return"redirect:/role/list";
        }

    ④ 编写RoleService的save()方法

    void save(Role role);

    RoleServiceImpl的save()方法

     @Override
        public void save(Role role) {
            roleDao.save(role);
        }
    ⑤ 编写RoleDao的save()方法
    void save(Role role);

    ⑥ 使用JdbcTemplate保存Role数据到sys_role(RoleDaoImpl中的save方法)

    @Override
        public void save(Role role) {
            jdbcTemplate.update("insert into sys_role values(?,?,?)",null,role.getRoleName(),role.getRoleDesc());
        }

    ⑦ 跳转回角色列表页面

    role_add.jsp
    角色信息 角色名称 角色描述
    注意:method="post"如果出现中文乱码,则可在web.xml中配置全局过滤的filter
    
    
      CharacterEncodingFilter
      org.springframework.web.filter.CharacterEncodingFilter
      
        encoding
        UTF-8
      
    
    
      CharacterEncodingFilter
      /*
    

    ② 创建RoleController

    package com.zd.controller;
    
    
    import com.zd.domain.Role;
    import com.zd.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;
    
    @RequestMapping("/role")
    @Controller
    public class RoleController {
    
        @Autowired
        private RoleService roleService;
    
        @RequestMapping("/save")
        public String save(Role role){
            roleService.save(role);
            return "redirect:/role/list";
        }
    
        @RequestMapping("/list")
        public ModelAndView list(){
            ModelAndView modelAndView = new ModelAndView();
            List roleList = roleService.list();
            //设置模型
            modelAndView.addObject("roleList",roleList);
            //设置视图
            modelAndView.setViewName("role-list");
            System.out.println(roleList);
            return modelAndView;
        }
    
    }
    

    service —— RoleService

    package com.zd.service;
    
    import com.zd.domain.Role;
    
    import java.util.List;
    
    public interface RoleService {
            public List list() ;
    
            void save(Role role);
    }
    

    service —— impl —— RoleServiceImpl

    package com.zd.service.impl;
    
    import com.zd.dao.RoleDao;
    import com.zd.domain.Role;
    import com.zd.service.RoleService;
    
    import java.util.List;
    
    public class RoleServiceImpl implements RoleService {
        private RoleDao roleDao;
    
        public void setRoleDao(RoleDao roleDao) {
            this.roleDao = roleDao;
        }
    
    
        @Override
        public List list() {
            List roleList = roleDao.findAll();
            return roleList;
        }
    
        @Override
        public void save(Role role) {
    
        }
    }
    

    dao —— RoleDao

    package com.zd.dao;
    
    import com.zd.domain.Role;
    
    import java.util.List;
    
    public interface RoleDao {
        List findAll();
    }
    

    dao —— RoleDao —— RoleDaoImpl

    package com.zd.dao.impl;
    
    import com.zd.dao.RoleDao;
    import com.zd.domain.Role;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    
    import java.util.List;
    
    public class RoleDaoImpl implements RoleDao {
        private JdbcTemplate jdbcTemplate;
    
        public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }
    
        public List findAll() {
            List roleList = jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper(Role.class));
            return roleList;
        }
    
    
    
    }
    

    配置文件 

    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
    

    jdbc.properties

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

    spring-mvc.xml

    
    
    
        
        
    
        
        
            
            
        
    
        
        
    
        
        
    
    

    applicationContext.xml

    
    
    
        
        
    
        
        
            
            
            
            
        
    
        
        
            
        
    
        
        
            
        
    
        
        
            
        
    
    

    role_list.jsp

    
                                
          
             
             ${role.id}
             ${role.roleName}
             ${role.roleDesc}
             
                删除
             
          
       
    

    错误记录

    错误原因:代码写错

    //源代码
    List roleList = jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper());

    java.lang.IllegalStateException: Mapped class was not specified

    //修改后
    List roleList = jdbcTemplate.query("select * from sys_role", new BeanPropertyRowMapper(Role.class));
    角色添加的步骤 ① 点击列表页面新建按钮跳转到角色添加页面 ② 输入角色信息,点击保存按钮,表单数据提交服务器 ③ 编写RoleController的save()方法
     @RequestMapping("/save")
        public String save(Role role){
            roleService.save(role);
            return"redirect:/role/list";
        }

    ④ 编写RoleService的save()方法

    void save(Role role);

    RoleServiceImpl的save()方法

     @Override
        public void save(Role role) {
            roleDao.save(role);
        }
    ⑤ 编写RoleDao的save()方法
    void save(Role role);

    ⑥ 使用JdbcTemplate保存Role数据到sys_role(RoleDaoImpl中的save方法)

    @Override
        public void save(Role role) {
            jdbcTemplate.update("insert into sys_role values(?,?,?)",null,role.getRoleName(),role.getRoleDesc());
        }

    ⑦ 跳转回角色列表页面

    role_add.jsp
    角色信息 角色名称 角色描述
    注意:method="post"如果出现中文乱码,则可在web.xml中配置全局过滤的filter
    
    
      CharacterEncodingFilter
      org.springframework.web.filter.CharacterEncodingFilter
      
        encoding
        UTF-8
      
    
    
      CharacterEncodingFilter
      /*
    
     用户列表的展示

    ① 点击用户管理菜单发送请求到服务器端(修改用户管理菜单的url地址)—— aside.jsp
  • 用户管理
  • ② 创建UserController

    package com.zd.controller;
    
    import com.zd.domain.User;
    import com.zd.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 java.util.List;
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
        @Autowired
        private UserService userService;
    
        @RequestMapping("/list")
        public ModelAndView list(){
            ModelAndView modelAndView = new ModelAndView();
            List userList = userService.list();
            //设置模型
            modelAndView.addObject("userList",userList);
            //设置视图
            modelAndView.setViewName("user-list");
            return modelAndView;
        }
    }
    

    ③ 创建UserService 的 list()方法
    package com.zd.service;
    
    import com.zd.domain.User;
    import java.util.List;
    
    public interface UserService {
        public List list();
    
    }
    

     UserServiceImpl 的 list()方法   将查询数据存储到Model中

    package com.zd.service.impl;
    
    import com.zd.dao.RoleDao;
    import com.zd.dao.UserDao;
    import com.zd.domain.Role;
    import com.zd.domain.User;
    import com.zd.service.UserService;
    
    import java.util.List;
    
    public class UserServiceImpl implements UserService {
    
        private UserDao userDao;
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
    
        private RoleDao roleDao;
        public void setRoleDao(RoleDao roleDao) {
            this.roleDao = roleDao;
        }
    
        public List list() {
            List userList = userDao.findAll();
            //封装userList中的每一个User的roles数据
            for (User user : userList) {
                //获得user的id
                Long id = user.getId();
                //将id作为参数 查询当前userId对应的Role集合数据
                List roles = roleDao.findRoleByUserId(id);
                user.setRoles(roles);
            }
            return userList;
        }
    }
    

    ④ 创建UserDao

    package com.zd.dao;
    
    import com.zd.domain.User;
    
    import java.util.List;
    
    public interface UserDao {
        List findAll();
    }
    

    UserDaoImpl  使用JdbcTemplate完成查询 *** 作

    package com.zd.dao.impl;
    
    import com.zd.dao.UserDao;
    import com.zd.domain.User;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    
    import java.util.List;
    
    public class UserDaoImpl implements UserDao {
    
        private JdbcTemplate jdbcTemplate;
        public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }
    
        public List findAll() {
            List userList = jdbcTemplate.query("select * from sys_user ", new BeanPropertyRowMapper(User.class));
            return userList;
        }
    
    }
    

    RoleDao 增添 findRoleByUserId() 方法

     List findRoleByUserId(Long id);

    RoleDaoImpl

    @Override
        public List findRoleByUserId(Long id) {
            List roles = jdbcTemplate.query("select * from sys_user_role ur,sys_role r where ur.roleId=r.id and ur.userId=?", new BeanPropertyRowMapper(Role.class), id);
            return roles;
        }

    转发到user-list.jsp页面进行展示

    
    
       
          
          ${user.id}
          ${user.username}
          ${user.email}
          ${user.phoneNum}
          
             
                   ${role.roleName}
             
          
          
             删除
          
       
    
    
    

    配置文件:applicationContext.xml

    
    
        
        
    
    
    
    
        
    
    用户添加 ① 点击列表页面新建按钮跳转到角色添加页面 user-list.jsp
    ② 输入角色信息,点击保存按钮,表单数据提交服务器 ③UserController的save()方法
    @RequestMapping("/save")
        //Long[] roleIds 存储用户角色
        public String save(User user,Long[] roleIds){
            userService.save(user, roleIds);
            return "redirect:/user/list";//跳转回角色列表页面
        }
    
        @RequestMapping("/saveUI")
        public ModelAndView saveUI(){
            ModelAndView modelAndView = new ModelAndView();
            List roleList = roleService.list();
            //设置模型
            modelAndView.addObject("roleList",roleList);
            //设置视图
            modelAndView.setViewName("user-add");
    
            return modelAndView;
        }

    ④ 编写UserService的save()方法

    void save(User user, Long[] roleIds);

    UserServiceImpl

    @Override
        public void save(User user, Long[] roleIds) {
            //第一步 向user表中存储数据
            Long userId = userDao.save(user);
            //第二步  向role表中存储多条数据
            userDao.saveUserRoleRel(userId,roleIds);
        }

    ⑤ 编写UserDao的save()方法

     Long save(User user);
    
        void saveUserRoleRel(Long id, Long[] roleIds);

    UserDaoImpl  使用JdbcTemplate保存Role数据到sys_role

     @Override
        public Long save(final User user) {
            //创建PreparedStatementCreator
            PreparedStatementCreator creator =new PreparedStatementCreator() {
                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    //使用原始jdbc完成有个preparedStatement的组件
                    PreparedStatement preparedStatement = connection.prepareStatement("insert into sys_user values(?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);
                    preparedStatement.setObject(1,null);
                    preparedStatement.setString(2,user.getUsername());
                    preparedStatement.setString(3,user.getEmail());
                    preparedStatement.setString(4,user.getPassword());
                    preparedStatement.setString(5,user.getPhoneNum());
                    return preparedStatement;
                }
            };
            //创建keyHolder
            GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
    
            jdbcTemplate.update(creator,keyHolder);
    
            //获得生成的主键
            long userId = keyHolder.getKey().longValue();
    
            //jdbcTemplate.update("insert into sys_user values(?,?,?,?)",null,user.getUsername(),user.getEmail(),user.getPassword(),user.getPhoneNum());
            return userId;//返回当前保存用户的id,该id是数据库自动生成的
        }
    
        @Override
        public void saveUserRoleRel(Long userId, Long[] roleIds) {
            for(Long roleId:roleIds)
                jdbcTemplate.update("insert into sys_user_role values(?,?)",userId,roleId);
    
        }

    user-add.jsp
    用户角色
    
        
            ${role.roleName}
        
    

     删除用户

    ① 点击用户列表的删除按钮,发送请求到服务器端 user-list.jsp
    
    											删除
    										
    
    
    错误记录: 以上源代码
    ② UserController的del()方法
    @RequestMapping("/del/{userId}")
        public String del(@PathVariable("userId") Long userId){
            userService.del(userId);
            return "redirect:/user/list";//跳回当前用户列表页面
        }
    ③ UserService的del()方法
    void del(Long userId);

    UserServiceImpl

     @Override
        public void del(Long userId) {
            //1、删除role关系表中的数据
            userDao.delUerRoleRel(userId);
            //2、删除user中的数据
            userDao.del(userId);
        }

    ④ UserDao

    void delUerRoleRel(Long userId);
    
    void del(Long userId);

    UserDaoImpl

    @Override
        public void delUerRoleRel(Long userId) {
            jdbcTemplate.update("delete from sys_user_role where userId=?",userId);
        }
    
    @Override
        public void del(Long userId) {
            jdbcTemplate.update("delete from sys_user where id=?",userId);
        }

    ⑤ UserDao

    void delUerRoleRel(Long userId);
    
     void del(Long userId);

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

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

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

    发表评论

    登录后才能评论

    评论列表(0条)

    保存