无法使用Spring Boot找到html页面 [英] cannot find html pages with spring boot

查看:101
本文介绍了无法使用Spring Boot找到html页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是弹簧靴,前端是角形.有时我想直接从服务重定向.我们仅使用.html,.css和脚本文件(没有.jsp).

这是返回"static/pages/savepassword.html"; 我如何尝试重定向到savepassword

第一个问题是在这种情况下如何正确重定向?

接下来,Spring找不到我的html文件.我有这个结构

我读到spring应该自动在"static"中找到所有静态文件,但事实并非如此.所以我尝试配置ViewControllerRegistry和RessourceControllerRegistry

  @Override公共无效addResourceHandlers(ResourceHandlerRegistry注册表){super.addResourceHandlers(registry);Registry.addResourceHandler("/static/**").addResourceLocations("/static/");//Registry.addResourceHandler("/stylesheets/**").addResourceLocations("/stylesheets/");//Registry.addResourceHandler("/scripts/**").addResourceLocations("/scripts/");//Registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");}@Override公共无效addViewControllers(ViewControllerRegistry注册表){super.addViewControllers(registry);Registry.addViewController("/savePassword").setViewName("static/pages/savePassword.html");Registry.addViewController("/login").setViewName("static/pages/login.html");Registry.setOrder(Ordered.HIGHEST_PRECEDENCE);} 

当我直接调用"static/pages/login.html"时,它可以工作.当我想打电话给"/login"时,它会显示404.第二个问题:我需要配置什么,不需要什么?

UPDATE-1:Spring Security

  http.authorizeRequests().antMatchers("/login","/logout","/user/**").permitAll().anyRequest().authenticated().和().异常处理().accessDeniedHandler(新的CustomAccessDeniedHandler()).authenticationEntryPoint(新的CustomAuthenticationEntryPoint()).和().requiresChannel().anyRequest().requiresSecure().和().csrf().disable()//.csrfTokenRepository(csrfTokenRepository()).addFilterBefore(new MDCFilter(),ExceptionTranslationFilter.class)//.addFilterBefore(new CorsFilter(),//ChannelProcessingFilter.class)//.addFilterAfter(new CsrfHeaderFilter(),CsrfFilter.class).formLogin().successHandler(新的CustomSuccessAuthenticationHandler()).failureHandler(新的CustomFailureHandler()).loginPage("/login").permitAll(); 

UPDATE-2 我更新了我的结构,但是在从/login重定向到自定义登录名时仍然遇到问题.

UPDATE-3 我看了鲍勃·希尔兹(Bob Shields)的第二条评论:

1.静态资源

Spring有一些默认配置,您可以在其中放置静态资源而不进行配置.您需要在 src/main/resources

中创建这些文件夹
  • /META-INF/resources/
  • 资源(是的,是src/main/resources中的一个附加资源文件夹
  • 静态
  • 公开

此处春季Doku.例如,请查看Bob Shields的第二条评论:

创建了一堆"findme.txt"文件后,每个文件内部都有不同的相对于源"路径字符串,我发现可以使用"

src/main/resources/public/findme.txt

src/main/resources/static/findme.txt

src/main/resources/resources/findme.txt-(是,资源^ 2!)

src/main/resources/findme.txt-找不到!

我将文件夹脚本"和样式表"放置在静态文件夹中.当我想在html中包含这些文件夹中的文件时,源代码看起来像 src ="scripts/file.js" ,因为 static 中的文件和文件夹是直接植根的到 host/scripts/file.js

我不需要ResourceHandlerRegistry!

2.查看控制器

我想将我的login.html根目录为/login,savepassword.html根目录为/savepassword,并将index.html根目录为/.这是我所做的:

  registry.addViewController("/savepassword").setViewName("savepassword.html");Registry.addViewController("/login").setViewName("login.html");Registry.addViewController("/").setViewName("loggedin/index.html"); 

我设置* .html是因为否则我会遇到一个问题,即spring不知道/login和login(.html)之间的区别.如您所见,我将index.html放在另一个名为"loggedin"的文件夹中.这个文件夹就在我的公共文件夹中(由Spring找到,请参见1.).我为什么要这样做?看看3.

3.春季安全性

  .authorizeRequests().antMatchers("/stylesheets/**","/scripts/**","/login","/user/**").permitAll()...省略了进一步的配置....loginPage("/login").permitAll(); 

首先,我希望用户必须先登录才能访问任何其他站点.因此,用于登录页面的所有资源都必须可用.

这段代码使样式表和脚本中的每个文件都可以访问.请记住,样式表和脚本文件夹放置在静态位置.由于自定义登录页面,我不得不设置"/login".老实说,我认为 .loginPage("/login").permitAll(); 会授予访问权限,但事实并非如此.没有它,Spring会尝试访问"/login",但不会导致没有权限,然后自动重定向到login => ERR_TOO_MANDY_REDIRECTS."/user/**"仅用于我的每个用户可以使用的某些服务.

如您所见,我没有访问"loggedin"文件夹的权限,因此,每个访问者只有登录后才能在"loggedin"中输入文件;)

4.重定向

我刚刚用@RequestController标记了我的整个控制器,该控制器实现了@ResponseBody.当我返回类似return "redirect:/savepassword"; 的String时,Spring会将其设置为ResponseBody并将其解释为String/Json(?).

我必须将控制器标记为@Controller,并将@ResponseBody设置为必须返回json或sth的每个服务.我应重定向的服务仅用@RequestMapping和method = RequestMethod.GET标记.最后,我返回一个类似 return"redirect:/savepassword"; 的字符串,这将使Spring重定向到/savepassword,该文件实际上位于 src/main/resources/public/savepassword.html中.

最后,它可以工作,而且很难找到spring如何提供文件.我希望它对其他人有帮助:)

