我的 Spring Boot 版本是 1.5.4,这是我的配置代码
@SpringBootApplication
@Configuration
@RestController
@ServletComponentScan
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
@RequestMapping("/")
public String home() {
System.out.println("test");
return "Hello World!";
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 servlet 过滤器代码
@WebFilter(urlPatterns = "/*")
public class LogFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("LogFilter");
chain.doFilter(request, response);
}
//init and destroy
Run Code Online (Sandbox Code Playgroud)
当我访问http://localhost:8080/ 时,控制台打印出来了
LogFilter
test
LogFilter <----the second time
Run Code Online (Sandbox Code Playgroud)
为什么要调用 filter 两次?Spring …
在我们的 Spring Boot 应用程序中,我们在 Quality 环境中进行了第一次部署,现在我们希望简化定义 URL 以接受来自 FrontEnd 应用程序的请求。
我们用 maven 构建我们的应用程序,然后我们用命令执行它
java -Dspring.profiles.active=prod -jar myapp-0.0.1-SNAPSHOT.jar
Run Code Online (Sandbox Code Playgroud)
我们认为我们可以在application.properties/application-prod.properties文件上设置 URL ,但这不起作用,因为在执行时它为空。另一种解决方法是-Dspring.profiles.active=prod在运行应用程序时以某种方式获取我们传递的参数,然后获取一个或另一个 URL 但这似乎有点脏......
那你们会怎么做呢?在谷歌上找不到任何东西给我留下了深刻的印象,显然人们有不同的解决方法,或者我以错误的方式搜索。
编辑 跨源信息:这就是我们最初实现它的方式。
@CrossOrigin(origins = BasicConfiguration.CLIENT_URL)
Run Code Online (Sandbox Code Playgroud)
这就是我们现在想要使用 Spring Security 的过滤器来做到这一点的方式
public class CorsFilter implements Filter, ApplicationContextAware {
@Value("${urlServer}")
private String urlServer;
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", urlServer);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, …Run Code Online (Sandbox Code Playgroud) 我正在使用 SpringBoot、Spring 数据和 postgresql。
在 postgres 中,我创建了一张表。
CREATE EXTENSION "uuid-ossp";
CREATE TABLE user (
id serial PRIMARY KEY not null,
user_id varchar(255) not null default uuid_generate_v4()
);
Run Code Online (Sandbox Code Playgroud)
比创建实体
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 9129894781337596497L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(columnDefinition = "serial")
private Integer id;
@Column(insertable = false)
private String userId;
public static User create(){
User user = new User();
return user;
}
public String getUserId(){
return userId;
}
}
Run Code Online (Sandbox Code Playgroud)
比这样创建 jpa 存储库 …
我正在开发一个 Spring Boot 应用程序并为用户编写一个 API 以便能够阅读消息。URL之一是:
/users/USER1/messages
Run Code Online (Sandbox Code Playgroud)
现在,我显然希望只有经过身份验证的用户才能访问此 get 请求的内容。但是所有经过身份验证的用户是不够的。我还希望只有拥有用户名的用户 - USER1 才能在这里查看真实内容,其余的应该收到 403 状态。我想出了如何在没有 spring 安全配置的情况下执行此操作(在我的服务中,我正在检查登录的用户名并将其与 URL 中的参数进行比较,仅当它们相等时才继续),但我认为应该有一种更简单的方法只使用 SecurityConfiguration?我当前的配置如下所示:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/users/**").authenticated()
.antMatchers("/h2-console/*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin();
http.csrf().disable();
http.headers().frameOptions().disable();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("superman").password("superman").roles("USER")
.and()
.withUser("admin").password("admin").roles("ADMIN");
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:以下回答建议方法安全表达式我已经使用了它,但它似乎仍然不起作用(如果我被认证为 USER2,我仍然可以读取 USER1 的消息)。这是我添加了 PreAuthorize 注释的控制器
@RequestMapping(method = RequestMethod.GET, value = "/messages", produces = {"application/json"})
@ResponseBody
@PreAuthorize("#userHandle == authentication.name")
public …Run Code Online (Sandbox Code Playgroud) 我有一个休息方法:
@RequestMapping(value = "wash/washHistory", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
@ResponseBody
public DeferredResult<String> getWashHistory(@RequestParam(value = "sid", required = true, defaultValue = "") String sid,
HttpServletResponse response, HttpServletRequest request,
@RequestParam(value = "sort", defaultValue = "") String sortType,
@RequestParam(value = "order", defaultValue = "") String order,
@RequestParam(value = "limit", defaultValue = "") String limit,
@RequestParam(value = "offset", defaultValue = "") String offset) {
System.out.println("Thread: "+Thread.currentThread());
final Integer managerId = checkSession(sid);
DeferredResult<String> defResult = new DeferredResult<>();
new Thread(() -> {
final String result …Run Code Online (Sandbox Code Playgroud) I have a spring boot application standing on Postgres database.
Now I want to use h2 database for Unit testing alone.
这样做对吗?或者有什么建议
我的对象:
@Entity
@Table(name="user")
public class User {
@Id
@Column(name="uid")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
//more code
}
Run Code Online (Sandbox Code Playgroud)
当我POST user JSON没有时uid,我收到错误,因为给定的 id 不能为 null。这不应该是这种情况,而uid应该由数据库生成。请指出我遗漏了什么。
JSON:
{
"email": "john@mail.com",
"name": "John Doe",
"phone": "98-765-4445"
}
Run Code Online (Sandbox Code Playgroud)
错误:
{
"timestamp": 1501058952038,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.dao.InvalidDataAccessApiUsageException",
"message": "The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!",
"path": "/api/user/"
}
Run Code Online (Sandbox Code Playgroud) 要查看发送到数据库的 SQL 查询,我们通常使用showSql参数:
spring.jpa.showSql=true
Run Code Online (Sandbox Code Playgroud)
它允许我们看到语句体而不是它的参数:
insert into master (id, version, name) values (null, ?, ?)
Run Code Online (Sandbox Code Playgroud)
尤其是我们没有看到查询的结果。
有没有办法在应用程序日志中查看 SQL 语句、其参数和结果?
在 Spring Boot (Websockets) 中
我刚看到这个例子:
messaging.convertAndSendToUser( username, "/queue/notifications",
new Notification("You just got mentioned!"));
Run Code Online (Sandbox Code Playgroud)
这家伙从哪里得到用户名?我找不到任何关于从哪里获得该用户名的提及......
I have used the below settings in my Application properties file. But still cant see my tables in h2 console.
application.properties
logging.level.org.springframework.web=INFO
spring.datasource.url=jdbc:h2:mem:challenge;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MV_STORE=FALSE
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.schema=classpath:/schema.sql
spring.datasource.data=classpath:/data.sql
spring.h2.console.enabled=true
spring.h2.console.path=/h2
server.port = 8080
Run Code Online (Sandbox Code Playgroud)
I used the string jdbc:h2:mem:challenge;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MV_STORE=FALSE in the JDBC URL on H2 console to login. Yet i am not seeing any tables
The below is my Graddle file
buildscript {
ext {
springBootVersion = '1.4.4.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: …Run Code Online (Sandbox Code Playgroud) spring-boot ×10
java ×6
spring ×5
h2 ×2
jpa ×2
postgresql ×2
cors ×1
hibernate ×1
jakarta-ee ×1
logging ×1
nonblocking ×1
rest ×1
spring-mvc ×1
spring-rest ×1
sql ×1
unit-testing ×1
websocket ×1