spring boot常用依赖
<!-- jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- 模板引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- spring-boot 测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- swagger 后端接口调试-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- 测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- 邮箱-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- durid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
<!--日志文件-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- json字符串-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
<!-- 天气api-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- 权限管理https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
spring boot 常见配置
durid
package com.wzh.root.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* 用户:hahao
* 日期:2023/2/23
* 时间:23:33
* 类名:DruidConfig
*/
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
//配置 Druid 监控管理后台的Servlet;
//内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new
StatViewServlet(), "/druid/*");
// 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet
// 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername", "admin"); //后台管理界面的登录账号
initParams.put("loginPassword", "123456"); //后台管理界面的登录密码
//后台允许谁可以访问
//initParams.put("allow", "localhost"):表示只有本机可以访问
//initParams.put("allow", ""):为空或者为null时,表示允许所有访问
initParams.put("allow", "");
//deny:Druid 后台拒绝谁访问
//initParams.put("wzh", "192.168.1.20");表示禁止此ip访问
//设置初始化参数
bean.setInitParameters(initParams);
return bean;
}
}
httpclient
package com.wzh.root.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
/**
* api调用 需要配置RestTemplate
*/
@Configuration
public class WeatherConfig {
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
}
mvc配置
package com.wzh.root.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 用户:hahao
* 日期:2023/2/24
* 时间:9:57
* 类名:WebMvcConfig
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
// 浏览器发送/test , 就会跳转到test页面;
registry.addViewController("/login").setViewName("login");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//静态资源释放
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/","classpath:/templates/");
}
}
配置文件
spring.mail.username=2357@qq.com
spring.mail.password=wbi
spring.mail.host=smtp.qq.com
# qq需要配置ssl
spring.mail.properties.mail.smtp.ssl.enable=true
测试
package com.wzh.sbemil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class SbEmilApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
//邮件设置1:一个简单的邮件
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("标题-wzh");
message.setText("内容-test");
message.setTo("2837@qq.com");
message.setFrom("28357@qq.com");
mailSender.send(message);
}
@Test
public void contextLoads2() throws MessagingException {
//邮件设置2:一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("标题");
helper.setText("<b style='color:red'>小趴菜</b>",true);
//发送附件
helper.addAttachment("绝对路径.jpg",new File("F:\\spring-boot\\sb-emil\\src\\main\\resources\\jpg.jpg"));
helper.addAttachment("相对路径.jpg",new File("src/main/resources/jpg.jpg"));
// helper.setTo("283757@qq.com");
//发送的地址
helper.setTo("224224@qq.com");
//helper.setFrom("22224@qq.com");
//发送者
helper.setFrom("283757@qq.com");
mailSender.send(mimeMessage);
}
}
shiro权限控制
shiro的配置
package com.wzh.sbshiro.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 用户:hahao
* 日期:2023/1/25
* 时间:16:41
* 类名:ShiroConfig
* 由下往上关联
*/
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("shirobean") DefaultWebSecurityManager manager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(manager);
//添加内置管理器
//anon 无需认证
//authc 认证访问
//user 记住我访问
//perms 对某个资源有权限才可以访问
//roles 拥有角色权限可以访问
Map<String, String> filterChainDefinitionMap=new LinkedHashMap<>();
//授权管理 写在下面的配置上面(必须) 在UserRealm里面进行授权
filterChainDefinitionMap.put("/user/add","perms[user:add]");
filterChainDefinitionMap.put("/user/update","perms[user:update]");
//添加配置
filterChainDefinitionMap.put("/user/*", "authc");
//没有登录 跳转到登录页面
bean.setLoginUrl("/tologin");
//没有授权 跳转到授权页面
bean.setUnauthorizedUrl("/unauth");
//注入配置
bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return bean;
}
@Bean(name = "shirobean")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
//关联
DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
manager.setRealm(userRealm);
//去除url的session
manager.setSessionManager(mySessionManager());
return manager;
}
@Bean//第一步 创建realm类
public UserRealm userRealm(){
return new UserRealm();
}
//整合shiro和thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
@Bean
public DefaultWebSessionManager mySessionManager(){
//shiro在第一次启动时会有JSESSIONID在url上面 导致报错 需要配置该类
//并在getDefaultWebSecurityManager方法中添加manager.setSessionManager(mySessionManager());
DefaultWebSessionManager defaultSessionManager = new DefaultWebSessionManager();
//将sessionIdUrlRewritingEnabled属性设置成false
defaultSessionManager.setSessionIdUrlRewritingEnabled(false);
return defaultSessionManager;
}
}
shiro的自定义realm
package com.wzh.sbshiro.config;
import com.wzh.sbshiro.pojo.User;
import com.wzh.sbshiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
/**
* 用户:hahao
* 日期:2023/1/25
* 时间:16:41
* 类名:UserRealm
*
* 自定义的realm 这个类似security的config
*/
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权");
//添加权限
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// info.addStringPermission("user:add");
//获取当前用户信息
Subject subject = SecurityUtils.getSubject();
//拿到user
User currentUser = (User) subject.getPrincipal();
// System.out.println(currentUser);
// System.out.println(currentUser.getPerms());
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//String name="1" string password="1" 伪造数据
//转换 传参的token就是登录页面输入的token 可以类型转换 方便比较数据库的内容
UsernamePasswordToken usertoken= (UsernamePasswordToken) authenticationToken;
//数据 数据库数据
User user = userService.queryUserBuName(usertoken.getUsername());
if (user==null //没有这个用户
//!usertoken.getUsername().equals(user) 伪造数据
){
//账号不对 抛出异常 UnknownAccountException 在配置页面接收ConfigController
return null;
}
//密码验证
//加密 md5
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
//加密算法的名称
hashedCredentialsMatcher.setHashAlgorithmName("MD5");
//是否让它 进行16进制的编码
hashedCredentialsMatcher.isStoredCredentialsHexEncoded();
// 迭代的次数
//hashedCredentialsMatcher.setHashIterations(3);
SimpleHash simpleHash = new SimpleHash("MD5",user.getPassword() );
//密码认证 shiro帮我们做 第一个参数放user 方便上面权限获取
return new SimpleAuthenticationInfo(user,simpleHash.toHex(),"");
}
}
swagger
配置
package com.wzh.sbswagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.web.context.support.HttpRequestHandlerServlet;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
/**
* 用户:hahao
* 日期:2023/1/26
* 时间:17:31
* 类名:SwaggerConfig
*/
@Configuration //配置类
@EnableSwagger2// 开启Swagger2的自动配置
//swagger3.0版本需要访问http://localhost:8080/swagger-ui/index.html
public class SwaggerConfig {
//配置 swagger的docket实例
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//给自己的测试取名字
.groupName("wzh")
//不开启swagger 默认是true
//.enable(false)
.select()
//RequestHandlerSelectors 配置扫描方法
// .any 所有
//basePackage(com.wzh.sbswagger,controller)基于某个包
//.withMethodAnnotation() 扫描方法上面的注解 注解。class
//withClassAnnotation() 扫描类上的注解 注解.class
//none() 都不扫描
.apis(RequestHandlerSelectors.any())
//过滤 只扫描下面的路径
// .paths("/hello")
.build()
;
}
//配置多个docket
@Bean
public Docket docket1(Environment environment){
//设置要显示的swagger环境
Profiles profiles = Profiles.of("dev", "test");
//获取项目的环境 决定是否开启swagger
boolean b = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//传入参数
.enable(b)
.select()
.apis(RequestHandlerSelectors.any())
.build();
}
@Bean
public ApiInfo apiInfo(){
return new ApiInfo(
"wzh的swagger", //title
"大大的描述", //介绍
"v1.0",
"http:localhost:8080/", //组网站
new Contact("wzh","www.baidu.com","sdfslfsni@qq.com"),//作者的描述
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()
);
}
}
security
配置
package sbs.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import javax.annotation.Resource;
import javax.sql.DataSource;
/**
* 用户:hahao
* 日期:2023/1/24
* 时间:12:16
* 类名:config
*
* 有关安全的配置
*/
@EnableWebSecurity
public class config extends WebSecurityConfigurerAdapter {
@Resource
DataSource dataSource;
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问
http.authorizeHttpRequests().antMatchers("/").permitAll()
//赋予各级权限
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限到登录页 登录页面
http.formLogin().loginPage("/tologin").loginProcessingUrl("/login");
//退出清理cookie 删除session 权限
//http.logout().deleteCookies("remove").invalidateHttpSession(true);
http.logout();
//关闭csrf 不然注销不掉
http.csrf().disable();
//退出登录到首页
http.rememberMe().rememberMeParameter("remember");
http.logout().logoutSuccessUrl("/");
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//赋予权限 内存 设置密码权限
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("vip1").and()
.withUser("wzh").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2").and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3");
//使用数据库
// auth.jdbcAuthentication().dataSource(dataSource).withDefaultSchema().withUser().password().roles();
}
}