首页 > 其他分享 >Spring Security(2)

Spring Security(2)

时间:2022-11-22 08:34:40浏览次数:31  
标签:return String Spring userid id sql Security public

您好,我是湘王,这是我的博客园,欢迎您来,欢迎您再来~

 

前面已经把需要的环境准备好了,包括数据库和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);
    }
}

 

/**
 * 角色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工具接口对接口进行进行测试:

 

 

 

 

却发现它什么都没显示?

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

 

 


 

 

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

 

标签:return,String,Spring,userid,id,sql,Security,public
From: https://www.cnblogs.com/xiangwang1111/p/16913605.html

相关文章

  • Springboot整合Swagger常用注解(三)
    swagger注解主要是用来给swagger生成的接口文档说明用的1、@Api使用范围:用在类上注解,控制整个类生成接口信息的内容,表示对类的说明,也代表了这个类是swagger2的资源参......
  • SpringCloud Gateway 网关常用技术实现
    SpringCloudGateway是目前非常流行的网关中间件,类似于nginx一样,主要提供【路由转发】和【负载均衡】功能,目的是为微服务架构提供一种简单而有效的统一的API路由管理......
  • Spring MVC之Controller参数接收
    @RequestBody接收参数注意事项:@RequestBody:后台接收只能声明一个、且只能接收json@RequestBody:不能和form/data共存@RequestBody:必须是:contentType:"applicatio......
  • spring 源码bean加载过程
    1.xml文件加载#(XmlBeanDefinitionReader)解析spring.xml文件,注册registerBeanDefinitions1.entityResolver->schemaResolver主要加载META-INF/spring.schema......
  • Spring中定时任务@Schedule注解的使用
    概述@Scheduled注解是springboot提供的用于定时任务控制的注解,主要用于控制任务在某个指定时间执行,或者每隔一段时间执行.注意需要配合@EnableScheduling使用,配置@Sch......
  • spring之自定义注解
    @Target({ElementType.METHOD,ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)@Constraint(validatedBy=MyConstraintValidator.class)public@interface......
  • springboot实现无数据库启动
    问题springboot往往是作为b/s系统的server端的架子来使用,但是有些时候,是作为静默的server,并没有界面和数据库,但是springboot默认是链接数据库的,如何解决这个问题呢?使用sprin......
  • spring AOP
    一、什么是AOPAOP(AspectOrientedProgramming),即面向切面编程,可以说是OOP(ObjectOrientedProgramming,面向对象编程)的补充和完善。OOP引入封装、继承、多态等概念来建立一......
  • Spring-IoC中Set和构造器注入
     新建Maven工程  修改pom文件1<?xmlversion="1.0"encoding="UTF-8"?>2<projectxmlns="http://maven.apache.org/POM/4.0.0"3xmlns:xsi="http......
  • 【Spring Cloud实战】Eurake服务注册与发现
    gitee地址:https://gitee.com/javaxiaobear/spring-cloud_study.git什么是服务治理?SpringCloud封装了Netflix公司开发的Eureka模块来实现服务治理。在传统的rpc远程调......