首页 文章

如何使用spring security在spring boot中设置上下文路径

提问于
浏览
4

我在application.properties中将contextPath设置为带 spring 安全性的spring boot应用程序中的server.contextPath = / myWebApp,默认url为/ login它不将上下文路径设置为/ myWebApp,并将我重定向为/ login而不是/ myWebApp / login . 如何使用spring security 4.0设置contextPath?由于tomcat作为context []发出警告..没有在容器中部署app .

2 回答

  • 0

    我在 Application.properties 文件中设置 server.servlet.context-path 解决了这个问题

    代码示例

    Application.properties

    server.servlet.context-path=/myWebApp/


    有了这个,您还可以根据需要实现登录页面http://localhost:8080/myWebApp/login


  • 1

    在Spring Boot中,您可以通过3种方式设置上下文路径 .

    First in application.properties 就像你一样 .

    server.contextPath=/myWebApp
    

    Second the change can be done programmatically as well:

    import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
    import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
    import org.springframework.stereotype.Component;
    
    @Component
    public class CustomContainer implements EmbeddedServletContainerCustomizer {
    
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
    
            container.setPort(8181);
            container.setContextPath("/myWebApp ");
    
        }
    
    }
    

    And Finally, by passing the system properties directly:

    java -jar -Dserver.contextPath=/myWebApp spring-boot-example-1.0.jar
    

    Spring Security Config is:

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/static/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .loginPage("/login")
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .loginProcessingUrl("/j_spring_security_check")
                    .failureUrl("/login?error=true")
                    .defaultSuccessUrl("/index")
                    .and()
                    .logout().logoutUrl("/logout").logoutSuccessUrl("/login")
                    ;
    
        }
    }
    

    并且没有任何进一步的更改,tomcat将自动启动 /myWebApp/login

相关问题