A. Generate Login(string)

本文介绍了一种用于生成用户登录名的算法,该算法通过组合用户的名和姓的前缀来创建唯一的登录名,并确保生成的登录名按字母顺序排列在最前面。文章提供了具体的实现代码,展示了如何从用户的名字中选取合适的前缀来形成登录名。

A. Generate Login(string)

time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
The preferred way to generate user login in Polygon is to concatenate a prefix of the user’s first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.

You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).

As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: “a”, “ab”, “abc” etc. are prefixes of string “{abcdef}” but “b” and ‘bc” are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: “a” and “ab” are alphabetically earlier than “ac” but “b” and “ba” are alphabetically later than “ac”.

Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.

Output
Output a single string — alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.

Examples
input
harry potter
output
hap
input
tom riddle
output
tomr

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#define INF 0x3f3f3f3f
using namespace std;
vector<string>ans;
int main()
{
    string a, b;
    cin>>a>>b;
    ans.clear();//清空
    int numa = a.length();//获取长度
    int numb = b.length();
    for(int i=1; i<=numa; i++)
    {
        for(int j=1; j<=numb; j++)
        {
            string temp = a.substr(0, i)+b.substr(0, j);//连接
            ans.push_back(temp);
        }
    }
    sort(ans.begin(), ans.end());//排序
    cout<<ans[0]<<endl;
    return 0;
}
public class JwtV0126Example { // 使用新版API生成密钥 private static final String SECRET_STR = "dZUPnA6iucvhpf8bVkdQkQhsN30XOHDDU3G5YFT5ulqeQnAefayH3HK9Jeedj6E0bBi4nrnm4EIXZXZdOcjWAg=="; // 256位(32字符) private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(SECRET_STR.getBytes(StandardCharsets.UTF_8)); // 验证Token public static boolean validateToken(String token) { try { Jws<Claims> jws = Jwts.parser() .verifyWith(SECRET_KEY) // 新版验证方法 .build() .parseSignedClaims(token); // 新版解析方法 Claims claims = jws.getPayload(); Date expiration = claims.getExpiration(); Date now = new Date(); // 检查token是否过期 if (expiration.before(now)) { throw new BaseException(ErrorMsg.LOGIN_EXPIRE.getCode(),ErrorMsg.LOGIN_EXPIRE.getMsg()); } // 可以添加其他自定义验证逻辑,如检查用户状态等 return true; } catch (JwtException e) { // token无效,如签名不匹配、格式错误等 throw new BaseException(ErrorMsg.NOT_JWT_LOGIN_INFO.getCode(),ErrorMsg.NOT_JWT_LOGIN_INFO.getMsg()); } } /** * 生成JWT令牌(使用0.12.6 API) */ public static String generateJwt(String username, String userInfo) { Map<String, Object> claims = new HashMap<>(); claims.put("userInfo", userInfo); // 使用新版API设置有效期 Instant now = Instant.now(); return Jwts.builder() .claims(claims) // 设置声明(新版API) .subject(username) .issuedAt(Date.from(now)) .expiration(Date.from(now.plus(1, ChronoUnit.HOURS))) // 1小时有效期 .signWith(SECRET_KEY, Jwts.SIG.HS256) // 新版签名方法 .compact(); } /** * 验证并解析JWT(使用0.12.6 API) */ public static void verifyAndParseJwt(String jwt) { try { Jws<Claims> claimsJws = Jwts.parser() .verifyWith(SECRET_KEY) // 新版验证方法 .build() .parseSignedClaims(jwt); // 新版解析方法 Claims claims = claimsJws.getPayload(); System.out.println("用户: " + claims.getSubject()); System.out.println("用户信息: " + claims.get("userInfo")); System.out.println("签发时间: " + claims.getIssuedAt()); System.out.println("过期时间: " + claims.getExpiration()); } catch (Exception e) { throw new BaseException(ErrorMsg.NOT_JWT_LOGIN_INFO.getCode(),ErrorMsg.NOT_JWT_LOGIN_INFO.getMsg()); } } //生成密钥字符串 public static String generateKey() { try { // 创建HMAC-SHA512密钥生成器 KeyGenerator keyGen = KeyGenerator.getInstance("HmacSHA512"); // 设置密钥长度为512位 keyGen.init(512); // 生成密钥 SecretKey secretKey = keyGen.generateKey(); // 获取Base64编码的密钥字符串 String base64Key = Base64.getEncoder().encodeToString(secretKey.getEncoded()); System.out.println("JWT密钥: " + base64Key); return base64Key; } catch (NoSuchAlgorithmException e) { throw new BaseException(ErrorMsg.GENERATE_JWT_KEY_FAIL.getMsg()); } } public static void main(String[] args) { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", "1"); jsonObject.put("userName", "nmm"); jsonObject.put("role", "admin"); jsonObject.put("dept", "dept01"); // 1. 生成JWT String jwt = generateJwt(jsonObject.getString("id"), jsonObject.toJSONString()); // 2. 验证并解析JWT verifyAndParseJwt(jwt); if (validateToken(jwt)) { System.out.println("success"); } } } 帮我做一个延期
最新发布
08-07
java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clueController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clueServiceImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clueAttachmentServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clueAttachmentMapper' defined in file [D:\H3C\system-common\target\classes\com\h3c\cprdm\clue\mapper\ClueAttachmentMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'dataSource': Could not bind properties to 'DataSource' : prefix=spring.datasource.druid, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid.password' to java.lang.String Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clueServiceImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clueAttachmentServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clueAttachmentMapper' defined in file [D:\H3C\system-common\target\classes\com\h3c\cprdm\clue\mapper\ClueAttachmentMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'dataSource': Could not bind properties to 'DataSource' : prefix=spring.datasource.druid, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid.password' to java.lang.String Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clueAttachmentServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clueAttachmentMapper' defined in file [D:\H3C\system-common\target\classes\com\h3c\cprdm\clue\mapper\ClueAttachmentMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'dataSource': Could not bind properties to 'DataSource' : prefix=spring.datasource.druid, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid.password' to java.lang.String Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clueAttachmentMapper' defined in file [D:\H3C\system-common\target\classes\com\h3c\cprdm\clue\mapper\ClueAttachmentMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'dataSource': Could not bind properties to 'DataSource' : prefix=spring.datasource.druid, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid.password' to java.lang.String Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'dataSource': Could not bind properties to 'DataSource' : prefix=spring.datasource.druid, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid.password' to java.lang.String Caused by: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'dataSource': Could not bind properties to 'DataSource' : prefix=spring.datasource.druid, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid.password' to java.lang.String Caused by: org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid.password' to java.lang.String Caused by: java.lang.IllegalStateException: either 'jasypt.encryptor.password', one of ['jasypt.encryptor.private-key-string', 'jasypt.encryptor.private-key-location'] for asymmetric encryption, or one of ['jasypt.encryptor.gcm-secret-key-string', 'jasypt.encryptor.gcm-secret-key-location', 'jasypt.encryptor.gcm-secret-key-password'] for AES/GCM encryption must be provided for Password-based or Asymmetric encryption [ERROR] contextLoads Time elapsed: 0 s <<< ERROR! java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clueController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clueServiceImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clueAttachmentServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clueAttachmentMapper' defined in file [D:\H3C\system-common\target\classes\com\h3c\cprdm\clue\mapper\ClueAttachmentMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'dataSource': Could not bind properties to 'DataSource' : prefix=spring.datasource.druid, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid.password' to java.lang.String Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clueServiceImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clueAttachmentServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clueAttachmentMapper' defined in file [D:\H3C\system-common\target\classes\com\h3c\cprdm\clue\mapper\ClueAttachmentMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'dataSource': Could not bind properties to 'DataSource' : prefix=spring.datasource.druid, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid.password' to java.lang.String Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clueAttachmentServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clueAttachmentMapper' defined in file [D:\H3C\system-common\target\classes\com\h3c\cprdm\clue\mapper\ClueAttachmentMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'dataSource': Could not bind properties to 'DataSource' : prefix=spring.datasource.druid, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid.password' to java.lang.String Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clueAttachmentMapper' defined in file [D:\H3C\system-common\target\classes\com\h3c\cprdm\clue\mapper\ClueAttachmentMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'dataSource': Could not bind properties to 'DataSource' : prefix=spring.datasource.druid, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid.password' to java.lang.String Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'dataSource': Could not bind properties to 'DataSource' : prefix=spring.datasource.druid, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid.password' to java.lang.String Caused by: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'dataSource': Could not bind properties to 'DataSource' : prefix=spring.datasource.druid, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid.password' to java.lang.String Caused by: org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.druid.password' to java.lang.String Caused by: java.lang.IllegalStateException: either 'jasypt.encryptor.password', one of ['jasypt.encryptor.private-key-string', 'jasypt.encryptor.private-key-location'] for asymmetric encryption, or one of ['jasypt.encryptor.gcm-secret-key-string', 'jasypt.encryptor.gcm-secret-key-location', 'jasypt.encryptor.gcm-secret-key-password'] for AES/GCM encryption must be provided for Password-based or Asymmetric encryption [INFO] [INFO] Results: [INFO] [ERROR] Errors: [ERROR] CprdmApplicationTests.codeGenerate » IllegalState Failed to load ApplicationCo... [ERROR] CprdmApplicationTests.contextLoads » IllegalState Failed to load ApplicationCo... [INFO] [ERROR] Tests run: 2, Failures: 0, Errors: 2, Skipped: 0 [INFO]
06-19
### 微信小程序登录 `wx.login` 的服务器端实现 #### 1. 登录流程概述 在微信小程序开发中,`wx.login()` 是用于获取临时登录凭证(code),该操作必须由客户端发起。此 code 只能通过前端 API 获取,并且有效期较短。因此,无法直接在服务器端执行 `wx.login()`。 为了完成整个登录过程,通常采用以下模式: - 客户端调用 `wx.login()` 获得 code; - 将获得的 code 发送到自建的服务端; - 服务端利用这个 code 结合自身的 AppID 和 AppSecret 请求微信接口换取用户的 OpenID 和 SessionKey[^1]。 #### 2. 前端代码示例 以下是使用 UniApp 框架下的 Vue 组件中的方法来捕获并传递 login code 到后端的例子: ```javascript methods: { onWxLogin() { uni.login({ provider: 'weixin', success(res) { console.log('login res:', res); const { code } = res; // Send the received code to backend server via HTTP request. uni.request({ url: `${process.env.VUE_APP_BASE_API}/api/auth/login`, method: "POST", data: { code }, success(response) { let token = response.data.token; // Store or use the returned token as needed... } }); } }) } } ``` #### 3. 后端处理逻辑 (Java Spring Boot Example) 当接收到从前端传来的 code 参数之后,可以通过向微信提供的 OAuth 接口发送 POST 请求来进行验证和交换用户信息。下面是一个基于 Java Spring Boot 的简单例子展示如何接收来自前端的应用程序编程接口(API)请求以及后续的操作: ```java @RestController @RequestMapping("/api/auth") public class AuthController { @PostMapping("/login") public ResponseEntity<Map<String, Object>> handleWeChatLogin(@RequestBody Map<String, String> body){ try{ final String CODE_URL = "https://api.weixin.qq.com/sns/jscode2session"; RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); HttpEntity entity = new HttpEntity(headers); MultiValueMap<String, String> params= new LinkedMultiValueMap<>(); params.add("appid", APP_ID); params.add("secret", SECRET_KEY); params.add("js_code", body.get("code")); params.add("grant_type", "authorization_code"); ResponseEntity<String> response = restTemplate.exchange( CODE_URL, HttpMethod.GET, entity, String.class, params ); JSONObject jsonResponse = new JSONObject(response.getBody()); String openId = jsonResponse.getString("openid"); String sessionKey = jsonResponse.getString("session_key"); // Generate a custom JWT Token here based on openid and other info... HashMap<String,Object> resultMap=new HashMap<>( ); resultMap.put("token","generated-jwt-token"); return new ResponseEntity<>(resultMap, HttpStatus.OK); }catch(Exception e){ logger.error(e.getMessage(),e); throw new RuntimeException("Failed to authenticate user."); } } } ``` 上述代码片段展示了如何构建一个 RESTful Web Service 来接受从小程序前端传来的一次性验证码(code),并通过调用微信开放平台提供的接口(auth.code2Session)[^4]去获取用户的唯一标识符(openid)和其他必要的认证信息(session key)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值