我不能确切地了解return工程try,catch.
try和finally没有catch,我可以把return里面try块.try,catch,finally,我不能忍受return的try块.catch块,我必须把return在外面try,catch,finally块.catch块throw Exception,我可以把return里面try块.它们如何正常工作?为什么我不能把它return放在try一块?
代码try,catch,finally
public int insertUser(UserBean user) {
int status = 0;
Connection myConn = null;
PreparedStatement myStmt = null;
try { …Run Code Online (Sandbox Code Playgroud) 我知道一个接口不能有构造函数,我们不能创建接口对象.
这是不可能的:
Comparator cmp = new Comparator();
Run Code Online (Sandbox Code Playgroud)
我不明白如何使用关键字"new Comparator()"创建一个匿名内部类.此关键字是否不会创建Comparator类型的对象?
这是完整的代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class DemoApp {
public static void main(String args[]) {
List<String> animals = new ArrayList<>();
animals.add("elephant");
animals.add("snake");
animals.add("lion");
animals.add("mangoose");
animals.add("cat");
animals.add("tiger");
Collections.sort(animals, new Comparator<String>() {
public int compare(String s1, String s2) {
return -s1.compareTo(s2);
}
});
displayList(animals);
}
public static void displayList(List<String> anim) {
for (String animal : anim) {
System.out.print(animal + " ");
}
System.out.println();
}
}
Run Code Online (Sandbox Code Playgroud) 我正在学习Swagger以及如何使用Swagger代码生成REST客户端。我知道如何使用Swagger进行文档编制,也知道如何使用Swagger生成简单的REST Server,但是我不知道如何使用Swagger代码生成简单的REST Client。
例如,我有一个简单的应用程序,它是一个REST Server,并且我想生成REST Client。我可以使用Swagger代码生成代码吗?
REST服务器的控制器:
package com.dgs.spring.springbootswagger.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@RestController
@RequestMapping("/api/v1")
@Api(value = "Employee Management System", description = "Operations pertaining to employee in Employee Management System")
public class EmployeeController {
@Autowired
private EmployeeRepository employeeRepository;
@ApiOperation(value = "View a list of available employees", response = List.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved list"),
@ApiResponse(code = 401, message = "You are not authorized to view the resource"),
@ApiResponse(code …Run Code Online (Sandbox Code Playgroud) 我尝试在 Spring Boot 中将 Query DSL 与 MongoDB 结合使用,但出现错误。该应用程序无需使用 MongoDB 的 Query DSL 库即可成功运行。我想使用这个库,因为我想使用更复杂的查询。代码应该可以工作,我认为某处有一个小错误。
问题是当我单击 Maven 包时,我收到这些错误,不幸的是我无法在此处发布所有输出:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'hotelController' defined in file [C:\Users\dgs\IdeaProjects\springboot-mongodb\target\classes\com\dgs\springbootmongodb\controller\HotelController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hotelRepository': Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.repository.support.QuerydslMongoPredicateExecutor]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Did not find a query class com.dgs.springbootmongodb.models.QHotel for domain class com.dgs.springbootmongodb.models.Hotel!
Caused by: org.springframework.beans.factory.BeanCreationException: Error …Run Code Online (Sandbox Code Playgroud) 我正在学习 Java 和 Spring 的基本身份验证和 Jwt 身份验证,我想问您基本身份验证是否是基于会话的身份验证?
我知道在基于会话的身份验证中,当客户端登录时,sessionId 存储在客户端浏览器上的 cookie 中,之后当客户端发出另一个请求时,服务器将 sessionId 与存储在服务器内存中的数据进行比较。另外我想问一下sessionId是如何从客户端浏览器发送到服务器的?它是像令牌一样在标头中发送还是如何发送?
最后一个问题是服务器如何验证 Jwt 令牌?我知道在会话身份验证的情况下,将从客户端发送的 sessionId 与服务器内存中的数据进行比较。但是如果使用 Jwt 身份验证会发生什么?令牌与标头一起发送,我知道服务器验证了它并且服务器内存中没有数据。那么服务器如何比较token呢?任何反馈将不胜感激!谢谢你!
我正在 Spring Boot 应用程序中学习 Spring Security,我有一个非常简单的例子。我看到,如果我发表评论,configure(AuthenticationManagerBuilder auth)则没有区别。无论我是否使用它,我都有相同的输出,我需要使用硬编码凭据登录。
@Configuration
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// private final MyUserDetailsService myUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic();
}
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.userDetailsService(myUserDetailsService);
// }
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Run Code Online (Sandbox Code Playgroud)
MyUserDetailsService 类:
@Service
public class MyUserDetailsService implements UserDetailsService {
private static final String USERNAME = "john";
private static final String …Run Code Online (Sandbox Code Playgroud) 我有一个简单的java项目,我尝试将Intellij中的java版本从java 11更改为java 8。它不是一个maven项目。我在谷歌上找到了一些东西,看起来很简单,但它不起作用。
所以,我按了ctrl + shift + alt + s,在这里我将jdk11更改为jdk1.8:
但现在如果我在 Intellij 终端上运行 java -version ,我会在控制台中看到以下内容:
java version "11.0.14" 2022-01-18 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.14+8-LTS-263)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.14+8-LTS-263, mixed mode)
Run Code Online (Sandbox Code Playgroud)
看起来它继续使用java 11。我还应该做什么?谢谢你!
你好,我使用 RESTful 进行基本身份验证,此代码是 RestController 的一部分:
@GetMapping("/jpa/users/{username}/goals")
public List<Goal> getAllGoals(@PathVariable String username) {
userId = getUserIdFromUsername(username);
return goalJpaRepository.findByUserId(userId);
}
public Long getUserIdFromUsername(String username) {
User user = userJpaRepository.findByUsername(username);
userId = user.getId();
return userId;
}
Run Code Online (Sandbox Code Playgroud)
我有一个问题,例如我正在使用 Postman 来检索特定用户的目标,如下所示:
http://localhost:8080/jpa/users/john/goals 带有 GET 请求
然后我对用户名 john 和该用户名的密码使用基本身份验证,然后我收到了 john 的目标。
之后,如果我对此链接http://localhost:8080/jpa/users/tom/goals执行 GET 请求,我会收到 Tom 的目标,但此时我已使用 john 登录,因此 john 可以看到他的目标,他也可以看到汤姆的目标。
问题是我如何访问 RestController 中的登录用户名,因为我想做这样的事情:
if (loginUsername == username) {
return goalJpaRepository.findByUserId(userId);
}
return "Access denied!";
Run Code Online (Sandbox Code Playgroud)
所以我想知道是否可以从HTTP Header访问登录用户名?
谢谢你!
更新- 是的,框架是 Spring Boot,我也使用 Spring Security …
java rest restful-authentication basic-authentication spring-rest
我刚刚在笔记本电脑上下载了 Intellij 并导入了一个 Maven 项目,问题是 Intellij 在 pom.xml 中没有找到任何依赖项。例如,如果我尝试导入 hibernate-core 或任何其他依赖项,则会出现错误:Dependency org.hibernate-core... not found。我该怎么办?任何反馈将不胜感激。
我正在学习如何使用基本身份验证和 OAuth2 JWT 令牌身份验证来保护微服务。我使用基本身份验证实现了它,现在我想将其转换为 OAuth2 身份验证。
这是使用基本身份验证来保护这两个微服务之间的通信的实现。
微服务1-REST API
@Configuration
@Getter
public class DemoApiConfiguration {
@Value("${demo.api.credentials.username}")
private String username;
@Value("${demo.api.credentials.password}")
private String password;
}
Run Code Online (Sandbox Code Playgroud)
安全配置器类:
@Configuration
@RequiredArgsConstructor
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
private final DemoApiConfiguration apiConfig;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic();
}
@Bean
public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
UserDetails theUser = User.withUsername(apiConfig.getUsername())
.password(passwordEncoder.encode(apiConfig.getPassword())).roles("USER").build();
InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
userDetailsManager.createUser(theUser);
return userDetailsManager;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
} …Run Code Online (Sandbox Code Playgroud) java ×9
spring-boot ×4
jwt ×2
spring ×2
bearer-token ×1
collections ×1
constructor ×1
hibernate ×1
interface ×1
java-8 ×1
maven ×1
mongodb ×1
oauth-2.0 ×1
pom.xml ×1
querydsl ×1
rest ×1
rest-client ×1
return ×1
spring-rest ×1
swagger ×1
try-catch ×1