javaparser-lombok
时间: 2024-08-14 13:02:05 浏览: 147
`javaparser-lombok`是一个Java库,它是由Lombok团队维护的。Lombok是一个流行的Java库,它通过提供注解(Annotations),简化了Java代码编写,减少了样板(boilerplate)代码,如getter、setter、equals、hashCode等。Javaparser则是一个强大的Java源码解析库,它允许开发者动态地分析和修改Java源代码。
当你将Lombok和Javaparser结合使用时,可以创建更简洁、易读的代码,并利用Javaparser的功能来处理或生成基于源代码的自动化任务,比如从已存在的Java类结构自动生成相应的Builder类,或者对代码进行深度分析和重构。
相关问题
springboot security项目 如何封装jwt 及token 其中数据表为package com.aokace.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; /** * <p> * * </p> * * @author aokace * @since 2023-05-23 */ @Getter @Setter @TableName("user") @ApiModel(value = "User对象", description = "") public class User implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "userid", type = IdType.AUTO) private Integer userid; @TableField("authority") private String authority; @TableField("role") private String role; @TableField("username") private String username; @TableField("password") private String password; }
首先需要引入相关的依赖,包括JWT和Spring Security的依赖:
```
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
然后创建一个JwtTokenUtil类来实现JWT的签发和验证功能:
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtTokenUtil {
private static final String CLAIM_KEY_USERNAME = "sub";
private static final String CLAIM_KEY_CREATED = "created";
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
claims.put(CLAIM_KEY_CREATED, new Date());
return generateToken(claims);
}
public String getUsernameFromToken(String token) {
String username;
try {
Claims claims = getClaimsFromToken(token);
username = claims.getSubject();
} catch (Exception e) {
username = null;
}
return username;
}
public Date getCreatedDateFromToken(String token) {
Date created;
try {
Claims claims = getClaimsFromToken(token);
created = new Date((Long) claims.get(CLAIM_KEY_CREATED));
} catch (Exception e) {
created = null;
}
return created;
}
public Date getExpirationDateFromToken(String token) {
Date expiration;
try {
Claims claims = getClaimsFromToken(token);
expiration = claims.getExpiration();
} catch (Exception e) {
expiration = null;
}
return expiration;
}
public boolean isTokenExpired(String token) {
Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
public String refreshToken(String token) {
String refreshedToken;
try {
Claims claims = getClaimsFromToken(token);
claims.put(CLAIM_KEY_CREATED, new Date());
refreshedToken = generateToken(claims);
} catch (Exception e) {
refreshedToken = null;
}
return refreshedToken;
}
public boolean validateToken(String token, UserDetails userDetails) {
String username = getUsernameFromToken(token);
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
}
private Claims getClaimsFromToken(String token) {
Claims claims;
try {
claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
claims = null;
}
return claims;
}
private String generateToken(Map<String, Object> claims) {
Date expirationDate = new Date(System.currentTimeMillis() + expiration * 1000);
JwtBuilder builder = Jwts.builder()
.setClaims(claims)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, secret);
return builder.compact();
}
}
```
其中,JwtTokenUtil类中的generateToken方法用于生成JWT Token,getUsernameFromToken和getExpirationDateFromToken方法用于解析JWT Token中的用户名和过期时间,isTokenExpired方法用于判断JWT Token是否已经过期,refreshToken方法用于刷新JWT Token,validateToken方法用于验证JWT Token是否有效,getClaimsFromToken方法用于从JWT Token中获取Claims。
然后在Spring Security的配置类中添加JwtTokenFilter来实现JWT的过滤和验证:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtTokenFilter jwtTokenFilter;
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
```
其中,SecurityConfig类中的configure方法用于配置Spring Security的策略,addFilterBefore方法用于添加JwtTokenFilter,authenticationManagerBean方法用于获取AuthenticationManager。
最后,在登录接口中,使用JwtTokenUtil生成JWT Token并返回给前端:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private UserDetailsService userDetailsService;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody AuthRequest authRequest) throws Exception {
try {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword())
);
UserDetails userDetails = userDetailsService.loadUserByUsername(authRequest.getUsername());
String token = jwtTokenUtil.generateToken(userDetails);
return ResponseEntity.ok(new AuthResponse(token));
} catch (Exception e) {
throw new Exception("Incorrect username or password", e);
}
}
}
```
其中,AuthController类中的login方法用于处理登录请求,通过authenticationManager.authenticate方法验证用户名和密码,然后使用JwtTokenUtil生成JWT Token并返回给前端。
可以用springboot+mybatis-plus编写后端代码用户登录注册以及用户车位信息的增删改查(使用JWT+token以及拦截器和异常处理)的完整后端代码吗(不用给我依赖xml文件
好的,以下是使用Spring Boot和Mybatis-Plus编写的用户登录注册和车位信息增删改查的完整后端代码,同时使用了JWT+token、拦截器和异常处理。
首先是pom.xml文件:
```xml
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Mybatis-Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
```
接下来是application.properties文件:
```properties
# 数据库配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
# Mybatis-Plus 配置
mybatis-plus.mapper-locations=classpath*:mapper/*.xml
mybatis-plus.type-aliases-package=com.example.demo.model
# JWT 配置
jwt.secret=YourSecretKey
jwt.expire-time=3600000
```
其中,jwt.secret为JWT的密钥,jwt.expire-time为JWT的过期时间,单位为毫秒。
接下来是实体类User.java:
```java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String username;
private String password;
}
```
实体类ParkingLot.java:
```java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ParkingLot {
private Long id;
private String name;
private Integer capacity;
private Integer vacant;
}
```
接下来是Mapper接口UserMapper.java:
```java
@Mapper
public interface UserMapper extends BaseMapper<User> {
User selectByUsername(String username);
}
```
Mapper接口ParkingLotMapper.java:
```java
@Mapper
public interface ParkingLotMapper extends BaseMapper<ParkingLot> {
}
```
接下来是Controller类UserController.java:
```java
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody User user) {
User dbUser = userMapper.selectByUsername(user.getUsername());
if (dbUser == null || !dbUser.getPassword().equals(user.getPassword())) {
throw new UnauthorizedException("用户名或密码错误");
}
String token = JwtUtils.generateToken(dbUser.getId(), dbUser.getUsername());
Map<String, Object> map = new HashMap<>();
map.put("token", token);
return ResponseEntity.ok(map);
}
@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody User user) {
User dbUser = userMapper.selectByUsername(user.getUsername());
if (dbUser != null) {
throw new BadRequestException("用户名已存在");
}
userMapper.insert(user);
return ResponseEntity.ok("注册成功");
}
}
```
Controller类ParkingLotController.java:
```java
@RestController
@RequestMapping("/api/parkinglot")
public class ParkingLotController {
@Autowired
private ParkingLotMapper parkingLotMapper;
@GetMapping("")
public ResponseEntity<?> getAll() {
List<ParkingLot> parkingLots = parkingLotMapper.selectList(null);
return ResponseEntity.ok(parkingLots);
}
@PostMapping("")
public ResponseEntity<?> add(@RequestBody ParkingLot parkingLot) {
parkingLotMapper.insert(parkingLot);
return ResponseEntity.ok("添加成功");
}
@PostMapping("/{id}")
public ResponseEntity<?> update(@PathVariable Long id, @RequestBody ParkingLot parkingLot) {
ParkingLot dbParkingLot = parkingLotMapper.selectById(id);
if (dbParkingLot == null) {
throw new NotFoundException("车位不存在");
}
parkingLot.setId(id);
parkingLotMapper.updateById(parkingLot);
return ResponseEntity.ok("修改成功");
}
@DeleteMapping("/{id}")
public ResponseEntity<?> delete(@PathVariable Long id) {
parkingLotMapper.deleteById(id);
return ResponseEntity.ok("删除成功");
}
}
```
接下来是JwtUtils.java工具类:
```java
public class JwtUtils {
private static final String SECRET_KEY = "YourSecretKey";
private static final long EXPIRE_TIME = 3600000;
public static String generateToken(Long id, String username) {
Date now = new Date();
Date expireTime = new Date(now.getTime() + EXPIRE_TIME);
return Jwts.builder()
.setId(id.toString())
.setSubject(username)
.setIssuedAt(now)
.setExpiration(expireTime)
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
}
public static Claims parseToken(String token) {
try {
return Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody();
} catch (JwtException e) {
throw new UnauthorizedException("无效的token");
}
}
}
```
接下来是TokenInterceptor.java拦截器:
```java
public class TokenInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String authorization = request.getHeader("Authorization");
if (authorization == null || !authorization.startsWith("Bearer ")) {
throw new UnauthorizedException("未授权访问");
}
String token = authorization.substring(7);
JwtUtils.parseToken(token);
return true;
}
}
```
最后是异常处理类GlobalExceptionHandler.java:
```java
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BadRequestException.class)
public ResponseEntity<?> handleBadRequestException(BadRequestException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<?> handleNotFoundException(NotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
}
@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<?> handleUnauthorizedException(UnauthorizedException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
}
}
```
至此,完整的后端代码就完成了。
阅读全文