小编A_B*_*A_B的帖子

针对未经身份验证的用户的 Spring Security 404 页面

我正在使用 Spring Boot 和 Thymeleaf。我有一个自定义 404 模板页面定义在src/main/resources/templates/error/404.html

当用户登录时这可以正常工作。

然而,当他们注销时,他们不会得到任何类型的 404 页面,他们只是被重定向回/login.

我认为我的安全配置需要更改,但不确定是什么。

@Override
protected void configure(HttpSecurity http) throws Exception {

  http.authorizeRequests()
      .antMatchers("/","/register*","/resetPassword","/forgotPassword","/login","/404").permitAll()
      .antMatchers("/admin/**").hasAuthority("ADMIN").anyRequest()
      .authenticated().and().formLogin().loginPage("/login").failureUrl("/login?error")
      .defaultSuccessUrl("/dashboard").successHandler(successHandler)
      .usernameParameter("email").passwordParameter("password")
      .and().logout()
      .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login?logout").and()
      .exceptionHandling().accessDeniedPage("/access-denied");
}

@Override
public void configure(WebSecurity web) throws Exception {
  web.ignoring().antMatchers("/error**","/resources/**", "/static/**", "/css/**", "/js/**", "/img/**");
}
Run Code Online (Sandbox Code Playgroud)

java spring spring-boot

8
推荐指数
1
解决办法
8027
查看次数

Spring Boot修改默认JSON响应

我有一个REST控制器,它返回一个像这样的产品列表:

电流输出

[  
   {  
      "id":1,
      "name":"Money market"
   },
   {  
      "id":2,
      "name":"Certificate of Deposit"
   },
   {  
      "id":3,
      "name":"Personal Savings"
   }
]
Run Code Online (Sandbox Code Playgroud)

为了让我们的JS网格库工作,我需要修改响应,如下所示:

期望的输出

{ "data" :
   [  
       {  
          "id":1,
          "name":"Money market"
       },
       {  
          "id":2,
          "name":"Certificate of Deposit"
       },
       {  
          "id":3,
          "name":"Personal Savings"
       }
    ]
}
Run Code Online (Sandbox Code Playgroud)

调节器

@RequestMapping(value = "/api/products", method = RequestMethod.GET)
public ResponseEntity<?> getAllProducts() {

  List<Product> result = productService.findAll();
  return ResponseEntity.ok(result);
}
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法来使用本机Spring库修改JSON响应?

java spring json spring-boot

5
推荐指数
2
解决办法
2646
查看次数

将用户对象存储在与Spring Security的会话中

根据我的理解,有许多不同的方法可以在Spring Security中检索经过身份验证的用户名.

我目前通过包含Principal作为控制器方法参数来获取用户名:

@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView displayHomePage(ModelAndView modelAndView, Principal principal) {

  modelAndView.addObject("email", principal.getName());

  // Render template located at src/main/resources/templates/dashboard.html
  modelAndView.setViewName("dashboard");

  return modelAndView;
}
Run Code Online (Sandbox Code Playgroud)

Spring Security是否为我提供了一种简单的方法将User对象存储到会话中,以便可以通过任何控制器方法轻松检索它?

我想避免每次执行数据库查找:

// Lookup user in database by e-mail
User user = userService.findUserByEmail(principal.getName());
Run Code Online (Sandbox Code Playgroud)

我正在使用Spring Security 4.2.

java spring spring-mvc spring-security spring-boot

4
推荐指数
1
解决办法
8318
查看次数

列表类型的Java泛型用法

有没有一种在这里使用Java泛型的方法,所以我的方法可以取List<Double>or或List<Pair<Double, Double>>

private Map<Integer, Double> getValuesMap(int indexBegin, int indexEnd, List<Double> values) {
  Map<Integer, Double> map = new LinkedHashMap<>();

  if (indexBegin <= indexEnd) {
    for (int i = indexBegin; i <= indexEnd; i++) {
      map.put(i, values.get(i));
    }
  } else {
    for (int i = indexBegin; i >= indexEnd; i--) {
      map.put(i, values.get(i));
    }
  }

  return map;
}
Run Code Online (Sandbox Code Playgroud)

java generics

4
推荐指数
1
解决办法
60
查看次数

JPA无法反序列化Java 8 LocalDateTime

当我的Entity类中有LocalDateTime字段时,我正在使用Spring Boot 1.5.1并在我点击API时获得异常.

MySQL dt列是TIMESTAMP

JPA无法本地反序列化LocalDateTime吗?

执行GET请求时的控制台输出

 2017-03-02 22:00:18.797 ERROR 13736 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize] with root cause

    java.io.StreamCorruptedException: invalid stream header: 20323031
Run Code Online (Sandbox Code Playgroud)

Reservation.class

package com.example.springboot.reservation;

import java.time.LocalDateTime;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

// Model class 

@Entity
@Table(name="reservation")
public class Reservation {

    @Id
    private Long id;

    @Column
    private LocalDateTime …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate jpa

2
推荐指数
1
解决办法
5452
查看次数

Thymeleaf的Spring安全表达

使用Spring Boot 1.5.2和Thymeleaf 2.1,我试图在HTML页面上添加一些代码来识别用户的角色.

但是,所有这些语句都评估为true,这是不正确的:

<div sec:authorize="hasAuthority('ADMIN')" > Has Authority ADMIN </div> 
<div sec:authorize="hasAuthority('USER')" > Has Authority USER </div> 
<div sec:authorize="hasRole('ROLE_ADMIN')">Has Role ROLE_ADMIN</div>
<div sec:authorize="hasRole('ROLE_USER')">Has Role ROLE_USER</div>
<div sec:authorize="hasRole('ADMIN')">Has Role ADMIN</div>
<div sec:authorize="hasRole('USER')">Has Role USER</div>
Run Code Online (Sandbox Code Playgroud)

User.java

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
Run Code Online (Sandbox Code Playgroud)

Role.java

@Entity
@Table(name = "role")
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;

    @Column(name = "role")
    private String role; …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security thymeleaf spring-boot

1
推荐指数
1
解决办法
5090
查看次数

防止 Java 中的 instanceof 和强制类型转换

instanceof如果我想要使用方法签名不同的不同验证器,如何避免在这种情况下使用和转换?

代码

for(BatchValidator validator : validators) {
  try {     
    if (validator instanceof BatchErrorValidator) {
      ((BatchErrorValidator<T>) validator).validate(targets);
    } else if (validator instanceof BatchWarningValidator) {
      ((BatchWarningValidator<T>) validator).validate(targets, header);
    }
  } catch (BatchValidationException e) {
    handleImportExceptions(e, header.getSequenceId());
  }
}
Run Code Online (Sandbox Code Playgroud)

java oop instanceof

-1
推荐指数
1
解决办法
145
查看次数