Springboot 正确跳转页面的几种方式

写springboot项目的时候,我们经常把js,css放在static下面,把html放在templates下面,然后如果不进行任何配置或者处理的话,我们想 访问页面,springboot会给我们抛出错误页,现在就说一下怎么能够正确跳转页面,我这边了解了三种方式

1. 使用controller的方式
这种方式比较简单粗暴就是对每一个要请求的页面需要加上对应的controller进行跳转,比如templates下面有index.html,想跳转的话需要写对应的controller


@Controller
public class JumpController {
    @RequestMapping("/index.html")
    public String index(){
        return "index";
    }
}

这样你访问http://127.0.0.1:8080/index.html 才能够正确跳转页面
这种每一个页面都要写对应的controller,虽然能实现功能,只是过于麻烦

2.自定义一个类实现WebMvcConfigurer 接口,并重写里面的addViewControllers方法添加关系对应

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
//addViewController就相当于上面第一种方式中的 @RequestMapping中的值,setViewName相当于返回的值
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index.html").setViewName("index");

    }
}

不过这种也需要所有的页面都在这里添加,所以还是很麻烦,于是就来到了第三种方式

3.自定义一个类,实现WebMvcConfigurer接口,并重写addResourceHandlers方法添加关系对应

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

   /* @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index.html").setViewName("index");

    }*/

//所有css,js,images等等都调到static路径下,其他的都跳到templates下
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/**").addResourceLocations("classpath:/templates/");
    }
}

三种方式都能实现页面的正确跳转.综合而言,第三种还是很方便!

 

### 解决Spring Boot Security 导致页面访问被拦截的方法 当在Spring Boot应用程序中集成了Spring Security之后,默认情况下所有的HTTP请求都会受到保护,这可能导致未预期的页面访问被拦截的情况发生。为了允许某些URL不受限制地访问或者自定义认证逻辑,可以调整配置。 #### 自定义SecurityConfig类来排除特定路径 创建一个新的`SecurityConfig`类并继承`WebSecurityConfigurerAdapter`(尽管官方建议不再扩展此适配器,在新版本中推荐使用更灵活的方式),可以在其中指定哪些资源不需要经过身份验证即可访问: ```java @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login", "/register", "/css/**", "/js/**").permitAll() // 允许匿名用户访问这些地址 .anyRequest().authenticated(); // 所有其他请求都需要认证 http.formLogin() .loginPage("/login") // 设置登录页为/login .defaultSuccessUrl("/") // 登录成功后的默认跳转页面 .failureUrl("/login?error=true"); // 登录失败重定向到带有错误参数的登录页 http.logout() .logoutUrl("/logout") // 注销链接设置为/logout .clearAuthentication(true); // 清除会话中的认证信息 } } ``` 上述代码片段展示了如何通过覆盖`configure()`方法来自定义HttpSecurity对象的行为[^1]。这里特别指定了几个静态文件夹以及注册和登录界面作为无需鉴权就能直接访问的内容;对于任何其他的请求,则要求用户提供有效的凭证才能继续浏览网站的功能区域。 另外一种方式是在不继承`WebSecurityConfigurerAdapter`的情况下编写配置类,并利用Java Config特性完成相同的工作。这种方式更加现代化并且符合当前的最佳实践指南。 #### 使用`WebSecurityCustomizer`接口简化配置 如果只需要简单地忽略一些公共API端点而不涉及复杂的业务逻辑处理,那么可以直接实现`WebSecurityCustomizer`接口来进行基本的安全性设定: ```java @Configuration public class PublicApiAccessConfiguration implements WebSecurityCustomizer { private static final String[] PUBLIC_APIS = {"/api/v1/public/**"}; public void customize(WebSecurity web){ web.ignoring().mvcMatchers(PUBLIC_APIS); } } ``` 这段代码的作用就是告诉Spring Security框架应该完全忽视对给定模式匹配下的所有请求执行任何形式的身份验证或授权检查过程[^2]。 #### 实现自己的`UserDetailsService` 为了让系统能够识别合法用户的凭据,还需要提供一个服务组件用于加载用户的具体详情数据。通常做法是让该组件实现`org.springframework.security.core.userdetails.UserDetailsService`接口,并返回代表已知账户的对象实例。下面给出了一种可能的设计思路: ```java @Service public class CustomUserService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String usernameOrEmail) throws UsernameNotFoundException { Optional<User> userOpt = userRepository.findByUsernameOrEmail(usernameOrEmail, usernameOrEmail); if (!userOpt.isPresent()) throw new UsernameNotFoundException("Invalid credentials"); Collection<SimpleGrantedAuthority> authorities = Arrays.stream(new String[]{"ROLE_USER"}).map(SimpleGrantedAuthority::new).collect(Collectors.toList()); return org.springframework.security.core.userdetails.User.builder() .username(userOpt.get().getUsername()) .password("{noop}" + userOpt.get().getPassword()) // 注意:生产环境中应启用加密存储密码 .authorities(authorities) .build(); } } ``` 在这个例子中,假设存在名为`UserRepository`的数据访问层负责查询数据库记录。一旦找到了对应的条目就会构建起相应的`UserDetails`实体以便后续由Spring Security框架进行进一步的操作,比如校验输入口令是否正确等[^3][^4]。
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值