Spring Security(2)

70 阅读4分钟

您好,我是湘王,这是我的掘金小站,欢迎您来,欢迎您再来~

前面已经把需要的环境准备好了,包括数据库和SQL语句,现在再来写代码。至于安装MySQL什么的就跳过去了,娘度子里面一大把。

先做一点声明:因为考虑到有些初学Java的工程师可能并不太熟悉MyBatis,而且MyBatis也并非能完全代替SQL,所以在接下来的所有业务代码中,会以JDBC为主。这么做也很好理解:会MyBatis的很大可能也会JDBC,但会JDBC的就不一定会MyBatis了。而且MyBatis用多了,写SQL能力可能会退化,这其实不好。当然,以上纯属个人意见,不喜可喷,欢迎来喷。

先创建一个专门用来操作数据库的Dao类,就叫MySQLDao吧:

/**
 * MySQLDao
 *
 * @author 湘王
 */
@Component
public class MySQLDao<T> {
   @Autowired
   private JdbcTemplate jdbcTemplate;

   // 创建数据
   public int create(final String sql, final @Nullable Object... args) throws Exception {
      try {
         if (1 <= jdbcTemplate.update(sql, args)) {
            return 0;
         }

         return -1;
      } catch (DuplicateKeyException e) {
         e.printStackTrace();
         throw new DuplicateKeyException("data duplicate exception");
      } catch (DataAccessException e) {
         e.printStackTrace();
         throw new RuntimeException("create data exception");
      }
   }

   // 查询数量
   public Integer count(final String sql, final Object[] args) {
      try {
         return jdbcTemplate.queryForObject(sql, args, Integer.class);
      } catch (DataAccessException e) {
         e.printStackTrace();
      }

      return null;
   }

   // 查询单条数据
   public Object findOne(final String sql, final RowMapper<?> rowMapper, final @Nullable Object... args) {
      try {
         List<?> list = jdbcTemplate.query(sql, rowMapper, args);
         if (null != list && list.size() > 0) {
            return list.get(0);
         }
      } catch (DataAccessException e) {
         e.printStackTrace();
      }

      return null;
   }

   // 获得列表
   public List<?> find(final String sql, final RowMapper<?> rowMapper, final @Nullable Object... args) {
      try {
         List<?> list = jdbcTemplate.query(sql, rowMapper, args);
         if (null != list && 0 != list.size()) {
            return list;
         }
      } catch (DataAccessException e) {
         e.printStackTrace();
      }

      return null;
   }

   // 更新或删除数据
   public boolean update(final String sql, final @Nullable Object... args) throws Exception {
      try {
         return 0 <= jdbcTemplate.update(sql, args);
      } catch (DataAccessException e) {
         e.printStackTrace();
         throw new RuntimeException("update or remove object exception");
      }
   }
}

 

接着创建实体类Entity(以SysUser为例):

/**
 * 用户entity
 *
 * @author 湘王
 */
public class SysUser implements Serializable, RowMapper<SysUser> {
    private static final long serialVersionUID = -1214743110268373599L;

    private int id;
    private String username;
    private String password;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    protected Date createtime;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    protected Date updatetime;

    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @JsonIgnore
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }

    public Date getUpdatetime() {
        return updatetime;
    }

    public void setUpdatetime(Date updatetime) {
        this.updatetime = updatetime;
    }

    @Override
    public SysUser mapRow(ResultSet result, int i) throws SQLException {
        SysUser user = new SysUser();

        user.setId(result.getInt("id"));
        user.setUsername(result.getString("username"));
        user.setPassword(result.getString("password"));
        user.setCreatetime(result.getTimestamp("createtime"));
        user.setUpdatetime(result.getTimestamp("updatetime"));

        return user;
    }
}

 

接着创建SysRole和SysUserRole,与SysUser类似:

/**
 * 角色entity
 *
 * @author 湘王
 */
public class SysRole implements Serializable, RowMapper<SysRole> {
    private static final long serialVersionUID = 6980192718775578676L;

    private int id;
    private String name;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    protected Date createtime;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    protected Date updatetime;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }

    public Date getUpdatetime() {
        return updatetime;
    }

    public void setUpdatetime(Date updatetime) {
        this.updatetime = updatetime;
    }

    @Override
    public SysRole mapRow(ResultSet result, int i) throws SQLException {
        SysRole role = new SysRole();

        role.setId(result.getInt("id"));
        role.setName(result.getString("name"));
        role.setCreatetime(result.getTimestamp("createtime"));
        role.setUpdatetime(result.getTimestamp("updatetime"));

        return role;
    }
}

 

/**
 * 用户角色entity
 *
 * @author 湘王
 */
public class SysUserRole implements Serializable, RowMapper<SysUserRole> {
    private static final long serialVersionUID = 9171155241328712313L;

    private int userid;
    private int roleid;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createtime;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date updatetime;

    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;
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }

    public Date getUpdatetime() {
        return updatetime;
    }

    public void setUpdatetime(Date updatetime) {
        this.updatetime = updatetime;
    }

    @Override
    public SysUserRole mapRow(ResultSet result, int i) throws SQLException {
        SysUserRole userRole = new SysUserRole();

        userRole.setUserid(result.getInt("userid"));
        userRole.setRoleid(result.getInt("roleid"));
        userRole.setCreatetime(result.getTimestamp("createtime"));
        userRole.setUpdatetime(result.getTimestamp("updatetime"));

        return userRole;
    }
}

