目录
常用记录
虚拟目录映射
MyPicConfig
@Configuration
public class MyPicConfig implements WebMvcConfigurer {
/**
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").
addResourceLocations("file:" + ProjectConfig.getProjectUploadDir()+ "/");
System.out.println("Upload Dir:" + ProjectConfig.getProjectUploadDir());
}
}
ProjectConfig
public class ProjectConfig {
static public File getProjectUploadDir(){
String a = System.getProperty("user.dir");
File file = new File(a + "/upload/");
if(!file.exists()){
//不存在创建文件夹
file.mkdirs();
}
return file;
}
}
控制器
FileController
@RequestMapping("/file") //资源url前缀 /file/xxx
@RestController //Rest控制器
public class FileController {
/*
* 自动装配 mybatis
* */
@Autowired
private FileMapper fileMapper;
@GetMapping //GET映射
public Result hello(){
List<FileBean> files = fileMapper.getAllFile();
return new Result(files,true);
}
@DeleteMapping("/{id}") //Delete方法映射 /{id} 要想在函数形参里使用 要加个 @PathVariable
public Result delete(@PathVariable Integer id){
Integer result = fileMapper.deleteFile(id);
return new Result(null,result == 0 ? false : true);
}
/*上传*/
@PostMapping()
public Result upload(@RequestParam MultipartFile doc) throws Exception {
String OriginalFilename = doc.getOriginalFilename();//获取原文件名
String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));//获取文件后缀名
//重新随机生成名字
String filename = UUID.randomUUID().toString() +suffixName;
//拼接路径
File localFile = new File(ProjectConfig.getProjectUploadDir() +"/"+filename);
//移动
doc.transferTo(localFile);
return new Result(filename,true);
}
@GetMapping("/test")
public String test() throws IOException {
String realPath = ResourceUtils.getURL("classpath:").getPath() + "static";
return realPath;
}
}
配置Mybatis
一、入口文件添加扫描mapper
DmApplication
@SpringBootApplication
@MapperScan(basePackages = "com.xxx.xxx.mapper") //这里是重点 ,要扫描的包
public class DmApplication {
public static void main(String[] args) {
SpringApplication.run(DmApplication.class, args);
}
}
二、定义mapper接口
FileMapper
@Mapper
public interface FileMapper {
@Select("SELECT * FROM files")
ArrayList<FileBean> getAllFile();
@Select("SELECT * FROM files where id = #{id}")
FileBean getFile(Integer id);
@Delete("DELETE FROM files where id = #{id}")
Integer deleteFile(Integer id);
}
三、定义bean
FileBean
public class FileBean {
private Integer id;
private String user;
private String displayname;
private Date time;
private String realfilepath;
//这里要自动生成一下set和get,构造函数。
}
四 、配置数据库信息
application.properties
# 应用名称
spring.application.name=dm
# 应用服务 WEB 访问端口
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
配置Mybatis PLUS
一、添加依赖
可以使用 Spring Initializer 快速初始化一个 Spring Boot 工程,勾选MyBatis PLUS + MySQL Driver
二、在 application.yml 配置文件中添加 MYSQL 数据库的相关配置:
spring:
datasource:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useSSL=false&rewriteBatchedStatements=true&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
server:
port: 8080
三、在 Spring Boot 启动类中添加 @MapperScan
注解,扫描 Mapper 文件夹:
@MapperScan("com.example.mybatisplus.mapper")
public class MybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisplusApplication.class, args);
}
}
四、编码
编写实体类 User.java(此处使用了 Lombok (opens new window)简化代码)
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
编写 Mapper 包下的 UserMapper
接口
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
五、使用
自动装配
@Autowired
private UserMapper userMapper;
常用代码
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
userList.forEach(System.out::println);
}
@Test
public void testSave() {
System.out.println(("----- save method test ------"));
User user = new User(); //创建对象
user.setAge(1); //设置年龄
user.setEmail("1"); //设置邮箱
user.setName("1"); //设置姓名
userMapper.insert(user); //保存
}
@Test
public void testDelete(){
userMapper.deleteById(1);
}
@Test
public void testUpdate(){
User user = new User();
user.setId(2L);
user.setName("Test");
userMapper.updateById(user);
}
页码
MybatisPlusConfig ( 设置拦截器 )
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
@Test
public void testGetByPage(){
Page<User> page = new Page<>(2, 2);//两个参数,第一个当前页码,第二个一个页码显示几个数据
Page<User> userPage = userMapper.selectPage(page, null);
userPage.getRecords().forEach(System.out::println);
}
DQL编程控制
@Test
public void testGetWrapperData(){
//方式一:按条件查询
QueryWrapper wrapper = new QueryWrapper();
wrapper.lt("id","4");
List<User> userList = userMapper.selectList(wrapper);
System.out.println(userList);
//方式二:lambda格式按条件查询
QueryWrapper<User> wrapper2 = new QueryWrapper();
wrapper2.lambda().lt(User::getId,4);
List<User> userList2 = userMapper.selectList(wrapper2);
System.out.println(userList2);
//方式三:lambda格式按条件查询
LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>();
lqw.lt(User::getId,4);
List<User> userList3 = userMapper.selectList(lqw);
System.out.println(userList3);
}
拦截器
一、创建拦截器类
package com.example.mybatisplus.controller.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class ProjectInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHanlder");
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
二、指定拦截规则/注册拦截器
package com.example.mybatisplus.config;
import com.example.mybatisplus.controller.interceptor.ProjectInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
System.out.println("注册拦截器");
registry.addInterceptor(new ProjectInterceptor()).addPathPatterns("/**") //拦截所有请求,包括静态资源文件
.excludePathPatterns("/", "/login", "/index.html", "/user/login", "/css/**", "/images/**", "/js/**", "/fonts/**"); //放行登录页,登陆操作,静态资源
}
}
Shiro
简单使用,通过配置文件读取账号密码
@Test
void TestShiro(){
//1.创建安全管理器
DefaultSecurityManager securityManager = new DefaultSecurityManager();
//2.给安全管理器设置realm
securityManager.setRealm(new IniRealm("classpath:shiro.ini"));
//3.SecurityUtils 给全局安全工具类设置安全管理器
SecurityUtils.setSecurityManager(securityManager);
//4.关键对象 subject 主体
Subject subject = SecurityUtils.getSubject();
//5.创建令牌
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("zhang","1123");
try{
subject.login(usernamePasswordToken);
System.out.println("认证状态:"+subject.isAuthenticated());
}catch (UnknownAccountException e) {
e.printStackTrace();
System.out.println("用户不存在");
}catch (IncorrectCredentialsException e){
e.printStackTrace();
System.out.println("密码错误");
}
}
shiro.ini
[users]
zhang=123
wang=123
自定义realm
新建一个CustomRealm类继承AuthorizingRealm
public class CustomRealm extends AuthorizingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String principal = (String) authenticationToken.getPrincipal();
//存在用户就去构造一个AuthenticationInfo 给shiro验证
if("zhang".equals(principal)){
//数据库中的 用户名和密码
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("zhang","1232",this.getName());
return simpleAuthenticationInfo;
}
//不存在该用户就返回null
return null;
}
}
给安全管理器传realm的时候传自定义的
//2.给安全管理器设置realm
securityManager.setRealm(new CustomRealm());
设置MD5比较器
//1.创建安全管理器
DefaultSecurityManager securityManager = new DefaultSecurityManager();
//2.给安全管理器设置realm
Md5Realm realm = new Md5Realm();
//设置凭证匹配器
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
credentialsMatcher.setHashAlgorithmName("md5");
realm.setCredentialsMatcher(credentialsMatcher);
//
securityManager.setRealm(realm);
..........
角色控制
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println(principalCollection.getPrimaryPrincipal());
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addRole("admin");//添加角色
simpleAuthorizationInfo.addStringPermissions(Collections.singleton("user:*:01"));//添加权限
return simpleAuthorizationInfo;
}
最新回复