I am using spring boot and angular in front end. Sometimes I want to redirect directly from a service. We are using only .html, .css and script files (no .jsp).

This is return "static/pages/savepassword.html"; how I tried to redirect to savepassword

So 1st question how do I redirect properly in this case?

Next, Spring doesn't find my html files. I have this structure

I read that spring should find all static files in "static" automatically, but it doesn't. So I tried to configure my ViewControllerRegistry and RessourceControllerRegistry

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        super.addResourceHandlers(registry);
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
//      registry.addResourceHandler("/stylesheets/**").addResourceLocations("/stylesheets/");
//      registry.addResourceHandler("/scripts/**").addResourceLocations("/scripts/");
//      registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        super.addViewControllers(registry);
        registry.addViewController("/savePassword").setViewName("static/pages/savePassword.html");
        registry.addViewController("/login").setViewName("static/pages/login.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }

When I call "static/pages/login.html" directly, it works. When i want to call "/login" it says 404. 2nd question: What do I need to configure and what not?

UPDATE-1: Spring Security

http
            .authorizeRequests().antMatchers("/login", "/logout", "/user/**").permitAll()
            .anyRequest().authenticated()
        .and()
            .exceptionHandling()
            .accessDeniedHandler(new CustomAccessDeniedHandler())
            .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
        .and()
            .requiresChannel()
            .anyRequest().requiresSecure()
        .and()
            .csrf()
            .disable()
            //.csrfTokenRepository(csrfTokenRepository())
            .addFilterBefore(new MDCFilter(), ExceptionTranslationFilter.class)
            // .addFilterBefore(new CorsFilter(),// ChannelProcessingFilter.class)
            //.addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
            .formLogin()
            .successHandler(new CustomSuccessAuthenticationHandler())
            .failureHandler(new CustomFailureHandler())
            .loginPage("/login").permitAll();

UPDATE-2 I updated my structure, but still have problems with redirecting from /login to the custom login.

UPDATE-3 I had a look at the 2nd comment by Bob Shields: https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot I did the following:

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        super.addResourceHandlers(registry);
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        super.addViewControllers(registry);
        registry.addViewController("/savepassword").setViewName("savepassword.html");
        registry.addViewController("/login").setViewName("login.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }

I set .html because otherwise /login would cause recursive problems. With this config, I can enter /login and /templates/login.html will be called (same for savepassword.html).

Now, I would like to know how to include my css/js in html:

<link rel="stylesheet" type="text/css" href="..resources/stylesheets/bootstrap.min.css" />
    <script src="..resources/scripts/angular.min.js"></script>
    <script src="..resources/scripts/login.js"></script>

This doesn't work...but I cann call my scripts directly with /scripts/login.js.

解决方案

Ok, now I totally got it. I try to be specific as possible.

My final structure

1. Static Ressources

Spring has some default configuration where you can put your static ressources without configure it. You need to create those folders in src/main/resources

  • /META-INF/resources/
  • resources (yes, an additional resources folder in src/main/resources
  • static
  • public

Have a look here in Spring Doku. For an example, check the 2nd comment by Bob Shields:

After creating a bunch of "findme.txt" files, each of which had different "source-relative" path string inside, I found that the following locations can be fetched with "http://host/findme.txt" are:

src/main/resources/public/findme.txt

src/main/resources/static/findme.txt

src/main/resources/resources/findme.txt - (yes, resources^2!)

src/main/resources/findme.txt - not found!!

I placed my folder "scripts" and "stylesheets" in the static folder. When I want to include files from these folders in html, the source looks like src="scripts/file.js"because the files and folders in staticare found directly rooted to host/scripts/file.js

No ResourceHandlerRegistry was necessary for me!

2. View Controller

I wanted to root my login.html to /login, savepassword.html to /savepassword and my index.html to /. Here is what I did:

registry.addViewController("/savepassword").setViewName("savepassword.html");
registry.addViewController("/login").setViewName("login.html");
registry.addViewController("/").setViewName("loggedin/index.html");

I set *.html because otherwise I had a problem that spring didn't know to differ between /login and the login(.html). As you can see I placed the index.html in a different folder called "loggedin". This folder is right in my public-folder (found by Spring, see 1.). Why do I do this? Have a look at 3.

3. Spring Security

.authorizeRequests().antMatchers("/stylesheets/**", "/scripts/**","/login", "/user/**").permitAll()
...omitted further configuration...
.loginPage("/login").permitAll();

First, I want that a user always has to be logged in before he can visit any other sites. So all ressources for loginpage must be available.

This piece of code makes every file in stylesheets and scripts accessible. Remember stylesheets and scripts-folder are placed in static. I had to set "/login" because of the custom loginpage. Honestly I thought that the .loginPage("/login").permitAll();would grant access, but it doesn't. Without it Spring tries to access the "/login", but can't cause of no rights and then automatically redirects to login => ERR_TOO_MANDY_REDIRECTS. "/user/**" is just for some of my services that every user can use.

As you can see, I don't give access to "loggedin"-folder, so that every visitor can enter files in "loggedin" only if he is loggedin ;)

4. Redirecting

I just marked my whole controller with @RequestController, which implements @ResponseBody. When I return a String like return "redirect:/savepassword";, Spring will set this as ResponseBody and it will be interpreted as String/Json(?).

I had to mark the controller as @Controller and set @ResponseBody to every service that must return json or sth. My service that shall redirect was only marked with @RequestMapping and method=RequestMethod.GET. Finally, I return a String like return "redirect:/savepassword"; This will make Spring redirect to /savepassword, which actually is placed in src/main/resources/public/savepassword.html.

Finally, it works and it was hard enough to find how spring serves the files. I hope it helps someoneelse :)

这篇关于无法使用Spring Boot找到html页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