springboot springsecurity实现后台线路管理

https://github.com/fwm1/springboot-firetech.git
一、springsecurity实现权限控制

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //允许所有用户访问"/"
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/admin").permitAll()
                //其他地址的访问均需验证权限
                .anyRequest().authenticated()
                .and()
                .formLogin()
                //指定登录页是"/login"
                .loginPage("/login")
                //登录成功后默认跳转到
                .defaultSuccessUrl("/identify")
                .failureUrl("/failure")
                .permitAll()
                .usernameParameter("username")
                .passwordParameter("password")
                .and()
                .logout()
                .logoutUrl("/logout")
                //退出登录后的默认url是"/"
                .logoutSuccessUrl("/")
                .invalidateHttpSession(true)
                .permitAll();
        //解决非thymeleaf的form表单提交被拦截问题
        http.csrf().disable();

        //解决中文乱码问题
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);
        http.addFilterBefore(filter,CsrfFilter.class);
    }

    /*
    * 通过静态资源
    * */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/static/css/**","/static/js/**");
    }

    @Bean
    public UserDetailsService systemUserService(){
        return new UserService();
    }
    
    /*
    * 密码加密
    * */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(systemUserService()).passwordEncoder(new PasswordEncoder() {
            @Override
            public String encode(CharSequence rawPassword) {
                return MD5Util.encode((String)rawPassword);
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return encodedPassword.equals(MD5Util.encode((String)rawPassword));
            }
        });
    }
}

二、MD5加密工具类  MD5Util

public class MD5Util {
    private static final String SALT = "firetechsalt";

    public static String encode(String password) {
        password = password + SALT;
        MessageDigest md5;
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String resultPassWord;
        try {
            md5 = MessageDigest.getInstance("MD5");
            resultPassWord = base64Encoder.encode(md5.digest(password.getBytes("utf-8")));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return resultPassWord;
    }
}

 三、UserService实现UserDetailsService接口

@Component
@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SystemUser user = userMapper.select(s);
        if(user == null)
            throw new UsernameNotFoundException("用户名不存在");
        return user;
    }

    public List<SystemUser> findAllUser(int pageNum, int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        return  userMapper.selectAll();
    }

    public void addUser(String username,String rowPassword,int group_id,String info){
        String password = MD5Util.encode(rowPassword);
        userMapper.addUser(username, password, group_id,info);
    }

    public void deleteUser(String username){
        userMapper.deleteUser(username);
    }
}

 四、mybatis中用注解实现多对多关系(多对多就是双方都是一对多关系)

public class SystemUser implements UserDetails{
    private int userId;
    private String userName;
    private String groupId;
    private List<Route> routeList;
}
@Select("select * from `user_` where user_name = #{userName}")
@Results({
            /*这里要指明属性groupId与表字段的映射group_id*/
            @Result(id = true, property = "userId", column = "user_id"),
            @Result(property = "userName", column = "user_name"),
            @Result(property = "groupId", column = "group_id"),
            @Result(property = "routeList", column = "group_id",javaType = List.class,
                    many = @Many(select = "com.firetech.project.mapper.RouteMapper.findRouteByGroupId")
            )
    })
    SystemUser select(String userName);

 

public class Route {
    private String routeName;
    private int groupId;
    private List<SystemUser> userList;
}
@Select("select * from route_ where group_id = #{group_id}")
@Results({
            @Result(property = "routeName",column = "route_name"),
            @Result(property = "groupId",column = "group_id")
})
Route findRouteByGroupId(int group_id);

 五、application.properties

# sqllite
spring.datasource.driver-class-name=org.sqlite.JDBC
spring.datasource.jdbc-url=jdbc:sqlite:F:/sqlite.db

# UTF-8编码
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true

# jsp
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

# pageHelper
pagehelper.helper-dialect=sqlite
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql

note:

1.springsecurity会拦截静态资源,需要配置;
  springboot默认静态资源在/resources/static下,但如果要在static下加子文件夹的话,还是需要配置
    spring.mvc.static-path-pattern=/static/**

2.spring.datasource.driver-class-name=org.sqlite.JDBC
  spring.datasource.jdbc-url=jdbc:sqlite:F:/sqlite.db

3.springsecurity可以取得UserDetail但是得不到username:
    mybatis属性和字段映射要写完整,否则无法正确构造SystemUser对象

4.jsp获取登录用户名:
    ${pageContext.request.remoteUser}

5.在没有用ajax发送http请求的时候,在controller中可以通过return "redirect:/user/list";的方式进行页面跳转.
  在使用ajax对表单数据进行封装,并发送至controller进行处理后就不能用以往的方法进行处理, 而需要在ajax提交的函数里进行跳转的设置:
window.location.href="/busasst/user/linestation";

6.ajax向后台发送请求时,dataType指的是"后台"预期的返回数据类型,若后台没有返回数据或者返回数据不一致则会执行error的回调函数

7.Spring Boot 打jar包 无法响应jsp 问题
    1)增加jsp依赖

    2)编译插件版本指定1.4.2

    <plugin>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-maven-plugin</artifactId>
           <version>1.4.2.RELEASE</version>
    </plugin>
    3)<!-- 将src/main/webapp下的所有文件文件编译到classes/META-INF/resources下-->

    <resource>
           <directory>src/main/webapp</directory>
           <targetPath>META-INF/resources</targetPath>
           <includes>
                  <include>**/*.*</include>
           </includes>
    </resource>
       4)application 配置

         spring.mvc.view.prefix=/WEB-INF/views/
         spring.mvc.view.suffix=.jsp

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值