标签: spring-boot

Spring Boot 句柄 SizeLimitExceededException

我使用 Spring Boot 1.5.7。
我还没有配置 CommonsMultipartResolver,因为 Spring Boot 已经处理文件上传了。

如果我的上传超过允许的最大大小,则会抛出一个丑陋的异常。
这是由我的控制器处理的。

@ControllerAdvice
public abstract class DefaultController implements InitializingBean {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ServiceException> handleException(final Exception ex) {
        ...
        } else if (ex instanceof MultipartException) {
            MultipartException me = (MultipartException) ex;
            Throwable cause = ex.getCause();
            if (cause instanceof IllegalStateException) {
                Throwable cause2 = cause.getCause();
                if (cause2 instanceof SizeLimitExceededException) {
                    // this is tomcat specific
                    SizeLimitExceededException slee = (SizeLimitExceededException) cause2;
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

这种处理不仅复杂而且可悲的是 Tomcat 特定的,因为 SizeLimitExceededException 在包中org.apache.tomcat.util.http.fileupload.FileUploadBase

我如何处理错误情况,即有人上传更大的文件然后允许并返回一条不错的消息,无论使用哪个 Servlet 引擎?

java spring-boot

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

Spring boot 连接池理解

在 Spring boot application.properties 文件中,我们有以下选项:

server.tomcat.max-threads = 100
server.tomcat.max-connections = 100
spring.datasource.tomcat.max-active = 100
spring.datasource.tomcat.max-idle = 30
Run Code Online (Sandbox Code Playgroud)

这是我的存储库类

public interface UserRepository extends JpaRepository<Users,Integer>{}
Run Code Online (Sandbox Code Playgroud)

这是服务类

@Service
@Transactional(rollbackFor = Exception.class)
public class UserService {

    @Autowired
    private UserRepository userRepository;
    public User getUserById(Integer id){return userRepository.findOne(id)}
Run Code Online (Sandbox Code Playgroud)

问题是,userRepository 如何创建与 DB 的连接以及它是否会使用我的应用程序属性文件中的连接池。我来自 JDBC 和 hibernate,在那里我使用了 DataManager、DataSource、Connection 类来使用连接池,但是在 Spring Boot 中,我没有这些类的任何代码行,一切正常

java spring database-connection spring-boot connection-pool

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

如何在使用 Spring Boot 2.0.0.M4+ 的某些环境中要求 SSL

在通过 2.0.0 里程碑版本升级我的 Spring Boot 应用程序时,我注意到从 2.0.0.M4 开始security.require-ssl和其他安全配置选项都消失了。我在当前文档中没有发现任何关于弃用或新方法的提及,所以我四处寻找并找到了工作起源的 GitHub 问题。我为 GitHub 问题中的目标鼓掌:

显着简化了 2.0 中的安全配置。

并且很高兴更改我的模式以进行升级,但我对如何在特定环境中要求 SSL 有点卡住了。我知道我可以在我的WebSecurityConfigurerAdapter配置中使用实现类似的结果,http.requiresChannel().anyRequest().requiresSecure()但我不想在我运行我的应用程序的每个环境中启用这个设置(例如,没有证书的预生产环境,本地开发)。我知道我可以在我的WebSecurityConfigurerAdapter配置中放置一些条件逻辑,但我喜欢保持我的 Spring 配置“环境不可知”,并将我的环境特定配置保存在特定于配置文件的属性文件中。

在最近对 Spring Boot 的安全配置进行了这些简化更改之后,在某些环境中需要 SSL 的推荐方法是什么?

spring-security spring-boot

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

Spring Boot - 动态更改连接

我有一个 Spring Boot 项目,其中包含多个不同年份的数据库,并且这些数据库具有相同的表,因此唯一的区别是年份(...,DB2016,DB2017)。在应用程序的控制器中,我需要返回属于“不同”年份的数据。此外,在未来几年将创建其他数据库(例如,在 2018 年将有一个名为“DB2018”的数据库)。所以我的问题是如何在不每年创建新数据源和新存储库的情况下切换数据库之间的连接。在我发布的另一个问题中(Spring Boot - 不同数据库的相同存储库和相同实体) 答案是为每个现有数据库创建不同的数据源和不同的存储库,但在这种情况下,我想根据当前年份从现有数据库中返回数据。进一步来说:

一些实体.java

@Entity(name = "SOMETABLE")
public class SomeEntity implements Serializable {
@Id
@Column(name="ID", nullable=false)
private Integer id;

@Column(name="NAME")
private String name;
}
Run Code Online (Sandbox Code Playgroud)

SomeRepository.java

public interface SomeRepository extends PagingAndSortingRepository<SomeEntity, Integer> {
@Query(nativeQuery= true, value = "SELECT * FROM SOMETABLE WHERE NAME = ?1")
List<SomeEntity> findByName(String name);
}
Run Code Online (Sandbox Code Playgroud)

一些控制器.java

@RequestMapping(value="/foo/{name}", method=RequestMethod.GET)
public ResponseEntity<List<SomeEntity>> findByName(@PathVariable("name") String name) {
List<SomeEntity> list = autowiredRepo.findByName(name);
return new ResponseEntity<List<SomeEntity>>(list,HttpStatus.OK);

}
Run Code Online (Sandbox Code Playgroud)

应用程序属性

spring.datasource.url=jdbc:postgresql://localhost:5432/DB
spring.datasource.username=xxx
spring.datasource.password=xxx
Run Code Online (Sandbox Code Playgroud)

所以如果今年是 2017 …

spring database-connection datasource dynamic spring-boot

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

404-not-found-while-running-spring-boot-rest-api

运行 springboot restservice 应用程序时出现 404 错误。我正在使用弹簧靴,球衣休息。我尝试过 GET 请求,http://localhost:8080/dunames但无法解决。请帮忙。

型号分类:

@Entity
@Table(name = "du")
public class duname {


    private String duname;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id; 
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public duname()
    {

    }

    public duname(String duname, int id)
    {
    this.duname=duname; 
    this.id=id;
    }


    public String getDuname() {
        return duname;
    }

    public void setDuname(String duname) {
        this.duname = duname;
    }
}
Run Code Online (Sandbox Code Playgroud)

服务等级:

public class duservice { …
Run Code Online (Sandbox Code Playgroud)

java rest spring-boot

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

如何在 keycloak 登录页面上实现 Recaptcha

我想在keycloak登录页面(如注册页面)中实现recaptcha。我使用所需的工厂类扩展了 UsernamePasswordForm 类。我什至还实施了行动要求类。但我仍然无法在提供者选项卡中看到添加登录信息。我也修改了现有的 login.ftl,但没有运气。

下面是我尝试过的。

我的身份验证器类:

public class MyLoginAuthenticator extends UsernamePasswordForm {

    @Override
    public void action(AuthenticationFlowContext context) {
        MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
        if (formData.containsKey("cancel")) {
            context.cancelLogin();
            return;
        }

        if (!validateForm(context, formData)) {
            return;
        }
        context.success();
    }

    protected boolean validateForm(AuthenticationFlowContext context, MultivaluedMap<String, String> formData) {
        return validateUserAndPassword(context, formData);
    }

    @Override
    public void authenticate(AuthenticationFlowContext context) {
        MultivaluedMap<String, String> formData = new MultivaluedMapImpl<>();
        String loginHint = context.getAuthenticationSession().getClientNote(OIDCLoginProtocol.LOGIN_HINT_PARAM);

        String rememberMeUsername = AuthenticationManager.getRememberMeUsername(context.getRealm(), context.getHttpRequest().getHttpHeaders());

        if (loginHint != null || rememberMeUsername != null) {
            if …
Run Code Online (Sandbox Code Playgroud)

java recaptcha spring-boot keycloak wildfly-10

4
推荐指数
2
解决办法
8547
查看次数

尤里卡客户端在尤里卡服务器 UI 中以名称“未知”运行

我创建了一个 Eureka 服务器 Spring Boot 应用程序。它已正确加载。之后我试图创建一个尤里卡客户端。但它没有在尤里卡服务器 UI 中列出。我正在添加我的客户端应用程序详细信息。

我的主控制器类文件如下,

@SpringBootApplication
@EnableDiscoveryClient
public class ZEurekaClientServiceApplication {

public static void main(String[] args) {
    SpringApplication.run(ZEurekaClientServiceApplication.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)

我的 pom.xml 包含 ,

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
Run Code Online (Sandbox Code Playgroud)

我的 application.properties 文件包含,

eureka.client.serviceUrl.defaultZone=http://localhost:8071/eureka
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
Run Code Online (Sandbox Code Playgroud)

当 It 客户端运行时,尤里卡服务器 UI 不显示它的名称。仅将 UNKNOWN 显示为应用程序。我在下面添加它的屏幕截图。在此处输入图片说明

我需要在尤里卡服务器 UI 中显示应用程序名称而不是“UNKNOWN”吗?是否有任何额外的设置来添加应用程序名称?

spring-boot netflix-eureka

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

在客户端 Spring Boot 应用程序上配置自定义 OAuth2AccessToken

授权服务器通常为您提供的标准 JSON 格式有一个名为“expires_in”的属性,但现在我正在使用一个自动化服务器,它为我提供了一个名为“access_token_expires_in”的属性。因此,即使在 access_token 过期时,我的 OAuth2AccessToken 也总是将 isExpired 返回为 false,这是有道理的,因为它试图读取不存在的“expires_in”属性。OAuth2AccessToken 的 getAdditionalInformation 返回我的“access_token_expires_in”属性值,值为 18000。

我想知道我是否可以告诉 spring 使用“access_token_expires_in”属性作为我的 access_token 的过期值?

我的代码:

@Configuration
class OAuth2RestConfiguration {
    @Bean
    protected OAuth2ProtectedResourceDetails resource() {

        final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
        resourceDetails.setAccessTokenUri("<tokenUri>");
        resourceDetails.setClientId("<clientId>");
        resourceDetails.setClientSecret("<clientSecret>");

        return resourceDetails;
    }

    @Bean
    public OAuth2RestTemplate restTemplate() throws Exception {
        final AccessTokenRequest atr = new DefaultAccessTokenRequest();
        final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resource(),
                new DefaultOAuth2ClientContext(atr));

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

授权服务器响应示例:

{
    "refresh_token_expires_in": 0,
    "access_token": "<access_token>",
    "access_token_expires_in": 18000,
    "token_type": "bearer"
}
Run Code Online (Sandbox Code Playgroud)

编辑 1: 作为一种解决方法,我扩展了 …

java spring-boot spring-security-oauth2

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

CORS 和 Spring Websocket

我已经按照本教程构建了一个提供websockets连接的 Spring Boot 应用程序,但除了 Spring Boot 本身提供的服务之外,我无法从其他客户端连接到这些 websocket。

complete教程附带的 GitHub 存储库中目录包含最终的 Spring Boot 代码。我从这个存储库中获取了index.htmlapp.js文件,并创建了另一个在 Node.js 服务器上运行的客户端。之后,我将连接字符串替换为指向localhost:8080(运行 Spring Boot 的位置)。然后我运行 Node.js 服务器并尝试使用 websockets,但它不起作用。

通过添加.setAllowedOrigins("*")StompEndpointRegistry注册表中,第一个问题很容易解决。使用此配置,我设法连接到 websocket,但现在我再也没有从套接字收到消息。

我不知道我错过了什么......有谁知道是什么问题?

提取index.htmlapp.js(重命名为index.js)文件以及Node.js 服务器可以在此处找到以进行测试。要运行它,只需安装依赖项 ( npm install),然后发出npm start. 服务器将响应http://localhost:3000/

spring stomp websocket cors spring-boot

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

使用 Spring Reactive 时如何验证 Mono

我们正在为一个项目评估 Spring 5,但不确定如何最好地验证Mono参数。传统上,我们一直使用MethodValidationPostProcessor来验证我们的方法参数,如下所示:

@Validated
@Service
public class FooService

@Validated(SignUpValidation.class)
public void signup(@Valid UserCommand userCommand) {

    ...
}
Run Code Online (Sandbox Code Playgroud)

然后我们将在ControllerAdviceor 中处理异常ErrorController,并将合适的 4xx 响应传递给客户端。

但是当我将参数更改为 时Mono,如下所示,它似乎不再起作用。

@Validated
@Service
public class FooService

@Validated(SignUpValidation.class)
public Mono<Void> signup(@Valid Mono<UserCommand> userCommand) {

    ...
}
Run Code Online (Sandbox Code Playgroud)

据我了解 Spring Reactive,可能它实际上不应该工作。那么,验证Monos 和Fluxes 然后发送合适的错误响应的Spring 5 最佳实践是什么?

spring spring-mvc spring-validator spring-boot spring-webflux

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