接着创建Service:

/**
 * 用户Service
 *
 * @author 湘王
 */
@Service
public class UserService {
    @Autowired
    private MySQLDao mySQLDao;

    public Integer count() {
        String sql = "SELECT COUNT(id) FROM sys_user;";
        return mySQLDao.count(sql, new Object[] {});
    }

    public int save(String username, String password) throws Exception {
        String sql = "INSERT INTO sys_user(username, password) VALUES (?, ?);";
        return mySQLDao.create(sql, username, password);
    }

    public SysUser getById(int id) {
        String sql = "SELECT id, username, password, createtime, updatetime FROM sys_user WHERE id = ?";
        return (SysUser) mySQLDao.findOne(sql, new SysUser(), id);
    }

    public SysUser getByName(String username) {
        String sql = "SELECT id, username, password, createtime, updatetime FROM sys_user WHERE username = ?";
        return (SysUser) mySQLDao.findOne(sql, new SysUser(), username);
    }

    public List<SysUser> getAll() {
        String sql = "SELECT id, username, password, createtime, updatetime FROM sys_user";
        return mySQLDao.find(sql, new SysUser());
    }
}
/**
 * 角色Service
 *
 * @author 湘王
 */
@Service
public class RoleService {
    @Autowired
    private MySQLDao roleDao;

    public void save(String name) throws Exception {
        String sql = "INSERT INTO sys_role(name) VALUES (?);";
        roleDao.create(sql, name);
    }

    public SysRole getById(int id) {
        String sql = "SELECT id, name, createtime, updatetime FROM sys_role WHERE id = ?";
        return (SysRole) roleDao.findOne(sql, new SysRole(), id);
    }

    public SysRole getByName(String name) {
        String sql = "SELECT id, name, createtime, updatetime FROM sys_role WHERE name = ?";
        return (SysRole) roleDao.findOne(sql, new SysRole(), name);
    }

    public List<SysRole> getAll() {
        String sql = "SELECT id, name, createtime, updatetime FROM sys_role";
        return roleDao.find(sql, new SysRole());
    }

    public List<SysRole> getByUserId(int userid) {
        String sql = "SELECT r.id, r.name, r.createtime, r.updatetime " +
                "FROM sys_role AS r, sys_user_role AS ur, sys_user AS u " +
                "WHERE u.id = ? AND u.id = ur.userid AND ur.roleid = r.id";
        return (List<SysRole>) roleDao.findOne(sql, new SysRole(), userid);
    }
}
/**
 * 用户角色Service
 *
 * @author 湘王
 */
@Service
public class UserRoleService {
    @Autowired
    private MySQLDao mySQLDao;

    public void save(int userid, int roleid) throws Exception {
        String sql = "INSERT INTO sys_user_role(userid, roleid) VALUES (?, ?);";
        mySQLDao.create(sql, userid, roleid);
    }

    public List<SysUserRole> getByUserId(int userid) {
        String sql = "SELECT userid, roleid, createtime, updatetime FROM sys_user_role WHERE userid = ?";
        return mySQLDao.find(sql, new SysUserRole(), userid);
    }

    public List<SysUserRole> getByRoleId(int roleid) {
        String sql = "SELECT userid, roleid, createtime, updatetime FROM sys_user_role WHERE roleid = ?";
        return mySQLDao.find(sql, new SysUserRole(), roleid);
    }

    public SysUserRole getById(int userid, int roleid) {
        String sql = "SELECT userid, roleid, createtime, updatetime FROM sys_user_role WHERE userid = ? AND roleid = ?";
        return (SysUserRole) mySQLDao.findOne(sql, new SysUserRole(), userid, roleid);
    }
}

 

最后创建一个LoginController:

/**
 * 登录Controller
 *
 * @author 湘王
 */
@RestController
public class LoginController {
    @GetMapping("/")
    public String index() {
        final String username = SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println("当前登录用户:" + username);

        return "SUCCESS";
    }

    // 登录
    @PostMapping("/login")
    public String login(String username, String password) {
        System.out.println("当前登录用户:" + username);

        return "SUCCESS";
    }

    // 登出
    @GetMapping("/logout")
    public String logout(String username) {
        System.out.println("登出用户:" + username);

        return "SUCCESS";
    }
}

 

启动应用:

/**
 * 应用入口
 *
 * @author 湘王
 */
@SpringBootApplication
public class RBACApplication {
    public static void main(String[] args) {
        SpringApplication.run(RBACApplication.class);
    }
}

 

用postman(或其他工具,如apipost)或者IDE工具接口对接口进行进行测试:

12.用postman进行测试 .png

 

却发现它什么都没显示?

对,没有任何显示是正常的,因为还有很重要的内容没有写呢。

感谢您的大驾光临!咨询技术、产品、运营和管理相关问题,请关注后留言。欢迎骚扰,不胜荣幸~