【问题标题】:Spring Boot Redirecting to another controller method from current controller methodSpring Boot从当前控制器方法重定向到另一个控制器方法
【发布时间】:2019-03-21 15:24:54
【问题描述】:

大家好,我是 Spring Boot 新手。我被困在我的学习道路中间。我有两个控制器(@Controller),其中定义了一些方法。我正在将表单数据提交到索引控制器中的方法,并且如果表单提交成功(成功登录),则希望移动到主控制器中的方法。在加载索引控制器的http://localhost:9090/method 时,它会正确加载所有静态内容,但是当我重定向return "redirect:/dashboard/index" 时,它会导航到http://localhost:9090/dashBoard/index。而/dashboard/index方法如下

@Controller
public class HomeController {
    @GetMapping(value = "/dashBoard/index")
    public String hello(Model model, @RequestParam(value = "name", required = false, defaultValue = "World") String name) {
        model.addAttribute("name", name);
        return "index";
    }
}

此方法返回“索引”,即.jsp 页面,但重定向到此方法会更改静态内容路径,例如http://localhost:9090/dashBoard/assets/images/avatar/1.jpg

似乎在静态内容的路径中附加/dashBoard/。我不明白该怎么做,请帮忙。我正在添加我的项目属性和结构,请查看

application.properties

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring.resources.static-locations=file:/var/www/static,classpath:static
spring.mvc.static-path-pattern=/resources/**
server.port=9090
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57InnoDBDialect
spring.jackson.serialization.fail-on-empty-beans=false

main class

[@SpringBootApplication
@EnableAutoConfiguration
public class SchoolpageApplication extends SpringBootServletInitializer {

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

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(SchoolpageApplication.class);
    }
}

Project Structure

Static content path

【问题讨论】:

    标签: spring-boot


    【解决方案1】:
    @Controller
    @RequestMapping("/dashBoard")
    public class HomeController {
        @GetMapping("index")
        public String hello(Model model, @RequestParam(value = "name", required = false, defaultValue = "World") String name) {
            model.addAttribute("name", name);
            return "index";
        }
    }
    

    你可以试试这个方法,每次你通过 /dashboard 访问一个 url,你都会进入这个控制器,你可以控制你想要的每个选项,比如 /foo(在这种情况下是 /index)和return 它会让你进入 /dashboard/+你的返回值(在这种情况下是索引)。

    我不是弹簧靴方面的专家,我对它也很陌生,但我希望这可以帮助你。

    【讨论】:

    • 您好,感谢您的回答,但您的想法行不通。我已经尝试过这种方式,但没有帮助。我通过将请求映射值从“dashBoard/index”缩短为“/index”并正确加载所有静态内容来解决它。
    猜你喜欢
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 2021-12-20
    • 2012-10-13
    相关资源
    最近更新 更多