SpringBoot基础
修改banner
在线制作网站:https://www.bootschool.net/ascii/
生成banner.txt并放在resources目录下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 _ooOoo_ o8888888o 88" . "88 (| ^_^ |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' | | \ .-\__ `-` ___/-. / ___`. .' /--.--\ `. . ___ ."" '< `.___\_<|>_/___.' >'"". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `-. \_ __\ /__ _/ .-` / / ========`-.____`-.___\_____/___.-`____.-'======== `=---=' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^ 佛祖保佑 永不宕机 永无BUG ^ ^ SpringBoot: ${spring-boot.version} ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SpringBoot整合thymeleaf
搭建thymeleaf环境并跑起来
添加maven依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 <dependency > <groupId > org.thymeleaf</groupId > <artifactId > thymeleaf-spring5</artifactId > <version > 3.0.11.RELEASE</version > </dependency > <dependency > <groupId > org.thymeleaf.extras</groupId > <artifactId > thymeleaf-extras-java8time</artifactId > <version > 3.0.4.RELEASE</version > </dependency >
在html中添加
1 <html xmlns:th ="http://www.thymeleaf.org" >
创建controller
1 2 3 4 5 6 7 8 @Controller public class HelloController { @RequestMapping({"/", "/index", "/index.html"}) public String toIndex (Model model) { model.addAttribute("msg" , "hello,springboot" ); return "index" ; } }
创建主页index.html
1 2 3 4 5 6 7 8 9 10 11 <!DOCTYPE html > <html lang ="en" xmlns:th ="http://www.thymeleaf.org" > <head > <meta charset ="UTF-8" > <title > Title</title > </head > <body > <h1 > 这是主页</h1 > <p th:text ="${msg}" > </p > </body > </html >
运行
SpringBoot整合mybatis
搭建环境并测试成功
创建数据库并添加数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 DROP TABLE IF EXISTS user; CREATE TABLE user ( id int(10) PRIMARY KEY, username varchar(255), password varchar(255), role varchar(255), ) ; INSERT INTO user VALUES (1, 'naclo', '123456', 'admin'); INSERT INTO user VALUES (2, 'root', 'root', 'admin'); INSERT INTO user VALUES (3, 'admin', 'admin', 'admin'); INSERT INTO user VALUES (4, 'guest', 'guest', 'guest'); INSERT INTO user VALUES (5, '张三', '123456', 'user'); INSERT INTO user VALUES (6, '李四', '123456', 'user');
添加maven依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > 8.0.19</version > </dependency > <dependency > <groupId > org.mybatis.spring.boot</groupId > <artifactId > mybatis-spring-boot-starter</artifactId > <version > 2.1.2</version > </dependency > <dependency > <groupId > org.projectlombok</groupId > <artifactId > lombok</artifactId > <version > 1.18.12</version > </dependency >
在application.yml里添加
1 2 3 4 5 6 7 8 mybatis: type-aliases-package: com.naclo.pojo mapper-locations: classpath:mapper/*.xml spring: datasource: username: root password: root url: jdbc:mysql://localhost:3306/springbootstudy?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
在pom.xml里添加
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <build > <resources > <resource > <directory > src/main/java</directory > <includes > <include > **/*.yml</include > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > false</filtering > </resource > <resource > <directory > src/main/resources</directory > <includes > <include > **/*.yml</include > <include > **/*.properties</include > <include > **/*.xml</include > <include > **/*.html</include > <include > **/*.css</include > <include > **/*.js</include > <include > **/*.txt</include > </includes > <filtering > false</filtering > </resource > </resources > </build >
编写实体类
1 2 3 4 5 6 7 8 9 @Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String username; private String password; private String role; }
编写mapper接口
1 2 3 4 5 @Repository @Mapper public interface UserMapper { public List<User> queryAllUser () ; }
编写mapper
1 2 3 4 5 6 7 8 9 10 <?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.naclo.mapper.UserMapper" > <select id ="queryAllUser" resultType ="User" > select * from user </select > </mapper >
编写测试类
1 2 3 4 5 6 7 8 9 10 @SpringBootTest public class UserMapperTest { @Autowired UserMapper userMapper; @Test public void queryAllUserTest () { userMapper.queryAllUser().forEach(System.out::println); } }
SpringBoot整合druid
添加maven依赖
1 2 3 4 5 6 <dependency > <groupId > com.alibaba</groupId > <artifactId > druid</artifactId > <version > 1.1.22</version > </dependency >
修改application添加数据源
创建DruidConfig
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 @Configuration public class DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druidDataSource () { return new DruidDataSource (); } @Bean public ServletRegistrationBean<StatViewServlet> statViewServlet () { ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean <StatViewServlet>(new StatViewServlet (), "/druid/*" ); Map<String, String> initParams = new HashMap <>(); initParams.put("loginUsername" , "admin" ); initParams.put("loginPassword" , "123456" ); initParams.put("allow" , "" ); bean.setInitParameters(initParams); return bean; } @Bean public FilterRegistrationBean<WebStatFilter> webStatFilter () { FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean <WebStatFilter>(); bean.setFilter(new WebStatFilter ()); Map<String, String> initParams = new HashMap <>(); initParams.put("exclusions" , "*.js,*.css,/druid/*" ); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*" )); return bean; } }
SpringBoot整合shiro
添加maven依赖
1 2 3 4 5 6 <!-- shiro-spring --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.5 .2 </version> </dependency>
编写UserService,查询用户名
创建UserRealm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 public class UserRealm extends AuthorizingRealm { @Autowired UserService userService; @Override protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principals) { System.out.println("执行了=>授权doGetAuthorizationInfo" ); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo (); Subject subject = SecurityUtils.getSubject(); User currentUser = (User) subject.getPrincipal(); Set<String> roleSet = new HashSet <>(); roleSet.add(currentUser.getRole()); info.setRoles(roleSet); return info; } @Override protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken token) throws AuthenticationException { System.out.println("执行了=>认证doGetAuthenticationInfo" ); UsernamePasswordToken userToken = (UsernamePasswordToken) token; User user = userService.queryUserByName(userToken.getUsername()); if (user==null ){ return null ; } return new SimpleAuthenticationInfo (user,user.getPassword(),"" ); } }
创建ShiroConfig
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 @Configuration public class ShiroConfig { @Bean public ShiroFilterFactoryBean getsShiroFilterFactoryBean (@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) { ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean (); bean.setSecurityManager(defaultWebSecurityManager); Map<String, String> filterMap = new LinkedHashMap <>(); filterMap.put("/user/*" , "roles[user]" ); filterMap.put("/admin/*" , "roles[admin]" ); filterMap.put("/guest/*" , "roles[guest]" ); filterMap.put("/logout" , "logout" ); filterMap.put("/login" , "anon" ); filterMap.put("/toLogin" , "anon" ); filterMap.put("/" , "anon" ); filterMap.put("/index" , "anon" ); filterMap.put("/**" , "authc" ); bean.setFilterChainDefinitionMap(filterMap); bean.setLoginUrl("/toLogin" ); bean.setUnauthorizedUrl("/noauth" ); return bean; } @Bean(name = "securityManager") public DefaultWebSecurityManager getDefaultWebSecurityManager (@Qualifier("userRealm") UserRealm userRealm) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager (); securityManager.setRealm(userRealm); return securityManager; } @Bean public UserRealm userRealm () { return new UserRealm (); } @Bean public ShiroDialect getShiroDialect () { return new ShiroDialect (); } }
常用拦截器
Filter
解释
anon
无需认证
auathc
需要认证
logout
登出
user
需要记住我才有用
perms[user]
需要某个或某些权限才能通过
roles[admin]
是某个或某些角色才能通过
创建controller跳转
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 @Controller public class HelloController { @RequestMapping({"/", "/index"}) public String toIndex (Model model) { model.addAttribute("msg" , "hello,springboot" ); return "index" ; } @RequestMapping("/admin/adminIndex") public String toAdminIndex () { return "adminIndex" ; } @RequestMapping("/guest/guestIndex") public String toGuestIndex () { return "guestIndex" ; } @RequestMapping("user/userIndex") public String toUserIndex () { return "userIndex" ; } @RequestMapping("toLogin") public String toLogin () { return "login" ; } @RequestMapping("/login") public String login (String username, String password, Model model) { Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken (username, password); try { subject.login(token); return "guest/guestIndex" ; return "index" ; } catch (UnknownAccountException e) { model.addAttribute("msg" , "用户名错误" ); return "login" ; } catch (IncorrectCredentialsException e) { model.addAttribute("msg" , "密码错误" ); return "login" ; } catch (LockedAccountException e) { model.addAttribute("msg" , "用户被锁定" ); return "login" ; } } @RequestMapping("/noauth") @ResponseBody public String unauthorized () { return "未经授权" ; } }
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <!DOCTYPE html > <html lang ="en" xmlns:th ="http://www.thymeleaf.org" xmlns:shiro ="http://www.pollix.at/thymeleaf/shiro" > <head > <meta charset ="UTF-8" > <title > Title</title > </head > <body > <h1 > 这是主页</h1 > <p th:text ="${msg}" > </p > <hr /> <a th:href ="@{/toLogin}" > login</a > <a th:href ="@{/logout}" > logout</a > <a th:href ="@{/user/userIndex}" > user</a > <a th:href ="@{/admin/adminIndex}" > admin</a > <a th:href ="@{/guest/guestIndex}" > guest</a > </body > </html >
login.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <!DOCTYPE html > <html lang ="en" xmlns:th ="http://www.thymeleaf.org" > <head > <meta charset ="UTF-8" > <title > Title</title > </head > <body > <h1 > 登陆</h1 > <hr /> <p th:text ="${msg}" style ="color: red" > </p > <form th:action ="@{/login}" > <p > 用户名: <input type ="text" name ="username" > </p > <p > 密码: <input type ="text" name ="password" > </p > <p > <input type ="submit" > </p > </form > </body > </html >
设置登陆后按照不同角色跳转不同页面
在controller里,登陆成功之后判断角色,并进行跳转,添加代码
1 2 3 4 5 if (subject.hasRole("admin" )) return "admin/adminIndex" ; if (subject.hasRole("user" )) return "user/userIndex" ; if (subject.hasRole("guest" ))
shiro整合thymeleaf
添加maven依赖
1 2 3 4 5 6 <dependency > <groupId > com.github.theborakompanioni</groupId > <artifactId > thymeleaf-extras-shiro</artifactId > <version > 2.0.0</version > </dependency >
html添加命名空间
1 <html lang ="en" xmlns:shiro ="http://www.pollix.at/thymeleaf/shiro" >
在ShiroConfig添加Bean
1 2 3 4 @Bean public ShiroDialect getShiroDialect () { return new ShiroDialect (); }
不同用户显示不同的按钮
1 2 3 4 5 6 7 8 9 <div shiro:hasAnyRoles ="user" > <a th:href ="@{/user/userIndex}" > user</a > </div > <div shiro:hasAnyRoles ="admin" > <a th:href ="@{/admin/adminIndex}" > admin</a > </div > <div shiro:hasAnyRoles ="guest" > <a th:href ="@{/guest/guestIndex}" > guest</a > </div >
已有用户登陆不显示登陆按钮,未有用户登陆不显示登出按钮
登陆成功,添加session
1 2 Session session = subject.getSession();session.setAttribute("loginUser" ,username);
页面上添加
1 2 3 4 5 6 <div th:if ="${session.loginUser}==null" > <a th:href ="@{/toLogin}" > login</a > </div > <div th:if ="${session.loginUser}!=null" > <a th:href ="@{/logout}" > logout</a > </div >
sss
SpringBoot整合poi
添加maven依赖
SpringBoot整合easyexcel
添加maven依赖
SpringBoot整合zookeeper+dubbo
SpringBoot整合swagger