当前位置: 首页 > 知识库问答 >
问题:

Spring Boot JettyServerCustomizer HTTPS端口未打开需要ServletContext来配置默认servlet处理

阎晋
2023-03-14

我试图使用Spring Boot与嵌入式。我希望嵌入式码头打开一个HTTPS端口443。

import java.io.FileNotFoundException;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ssl.SslSocketConnector;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.jetty.JettyServerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.util.ResourceUtils;

import com.samsoft.expunto.service.UserService;

/**
 * @author Kumar Sambhav Jain
 * 
 */
@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests().antMatchers("/", "/resources/**")
                .permitAll().anyRequest().authenticated().and().formLogin()
                .loginPage("/").defaultSuccessUrl("/home", false).and()
                .requiresChannel().anyRequest().requiresSecure().and().logout()
                .invalidateHttpSession(true).logoutUrl("/logout")
                .logoutSuccessUrl("/").and().userDetailsService(userService);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
    }

    @Bean
    public JettyServerCustomizer jettyCutomizer() {
        return new JettyServerCustomizer() {

            @Override
            public void customize(Server server) {
                SslContextFactory sslContextFactory = new SslContextFactory();
                sslContextFactory.setKeyStorePassword("jetty6");
                try {
                    sslContextFactory.setKeyStorePath(ResourceUtils.getFile(
                            "classpath:jetty-ssl.keystore").getAbsolutePath());
                } catch (FileNotFoundException ex) {
                    throw new IllegalStateException("Could not load keystore",
                            ex);
                }
                SslSocketConnector sslConnector = new SslSocketConnector(
                        sslContextFactory);
                sslConnector.setPort(443);
                sslConnector.setMaxIdleTime(60000);
                server.addConnector(sslConnector);
            }
        };
    }
}
@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
        implements EmbeddedServletContainerCustomizer {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests().antMatchers("/", "/resources/**")
                .permitAll().anyRequest().authenticated().and().formLogin()
                .loginPage("/").defaultSuccessUrl("/home", false).and()
                .requiresChannel().anyRequest().requiresSecure().and().logout()
                .invalidateHttpSession(true).logoutUrl("/logout")
                .logoutSuccessUrl("/").and().userDetailsService(userService);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
    }

    public JettyServerCustomizer jettyServerCustomizer() {
        return new JettyServerCustomizer() {

            @Override
            public void customize(Server server) {
                SslContextFactory sslContextFactory = new SslContextFactory();
                sslContextFactory.setKeyStorePassword("jetty6");
                try {
                    sslContextFactory.setKeyStorePath(ResourceUtils.getFile(
                            "classpath:jetty-ssl.keystore").getAbsolutePath());
                } catch (FileNotFoundException ex) {
                    throw new IllegalStateException("Could not load keystore",
                            ex);
                }
                SslSocketConnector sslConnector = new SslSocketConnector(
                        sslContextFactory);
                sslConnector.setPort(443);
                sslConnector.setMaxIdleTime(60000);
                server.addConnector(sslConnector);
            }
        };
    }

    public void customizeJetty(
            JettyEmbeddedServletContainerFactory containerFactory) {
        containerFactory.addServerCustomizers(jettyServerCustomizer());
    }

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        if (container instanceof JettyEmbeddedServletContainerFactory) {
            customizeJetty((JettyEmbeddedServletContainerFactory) container);
        }
        container.setContextPath("");
    }
}
: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
    at org.springframework.util.Assert.notNull(Assert.java:112)
    at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.<init>(DefaultServletHandlerConfigurer.java:54)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:346)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$d7014349.CGLIB$defaultServletHandlerMapping$24(<generated>)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$d7014349$$FastClassBySpringCGLIB$$ec8be680.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$d7014349.defaultServletHandlerMapping(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)

共有1个答案

赵禄
2023-03-14

根据M.Deinum的建议,将定制器移动到用@EnableAutoConfiguration注释的类中就可以实现。

这对我很有效:-

@Configuration

@EnableAutoConfiguration
public class Application implements EmbeddedServletContainerCustomizer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }

    @Bean
    public JettyServerCustomizer jettyServerCustomizer() {
        return new JettyServerCustomizer() {

            @Override
            public void customize(Server server) {
                SslContextFactory sslContextFactory = new SslContextFactory();
                sslContextFactory.setKeyStorePassword("jetty6");
                try {
                    sslContextFactory.setKeyStorePath(ResourceUtils.getFile(
                            "classpath:jetty-ssl.keystore").getAbsolutePath());
                } catch (FileNotFoundException ex) {
                    throw new IllegalStateException("Could not load keystore",
                            ex);
                }
                SslSocketConnector sslConnector = new SslSocketConnector(
                        sslContextFactory);
                sslConnector.setPort(443);
                sslConnector.setMaxIdleTime(60000);
                server.addConnector(sslConnector);
            }
        };
    }

    public void customizeJetty(
            JettyEmbeddedServletContainerFactory containerFactory) {
        containerFactory.addServerCustomizers(jettyServerCustomizer());
    }

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        if (container instanceof JettyEmbeddedServletContainerFactory) {
            customizeJetty((JettyEmbeddedServletContainerFactory) container);
        }
    }
}
 类似资料:
  • 问题内容: 我有以下测试课: 问题似乎来自BaseTestConfiguration类: 我系统地得到了这个异常: 我不确定如何解决此问题。当我运行测试时,Spring不知何故正在寻找ServletContext并收到上述异常… 问题答案: 你的其中一门课程显然带有注释。这是如何结束在你的堆栈跟踪,因为它是进口的。 因此,尽管你认为自己不需要(因此也不需要),但实际上确实需要它,只是因为你正在使用

  • 当我将messageSource方法重命名为messageSource2时,它可以工作,但我不太会使用自带默认messageSource的LocalizedMessageService来查询自定义消息。 如何将自定义消息基名称添加到默认消息源?

  • 我正在将Spring MVC servlet 3.1应用程序移动到Spring Boot 1.3.0,当我将注释添加到我的一个Java配置类时,我在启动时出现异常(完整如下)。 我正在为我的Spring安全支持子类化

  • 问题内容: 通常,在switch语句中不需要默认值。但是,在以下情况下,仅当我取消注释默认语句时,代码才能成功编译。有人可以解释为什么吗? 问题答案: 您必须取消注释的原因是您的函数说它返回一个,但是如果您只为定义了标签,那么如果您传入其他任何内容,该函数将不会返回值。Java要求所有声明它们返回值的函数实际上在所有可能的控制路径上都返回一个值,并且在您的情况下,编译器不确信所有可能的输入都返回了

  • 问题内容: 我正在尝试将我的应用程序升级到新版本的Firebase。我仔细阅读了设置指南,并编辑了所有代码以匹配新语法。但是,当我运行该应用程序时,出现了这两个错误。 我 在AppDelegate中,并将GoogleServices- Info.plist导入到我的项目中。plist也具有所有正确的信息。其他人遇到这个问题或知道如何解决? 问题答案: 这是您的问题的答案: 要配置Firebase,

  • 与Jquery Mobile自动初始化共同协作 Working with Jquery Mobile's Auto-initialization 不像其他的Jq项目,比如jq和jq ui,Jquery Mobile会在加载到增强特性时马上应用它(远早于document.ready事件发生时)。这些特性会基于Jquery Mobile的默认配置应用,是针对默认的情形设计的,他可能符合你的需求,也可能