java实习课堂笔记五

SSM实验3

  • 本次实验的所有操作都是在SSM实验2的基础上进行的

实验新增内容

实现过滤网页不正常登录的功能和批量删除用户的功能,同时新增角色权限管理功能

实验过程

  1. 在java文件夹下创建filter包,并在该包下创建LoginFilter类
  • LoginFilter类实现Filter接口,专门用于拦截不正常的页面跳转,也就是让用户名未登录或登录失败时不可进行其余的正常操作
public class LoginFilter implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        String uri = request.getRequestURI();
        if(user==null && uri.indexOf("login.do")==-1){
            response.sendRedirect(request.getContextPath() + "../login.jsp");
        }else{
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
    }
}
  1. 在web.xml文件中添加过滤器
  • 这段代码大致放在web.xml文件的52行
<!--解决用户通过网址绕过登录的问题-->
  <filter>
    <filter-name>loginFilter</filter-name>
    <filter-class>com.yeling.filter.LoginFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>loginFilter</filter-name>
    <url-pattern>*.do</url-pattern>
  </filter-mapping>
  1. 在UserDao接口中新增deleteAll方法,并在UserMapper.xml中实现该方法
    void deleteAll(@Param("ids")List<Integer> ids);
    <delete id="deleteAll" parameterType="list">
        delete from user where id in
        <foreach collection="ids" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </delete>
  1. 在UserService接口中新增方法deleteAll,并在UserServiceImpl类中实现该方法
    void deleteAll(List<Integer> ids);
    @Override
    public void deleteAll(List<Integer> ids) {
        userDao.deleteAll(ids);
    }
  1. 使用Mysql图形界面管理工具创建role表和user-role表
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
  2. 在bean包里创建Role类和UserRole类
public class Role {

    private int id;
    private String rolename;    //角色名称
    private String roledesc;    //角色描述

    public int getId() {
        return id;
    }

    public void setId(int 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 + '\'' +
                '}';
    }
}
public class UserRole {

    private int id;
    private int userId;
    private int roleId;

    public UserRole() {
    }

    public UserRole(int id, int userId, int roleId) {
        this.id = id;
        this.userId = userId;
        this.roleId = roleId;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public int getRoleId() {
        return roleId;
    }

    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }

    @Override
    public String toString() {
        return "UserRole{" +
                "id=" + id +
                ", userId=" + userId +
                ", roleId=" + roleId +
                '}';
    }
}
  1. 在dao包里创建RoleDao接口
public interface RoleDao {
    List<Integer> findRoleIdByUserId(int userId);

    List<Role> findRoleByUserId(int userId);

    void addRole(UserRole userRole);
}
  1. 在Mapper文件夹下创建RoleMapper.xml文件
<?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.yeling.dao.RoleDao" >

    <select id="findRoleIdByUserId" parameterType="int" resultType="int">
        select roleId from user_role where userId=#{userId}
    </select>

    <select id="findRoleByUserId" parameterType="int" resultType="role">
        select * from role where id not in (select roleId from user_role where userId=#{userId})
    </select>

    <select id="addRole" parameterType="userRole">
        insert into user_role (userId,roleId) values (#{userId}, #{roleId})
    </select>
</mapper>
  1. 在service包下创建RoleService接口
public interface RoleService {

    List<Integer> findRoleId(int userId);

    List<Role> findRoleByUserId(int userId);

    void addRole(List<Integer> ids, String userId);
}
  1. 在impl包下创建RoleServiceImpl类并实现RoleService接口
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Integer> findRoleId(int userId) {
        return roleDao.findRoleIdByUserId(userId);
    }

    @Override
    public List<Role> findRoleByUserId(int userId) {
        return roleDao.findRoleByUserId(userId);
    }

    @Override
    public void addRole(List<Integer> ids, String userId) {
        for(int roleId: ids){
            UserRole userRole = new UserRole();
            userRole.setUserId(Integer.parseInt(userId));
            userRole.setRoleId(roleId);
            roleDao.addRole(userRole);
        }
    }
}
  1. 在UserController类中新增属性和方法,并修改login方法
   @Autowired
   private RoleService roleService;

   @RequestMapping("/login.do")
   public ModelAndView login(User user, HttpSession session){   //session.setAttribute();

       int id = userService.login(user.getUsername(), user.getPassword());
       ModelAndView mv = new ModelAndView();
       if(id != -1){
           List<Integer> roleIds = roleService.findRoleId(id);
           session.setAttribute("roleIds", roleIds);
           session.setAttribute("user", user);
           mv.setViewName("main");
       }else{
           mv.setViewName("../failer");
       }
       return mv;
   }

   @RequestMapping("/deleteAll.do")
   public String deleteAll(String userList){
       String[] str = userList.split(",");
       List<Integer> ids = new ArrayList<>();
       for(String s:str){
           ids.add(Integer.parseInt(s));
       }
       userService.deleteAll(ids);
       return "redirect:findAll.do";
   }

   @RequestMapping("toAddRole.do")
   public ModelAndView toAddRole(int id){
       List<Role> roleList = roleService.findRoleByUserId(id);
       ModelAndView mv = new ModelAndView();
       mv.addObject("roles", roleList);
       mv.addObject("id", id);
       mv.setViewName("user-role-add");
       return mv;
   }

   @RequestMapping("addRole.do")
   @ResponseBody
   public String add(String roleList, String userId){
       String[] strings = roleList.split(",");
       List<Integer> ids = new ArrayList<>();
       for(String s: strings){
           ids.add(Integer.parseInt(s));
       }
       roleService.addRole(ids, userId);
       return "";
   }
  1. 在user-list.jsp文件中添加部分代码,使得管理员可以在管理用户界面给用户添加角色
  • 这段代码放在user-list.jsp文件的157行
												<% List<Integer> roleIds = (List<Integer>) session.getAttribute("roleIds");%>
												<% if(roleIds.contains(1)){%>
												<a href="/user/toAddRole.do?id=${user.id}">添加角色</a>
												<%}%>
  1. 配置Tomcat Server并运行

结果展示

在这里插入图片描述
在这里插入图片描述

实验小结

  • 利用SSM框架实现用户和角色管理非常方便,二者拥有不同的dao层、service层,但却同时公用一个controller层,这样既降低了业务逻辑的耦合度,又方便了controller对请求的处理
  • 废话不多说,项目链接放上来
    链接:SSM3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值