基于Java+SpringBoot+Vue前后端分离手机销售商城系统设计和实现
warning:
这篇文章距离上次修改已过180天,其中的内容可能已经有所变动。
由于篇幅所限,以下仅展示如何使用Spring Security配置路径的安全性,以及如何创建一个简单的商品列表API接口。
// 导入Spring Security相关的依赖
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // 禁用CSRF保护
.authorizeRequests()
.antMatchers("/h5/**", "/user/login", "/act/page", "/act/list", "/act/detail", "/user/register").permitAll() // 允许这些路径无需认证访问
.anyRequest().authenticated() // 其他所有请求需要认证
.and()
.addFilter(new JWTLoginFilter(authenticationManager())) // 添加登录过滤器
.addFilter(new JWTAuthenticationFilter(authenticationManager())); // 添加认证过滤器
}
}
// 导入Spring Boot和Spring Data JPA依赖
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
@RestController
@RequestMapping("/api/product")
public class ProductController {
@Autowired
private ProductService productService;
// 获取商品列表
@GetMapping("/list")
public ResponseEntity<?> getProductList(Pageable pageable) {
Page<Product> page = productService.findAll(pageable);
return ResponseEntity.ok().body(new PageImpl<>(page.getContent(), pageable, page.getTotalElements()));
}
// 其他接口方法
}
以上代码展示了如何在Spring Boot应用中使用Spring Security来保护API端点,并且如何创建一个简单的商品列表API接口。这只是一个基本的例子,实际应用中需要更多的安全性配置和细节,比如Token的生成和验证。
评论已关闭