spring boot 时间对象加一天
时间: 2024-06-19 12:00:49 浏览: 8
在Spring Boot中,如果你想要获取当前日期并增加一天,你可以使用Java 8中的`java.time`包提供的类,比如`LocalDate`或`ZonedDateTime`。以下是一个简单的示例:
```java
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
// 获取当前日期并增加一天
LocalDate tomorrow = LocalDate.now().plusDays(1);
ZonedDateTime tomorrowZonedDateTime = ZonedDateTime.now().plusDays(1);
// 打印结果
System.out.println("Tomorrow's LocalDate: " + tomorrow);
System.out.println("Tomorrow's ZonedDateTime: " + tomorrowZonedDateTime);
```
在这个例子中,`plusDays(1)`方法会增加一天,`now()`方法获取当前日期时间。
如果你想在Spring MVC的控制器或服务类中使用,你可以注入`LocalDateTime`或`ZonedDateTime` bean,并进行类似的操作。如果是在模板引擎(如Thymeleaf)中,可以使用表达式语言(EL)来显示这些值。
相关问题
spring boot Date 减两天
要使用 Spring Boot 对日期进行操作,可以使用 Java 提供的 Date 和 Calendar 类。Date 类提供了一些方法来进行日期计算,其中一个方法是 setTime(),可以用来设置日期的毫秒数。你可以先将需要操作的日期转换为毫秒数,然后将两天的毫秒数相加或相减,得到新的日期的毫秒数,最后再将其转换为 Date 对象。
下面是一个示例代码,展示了如何使用 Java 的 Date 类和 Calendar 类来减去两天:
```
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static void main(String[] args) {
// 获取当前日期
Date date = new Date();
// 将日期转换为日历对象
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// 将日历对象减去两天
calendar.add(Calendar.DAY_OF_MONTH, -2);
// 获取新的日期
Date newDate = calendar.getTime();
}
}
```
spring boot实现微信小程序登录完整代码
以下是一个基于 Spring Boot 和 Spring Security 的微信小程序登录示例代码:
1. 自定义 WeChatAuthenticationToken 类
```java
public class WeChatAuthenticationToken extends AbstractAuthenticationToken {
private final Object principal;
private Object credentials;
public WeChatAuthenticationToken(Object principal, Object credentials) {
super(null);
this.principal = principal;
this.credentials = credentials;
setAuthenticated(false);
}
public WeChatAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
this.credentials = credentials;
super.setAuthenticated(true); // must use super, as we override
}
@Override
public Object getCredentials() {
return this.credentials;
}
@Override
public Object getPrincipal() {
return this.principal;
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
this.credentials = null;
}
}
```
2. 自定义 WeChatAuthenticationProvider 类
```java
@Service
public class WeChatAuthenticationProvider implements AuthenticationProvider {
private final String WECHAT_APPID = "your wechat appid"; // 微信小程序的 appid
private final String WECHAT_SECRET = "your wechat appsecret"; // 微信小程序的 appsecret
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String code = authentication.getCredentials().toString();
// 调用微信接口,获取 openid 和 session_key
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WECHAT_APPID
+ "&secret=" + WECHAT_SECRET
+ "&js_code=" + code
+ "&grant_type=authorization_code";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
String responseBody = responseEntity.getBody();
ObjectMapper objectMapper = new ObjectMapper();
try {
JsonNode jsonNode = objectMapper.readTree(responseBody);
String openid = jsonNode.get("openid").asText();
String sessionKey = jsonNode.get("session_key").asText();
// 将 openid 和 session_key 封装成一个 WeChatAuthenticationToken 对象,返回认证结果
WeChatAuthenticationToken authenticationToken = new WeChatAuthenticationToken(openid, sessionKey);
return authenticationToken;
} catch (IOException e) {
throw new AuthenticationServiceException("Failed to get openid and session_key from wechat api", e);
}
}
@Override
public boolean supports(Class<?> authentication) {
return WeChatAuthenticationToken.class.isAssignableFrom(authentication);
}
}
```
3. 自定义 WeChatAuthenticationFilter 类
```java
public class WeChatAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private final String LOGIN_URL = "/login/wechat";
public WeChatAuthenticationFilter() {
super(new AntPathRequestMatcher("/login/wechat", "POST"));
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
String code = IOUtils.toString(request.getInputStream(), Charset.forName("UTF-8"));
// 将 code 封装成一个 WeChatAuthenticationToken 对象,交给 AuthenticationManager 进行认证
WeChatAuthenticationToken authenticationToken = new WeChatAuthenticationToken(code, code);
return getAuthenticationManager().authenticate(authenticationToken);
}
}
```
4. 自定义 WeChatAuthenticationSuccessHandler 类
```java
public class WeChatAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
private final long EXPIRATION_TIME = 1000 * 60 * 60 * 24; // 登录态过期时间为 1 天
private final String SECRET_KEY = "your secret key"; // JWT 加密所需的秘钥
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
String openid = authentication.getName();
String sessionKey = authentication.getCredentials().toString();
// 生成 JWT
String jwt = Jwts.builder()
.setSubject(openid)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
// 将 JWT 返回给前端
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"jwt\":\"" + jwt + "\"}");
}
}
```
5. Spring Security 配置
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private WeChatAuthenticationProvider weChatAuthenticationProvider;
@Autowired
private WeChatAuthenticationSuccessHandler weChatAuthenticationSuccessHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.addFilterBefore(weChatAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/login/wechat").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint());
}
@Bean
public WeChatAuthenticationFilter weChatAuthenticationFilter() throws Exception {
WeChatAuthenticationFilter filter = new WeChatAuthenticationFilter();
filter.setAuthenticationManager(authenticationManager());
filter.setAuthenticationSuccessHandler(weChatAuthenticationSuccessHandler);
return filter;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(weChatAuthenticationProvider);
}
}
```
注意,在使用 JWT 进行加密时,需要保证 SECRET_KEY 的安全性。建议将 SECRET_KEY 存储在安全的地方,并且不要将其泄露给他人。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)