spring boot static静态资源访问及tempates资源访问 sercurity初始项目

本文介绍了在Spring Boot中如何正确访问static静态资源和templates模板资源,尤其是在涉及security安全配置时的注意事项。通过示例,演示了controller的正确编写方式,以避免报错。同时,提到了添加security依赖后,界面显示的变化。
摘要由CSDN通过智能技术生成

在这里插入图片描述
作为示例,在static文件夹下放置一个html文件
在这里插入图片描述
启动tomcat直接访问是没有问题
如果把controller这样写
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
不得不说这个报错还是很有误导性
在这里插入图片描述
只有这样写
在这里插入图片描述
访问接口是没有问题的
加入templates依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

在这里插入图片描述
在这里插入图片描述
发现这个界面并不是那个粗糙的界面
因为添加了sercurity依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
以下是Spring Boot Security配置方法: 1.添加依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2.配置安全性 在application.properties文件中添加以下配置: ```properties # 禁用CSRF保护 security.enable-csrf=false # 配置登录页面 spring.security.login-page=/login # 配置登录处理接口 spring.security.login-processing-url=/doLogin # 配置退出登录接口 spring.security.logout-url=/logout # 配置退出登录成功后跳转的页面 spring.security.logout-success-url=/ ``` 3.创建用户 在SecurityConfig类中创建用户: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password(passwordEncoder().encode("password")).roles("USER") .and() .withUser("admin").password(passwordEncoder().encode("password")).roles("ADMIN"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 4.配置访问权限 在SecurityConfig类中配置访问权限: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .loginProcessingUrl("/doLogin") .defaultSuccessUrl("/") .permitAll() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/") .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password(passwordEncoder().encode("password")).roles("USER") .and() .withUser("admin").password(passwordEncoder().encode("password")).roles("ADMIN"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 5.测试 启动应用程序并访问受保护的页面,将会自动跳转到登录页面。输入正确的用户名和密码后,将会跳转回原始请求的页面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值