简体   繁体   English

独立运行Spring Boot应用程序时映射不起作用

[英]Mapping is not working when run spring boot application standalone

I used spring boot in my project. 我在项目中使用了弹簧靴。 when I start the application using ide everything is okay, but when I run the jar file and open the first page in browser, I see this text : 当我使用ide启动应用程序时,一切正常,但是当我运行jar文件并在浏览器中打开第一页时,我看到以下文本:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

There was an unexpected error (type=Not Found, status=404).
/login.html

Spring boot configuration class is : Spring Boot配置类是:

@EnableAutoConfiguration
@EnableTransactionManagement
@EnableJpaAuditing
@EnableCaching
@EnableWebMvc
@EnableWebMvcSecurity
@Import({SecurityLauncher.class})
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class Launcher extends WebMvcConfigurerAdapter {

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

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        super.addResourceHandlers(registry);
    }

    @Bean
    public DispatcherServlet dispatcherServlet() {
        return new DispatcherServlet();
    }

    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

How to solve this problem? 如何解决这个问题呢?

Edit -> Project tree 编辑->项目树

├── src
│   ├── main
│   │   ├── java
│   │   ├── resources
│   │   └── webapp
│   │       ├── app
│   │       │   ├── css
│   │       │   ├── js
│   │       │   │   ├── controllers
│   │       │   │   ├── directives
│   │       │   │   ├── factory
│   │       │   │   ├── filters
│   │       │   │   └── services
│   │       │   ├── lib
│   │       │   ├── resources
│   │       │   ├── templates
│   │       │   └── view
│   │       └── WEB-INF
|   |       |__ index and login files
│   └── test
│       └── java

Edit 2 -> Spring security config: 编辑2-> Spring安全配置:

public class SecurityLauncher extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login/*", "/login.html*").permitAll().antMatchers("/*").authenticated()
                .and().formLogin().loginProcessingUrl("/login").loginPage("/login.html")
                .passwordParameter("password").usernameParameter("username").defaultSuccessUrl("/").and()
                .logout().logoutUrl("/logout").deleteCookies("JSESSIONID").permitAll().and().csrf().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth, UserSecurityProvider securityProvider) throws Exception {
        auth.userDetailsService(securityProvider);
    }

}

The @SpringBootApplication is scanning for controller in the wrong package and does not find the controller so you have to remove @SpringBootApplication and let @ComponentScan(basePackages = "...") look for controller to get scaned right. @SpringBootApplication正在使用错误的软件包扫描控制器,并且找不到控制器,因此您必须删除@SpringBootApplication,并让@ComponentScan(basePackages =“ ...”)查找要正确扫描的控制器。 Do you see a mapping message in log when you start for login.html ? 启动login.html时,您是否在日志中看到映射消息?

Typically, in a Spring Boot application you place your static files under src/main/resources/static , src/main/resources/public , src/main/resources/resources or src/main/resources/META-INF/resources . 通常,在Spring Boot应用程序中,您将静态文件放置在src/main/resources/staticsrc/main/resources/publicsrc/main/resources/resourcessrc/main/resources/META-INF/resources Your templates belong to src/main/resources/templates . 您的模板属于src/main/resources/templates

The official documentation says: 官方文件说:

Do not use the src/main/webapp directory if your application will be packaged as a jar. 如果您的应用程序将打包为jar,则不要使用src / main / webapp目录。 Although this directory is a common standard, it will only work with war packaging and it will be silently ignored by most build tools if you generate a jar. 尽管此目录是一个通用标准,但它仅适用于war打包,如果生成jar,大多数构建工具都将忽略它。

If it is just a html file you need to add to the path src/main/resources/static 如果只是html文件,则需要添加到路径src / main / resources / static

src/main/resources/static/index.html

And the call it 然后打电话

http://{IP}:{port}/index.html

The issue lies in contextPath. 问题出在contextPath。 there are two ways to solve it: 有两种解决方法:

  1. run your app without any contextPath. 在没有任何contextPath的情况下运行您的应用。 eg http://localhost:8080/hello 例如http:// localhost:8080 / hello
  2. or set your contextPath in application.properties as server.contextPath=/myapp and then access the url as: http://localhost:8080/myapp/hello 或在application.properties中将contextPath设置为server.contextPath = / myapp,然后以以下方式访问该URL: http:// localhost:8080 / myapp / hello

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content

By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. 默认情况下,Spring Boot将从类路径中的/ static目录(或/ public或/ resources或/ META-INF / resources)或ServletContext的根目录中提供静态内容。 It uses the ResourceHttpRequestHandler from Spring MVC so you can modify that behavior by adding your own WebMvcConfigurerAdapter and overriding the addResourceHandlers method. 它使用Spring MVC中的ResourceHttpRequestHandler,因此您可以通过添加自己的WebMvcConfigurerAdapter并覆盖addResourceHandlers方法来修改该行为。

In a stand-alone web application the default servlet from the container is also enabled, and acts as a fallback, serving content from the root of the ServletContext if Spring decides not to handle it. 在独立的Web应用程序中,还启用了容器中的默认Servlet,并将其用作后备,如果Spring决定不处理,则从ServletContext的根目录提供内容。 Most of the time this will not happen (unless you modify the default MVC configuration) because Spring will always be able to handle requests through the DispatcherServlet. 大多数情况下,这种情况不会发生(除非您修改默认的MVC配置),因为Spring始终能够通过DispatcherServlet处理请求。

By default, resources are mapped on /** but you can tune that via spring.mvc.static-path-pattern. 默认情况下,资源映射在/ **上,但是您可以通过spring.mvc.static-path-pattern对其进行调整。 For instance, relocating all resources to /resources/** can be achieved as follows: 例如,将所有资源重定位到/ resources / **可以实现如下:

spring.mvc.static-path-pattern=/resources/** spring.mvc.static路径图案= /资源/ **

Hope helpful!!! 希望对大家有帮助!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM