Spring Boot遇到的一些问题

MyBatis Pagehelper分页

1. pom引入pagehelper包



            com.github.pagehelper
            pagehelper-spring-boot-starter
            1.2.3
        

2. 在application.properties配置PageHelper

#MyBatis分页插件配置
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

3. 创建实体类

public class User {

    Integer id;
    String name;
    Integer age;

    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

4. 创建mapper类userMapper

public interface UserMapper {

    @Select("select * from user")
    List findAll();
}

5.创建service类userService

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    public PageInfo findAll(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List userList = userMapper.findAll();
        PageInfo pageInfo = new PageInfo<>(userList);
        return pageInfo;
    }
}

6. 创建 controller 类 UserController

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("findAll")
    public PageInfo getUser(int pageNum, int pageSize) {
        return userService.findAll(pageNum,pageSize);
    }
}

7. 运行程序后,使用Http请求测试

Shiro-Spring-Boot-Web-Starter

1. pom文件导入jar包

  
        
            org.apache.shiro
            shiro-spring-boot-web-starter
            1.4.0
        
        
        
            com.github.theborakompanioni
            thymeleaf-extras-shiro
            2.0.0
        

2. 在application.properties配置Shiro


shiro.loginUrl=/login  

shiro.successUrl=/home

shiro.unauthorizedUrl=/403

4. 创建编写shiroConfig配置类

package com.truth.bug.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;


@Configuration
@ControllerAdvice
public class ShiroConfig {

    private Logger logger = LoggerFactory.getLogger(ShiroConfig.class);

    /**
     * 处理Shiro异常
     */
    @ExceptionHandler(AuthorizationException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public void authorizationExceptionHandler() {
        logger.error("没有权限访问该资源");
    }


    @Bean
    public Realm realm() {
        return new MyShiroRealm();
    }

    @Bean
    public CacheManager cacheManager() {
        return new MemoryConstrainedCacheManager();
    }


    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        chainDefinition.addPathDefinition("/favicon.ico", "anon");
        chainDefinition.addPathDefinition("/dist/**", "anon");
        chainDefinition.addPathDefinition("/bootstrap/**", "anon");
        chainDefinition.addPathDefinition("/plugins/**", "anon");
        chainDefinition.addPathDefinition("/css/**", "anon");
        chainDefinition.addPathDefinition("/js/**", "anon");
        chainDefinition.addPathDefinition("/img/**", "anon");
        chainDefinition.addPathDefinition("/", "anon");
        chainDefinition.addPathDefinition("/logout", "logout");
        chainDefinition.addPathDefinition("/**", "authc");
        return chainDefinition;
    }

    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }

}

4. 编写自己Realm类

package com.truth.bug.shiro;

import com.truth.bug.entity.Role;
import com.truth.bug.entity.User;
import com.truth.bug.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by Truth on 2018/8/31 0031 14:34
 */

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //用户认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        if (principalCollection == null){
            throw new AuthenticationException("PrincipalCollection方法参数不能为null");
        }
        User user = (User) getAvailablePrincipal(principalCollection);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        
        List roleList = user.getRoles();
        Set roles = new HashSet<>();
        for (int i = 0;i < roleList.size();i++){
            roles.add(roleList.get(i).getRoleName());
        }

        info.setRoles(roles);
        return null;
    }

    //用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //加这一步的目的是在Post请求的时候会先进认证,然后在到请求
        if (authenticationToken.getPrincipal() == null){
            return null;
        }
        //获取用户信息
        String phone = authenticationToken.getPrincipal().toString();
        User user = userService.findUser(phone);
        if (user == null){
            //这里返回后会报出对应异常
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        authenticationInfo.setCredentials(user);
        return authenticationInfo;
    }
}

4. Login控制器示例

  @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(String phone,String password, HttpSession session){

        UsernamePasswordToken token = new UsernamePasswordToken(phone, DigestUtils.md5Hex(password + passwordSalt));
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(token);
            session.setAttribute("user",subject.getPrincipal());
            return AjaxResult.success();
        }catch (AuthenticationException ex){
            return  AjaxResult.error("账号或密码错误");
        }
    }

5.登录用户修改个人信息后,不重新登陆进行同步更新

 public AjaxResult updateUser(User user){
            
           User user1 = (User)SecurityUtils.getSubject().getPrincipal();
          
           userService.updateUser(user);
          
           user1.setUserName(user.getUserName());
           return AjaxResult.success();
        }

你可能感兴趣的:(Spring Boot遇到的一些问题)