springBoot+mybatis+springsecurity整合!
2017-08-24 14:28
686 查看
首先项目是maven工程,创建maven工程相信大家一定不陌生了。下面咱们直接进入主题。
首先搭建springBoot工程,pom.xml里面添加这些jar信息,就足够了,因为springBoot非常强大,
创建启动类
@SpringBootApplication
}
创建配置文件application.properties,因为springBoot会默认取加载这个配置文件
项目根路径
server.context-path=/bry
项目端口号
server.port=8090
是不是非常简单,下面在创建页面,通过controller访问页面,这一套跟springMVC就很像了,
咱们使用thymeleaf模板来处理页面,代替视图解析器,
在src/main/resources下面创建static和templates包,默认的静态资源是放在static里面的,页面是放在
templates里面的,当然可以自己去配置目录,但是没有必要,既然springBoot给我们提供了这么好的便利,我们为什么不用呢?
接下来,在templates里面定义一个index.html
在定义一个controller,加一个跳转的方法
@RequestMapping(value = { “index”}, method = RequestMethod.GET)
public String gotoIndex(Model model) {
return “index”;
}
这样就可以跳转到页面了,因为我们使用了强大的thymeleaf,一切他帮助我们处理了,
现在最简单的工程我们已经搭建起来了,是不是超级简单!
下面来说一下怎么整合mybatis:
1.还是整合jar,也就是编写pom.xml,
2.声明Mapper 接口和实现Mapper 的xml, 注意接口需要加上@Mapper,会自动扫描注入,例如:
@Mapper
public interface UserMapper (){}
然后定义UserMapper.xml,里面的内容跟mybatis写法一致,不在啰嗦.
3.application.properties加入连接数据库的信息:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://IP:3306/springSecurityTest?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
spring.datasource.validation-query=SELECT 1
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=27800
如此简单就整合了mybatis,看看springBoot是不是非常牛气啊,真的得说太赞了,不用想以前那么繁琐的配置了
最后来说一下怎么整合springsecurity.
1.还是老规矩,配置pom.xml
application.properties什么都不用配置就行.
2.接下来的步骤有点繁琐,首先为了看到效果我们创建几个表和对应的实体类
sys_role表 字段id,name
sys_user表 字段id,username,password
sys_role_user表 字段id,Sys_User_id,Sys_Role_id
3.插入几条数据
4.创建对应的实体类:
5.接下来是配置类WebSecurityConfig
6.其中用到了md5加密工具 ,这个经常用,不再啰嗦,你也可以使用别的加密方式,
例如 BCryptPasswordEncoder
7.新建 CustomUserService 用于将用户权限交给 springsecurity 进行管控;
8.定义controller 我们的配置里面配置了登录成功之后跳转到首页
跳转到登录页面
@RequestMapping(value = “/login”)
public String login() {
return “login”;
}
跳转到主页
@RequestMapping(value = {“/”,}, method = RequestMethod.GET)
public String gotohome() {
return “home”;
}
9.最后你可以自定义html页面,很简单了,这里不再啰嗦!
10.配置完springsecurity之后,你的controller就可以加权限了
11.如果你想使用 BCryptPasswordEncoder加密,配置文件需要修改成下面这样
存入数据库的加密方法如下:
end……..
首先搭建springBoot工程,pom.xml里面添加这些jar信息,就足够了,因为springBoot非常强大,
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.5.RELEASE</version> </parent>
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
创建启动类
@SpringBootApplication
public class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); }
public static void main(String[] args) { SpringApplication.run(Application.class, args); }
}
创建配置文件application.properties,因为springBoot会默认取加载这个配置文件
项目根路径
server.context-path=/bry
项目端口号
server.port=8090
是不是非常简单,下面在创建页面,通过controller访问页面,这一套跟springMVC就很像了,
咱们使用thymeleaf模板来处理页面,代替视图解析器,
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
在src/main/resources下面创建static和templates包,默认的静态资源是放在static里面的,页面是放在
templates里面的,当然可以自己去配置目录,但是没有必要,既然springBoot给我们提供了这么好的便利,我们为什么不用呢?
接下来,在templates里面定义一个index.html
在定义一个controller,加一个跳转的方法
@RequestMapping(value = { “index”}, method = RequestMethod.GET)
public String gotoIndex(Model model) {
return “index”;
}
这样就可以跳转到页面了,因为我们使用了强大的thymeleaf,一切他帮助我们处理了,
现在最简单的工程我们已经搭建起来了,是不是超级简单!
下面来说一下怎么整合mybatis:
1.还是整合jar,也就是编写pom.xml,
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
2.声明Mapper 接口和实现Mapper 的xml, 注意接口需要加上@Mapper,会自动扫描注入,例如:
@Mapper
public interface UserMapper (){}
然后定义UserMapper.xml,里面的内容跟mybatis写法一致,不在啰嗦.
3.application.properties加入连接数据库的信息:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://IP:3306/springSecurityTest?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
spring.datasource.validation-query=SELECT 1
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=27800
如此简单就整合了mybatis,看看springBoot是不是非常牛气啊,真的得说太赞了,不用想以前那么繁琐的配置了
最后来说一下怎么整合springsecurity.
1.还是老规矩,配置pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> </dependency>
application.properties什么都不用配置就行.
2.接下来的步骤有点繁琐,首先为了看到效果我们创建几个表和对应的实体类
sys_role表 字段id,name
sys_user表 字段id,username,password
sys_role_user表 字段id,Sys_User_id,Sys_Role_id
3.插入几条数据
INSERT INTO sys_role VALUES ('1', 'ROLE_ADMIN');
INSERT INTO sys_role VALUES ('2', 'ROLE_USER');
INSERT INTO sys_user VALUES ('1', 'admin', '6d789d4353c72e4f625d21c6b7ac2982'); INSERT INTO sys_user VALUES ('2', 'user', '36f1cab655c5252fc4f163a1409500b8');
INSERT INTO sys_role_user VALUES ('1', '1', '1'); INSERT INTO sys_role_user VALUES ('2', '2', '2');
4.创建对应的实体类:
public class SysRole { private Integer id; private String name;
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }
}
public class SysUser { private Integer id; private String username; private String password;
private List<SysRole> roles; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public List<SysRole> getRoles() { return roles; } public void setRoles(List<SysRole> roles) { this.roles = roles; }
}
5.接下来是配置类WebSecurityConfig
@Configuration //必须加这个注解,用于生成一个配置类, @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) //启用Security注解 public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean UserDetailsService customUserService() { // 注册UserDetailsService 的bean return new CustomUserService(); }
/** * 配置.忽略的静态文件,不加的话,登录之前页面的css,js不能正常使用,得登录之后才能正常. */ @Override public void configure(WebSecurity web) throws Exception { // 忽略URL web.ignoring().antMatchers("/**/*.js", "/lang/*.json", "/**/*.css", "/**/*.js", "/**/*.map", "/**/*.html", "/**/*.png"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(customUserService()).passwordEncoder(new PasswordEncoder(){ //使用MD5获取加密之后的密码 @Override public 4000 String encode(CharSequence rawPassword) { return MD5Util.encode((String)rawPassword); } //验证密码 @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return encodedPassword.equals(MD5Util.encode((String)rawPassword)); }}); //user Details Service验证 } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/").permitAll() //首页任意访问 .anyRequest().authenticated() // //其他所有资源都需要认证,登陆后才能访问 .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/", true)//登录成功之后跳转首页 .failureUrl("/login?error") //登录失败 返回error .permitAll() // 登录页面用户任意访问 .and() .logout().permitAll(); // 注销行为任意访问 }
}
6.其中用到了md5加密工具 ,这个经常用,不再啰嗦,你也可以使用别的加密方式,
例如 BCryptPasswordEncoder
public class MD5Util {
private static final String SALT = "tamboo"; public static String encode(String password) { password = password + SALT; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new RuntimeException(e); } char[] charArray = password.toCharArray(); byte[] byteArray = new byte[charArray.length]; for (int i = 0; i < charArray.length; i++) byteArray[i] = (byte) charArray[i]; byte[] md5Bytes = md5.digest(byteArray); StringBuffer hexValue = new StringBuffer(); for (int i = 0; i < md5Bytes.length; i++) { int val = ((int) md5Bytes[i]) & 0xff; if (val < 16) { hexValue.append("0"); } hexValue.append(Integer.toHexString(val)); } return hexValue.toString(); } public static void main(String[] args) { System.out.println(MD5Util.encode("admin")); System.out.println(MD5Util.encode("user")); }
}
7.新建 CustomUserService 用于将用户权限交给 springsecurity 进行管控;
@Service public class CustomUserService implements UserDetailsService { @Autowired UserMapper userMapper;
@Override public UserDetails loadUserByUsername(String username) { // 重写loadUserByUsername 方法获得 userdetails 类型用户 SysUser user = userMapper.findByUserName(username); if (user == null) { throw new UsernameNotFoundException("用户名不存在"); } List<SimpleGrantedAuthority> authorities = new ArrayList<>(); // 用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。 for (SysRole role : user.getRoles()) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities); }
}
8.定义controller 我们的配置里面配置了登录成功之后跳转到首页
跳转到登录页面
@RequestMapping(value = “/login”)
public String login() {
return “login”;
}
跳转到主页
@RequestMapping(value = {“/”,}, method = RequestMethod.GET)
public String gotohome() {
return “home”;
}
9.最后你可以自定义html页面,很简单了,这里不再啰嗦!
10.配置完springsecurity之后,你的controller就可以加权限了
@RequestMapping("/getuser") //必须有这个权限才可以使用 @Secured("ROLE_USER") @ResponseBody public User getUser() { User user = new User(); user.setName("test"); return user; }
11.如果你想使用 BCryptPasswordEncoder加密,配置文件需要修改成下面这样
@Autowired protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(customUserService).passwordEncoder(new BCryptPasswordEncoder()); }
存入数据库的加密方法如下:
public SysUser create(User u user){ //进行加密 BCryptPasswordEncoder encoder =new BCryptPasswordEncoder(); sysUser.setPassword(encoder.encode(user.getRawPassword().trim())); userDao.create(user); return sysUser; }
end……..
相关文章推荐
- SpringBoot + Mybatis plus 实现多数据源整合
- spring_boot整合mybatis项目启动时报错
- spring-boot | 使员Druid 整合Mybatis 最简配置多数据源
- springboot之整合mybatis-annotation(注解方式)
- 采用shardbatis在springBoot中实现表的水平拆分,整合swagger,mybatis,shardbatis,pagehelper
- SpringBoot非官方教程 | 第六篇:springboot整合mybatis
- spring boot和mybatis整合
- Eclipse+maven+springboot+mybatis整合
- Spring Boot + MyBatis + Redis整合小案例
- Spring Boot整合使用mybatis
- SpringBoot整合Spring Security和Mybatis验证
- SpringBoot、MyBatis、Shiro框架renren-security
- 关于Springboot整合mybatis启动的问题
- SpringBoot整合Mybatis
- Spring Boot 整合 MyBatis 并启用二级缓存
- java鬼混笔记:springboot 9、springboot整合mybatis加上分页功能
- springboot整合mybatis
- Spring Boot整合mybatis全注解入门教程
- springboot整合mybatis(xml版)
- Spring Boot相关知识(三) Spring Boot项目整合MyBatis