繁体   English   中英

Spring 开机无法解析 Thymeleaf 查看

[英]Spring Boot can't resolve Thymeleaf view

我将 Spring Boot 与 Thymeleaf 集成,但 web 在 controller 返回视图后不会重定向或转发。 这是 Thymeleaf 页面:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>login</title>

    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/3.3.7/css/bootstrap.css}" rel="stylesheet">
    <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Open+Sans:400,300'>
    <link rel='stylesheet' href='https://fonts.googleapis.com/icon?family=Material+Icons'>

    <link rel="stylesheet" href="css/style.css" th:href="@{/css/style.css}">


</head>

<body>

            <div class="cont_forms">
                <div class="cont_img_back_">
                    <img src="https://images.unsplash.com/42/U7Fc1sy5SCUDIu4tlJY3_NY_by_PhilippHenzler_philmotion.de.jpg?ixlib=rb-0.3.5&q=50&fm=jpg&crop=entropy&s=7686972873678f32efaf2cd79671673d"
                         alt=""/>
                </div>
                <div class="cont_form_login">
                    <a href="#" onclick="ocultar_login_sign_up()"><i class="material-icons">&#xE5C4;</i></a>
                    <h3>login</h3>
                    <input id="login_name" type="text" placeholder="username"/>
                    <input id="login_password" type="password" placeholder="password"/>
                    <div class="checkbox mb-3" style="margin:5% auto 0% 2%">
                        <label>
                            <input type="checkbox" id="remember"> Remember me
                        </label>
                    </div>
                    <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
                    <button class="btn_login" onclick="login('http://localhost:8080/assignment/user/login')">login</button>
                </div>

            </div>

        </div>
    </div>
</div>

<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="js/index.js"></script>

<script>
    function login(url) {
        var username = document.getElementById("login_name").value;
        var password = document.getElementById("login_password").value;
        $.post(url, {'username':username, 'password':password});
    }

</script>

</body>

</html>

我有一个 controller:

@RestController
public class LoginController {

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private TeacherRepository teacherRepository;

    @PostMapping(value = "/user/login")
    public ModelAndView login(@RequestParam("username") String username,
                              @RequestParam("password") String password,
                              Map<String, Object> info,
                              HttpSession session) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("index");
            Optional<Student> student = studentRepository.findById(username);
            if (!student.isPresent()) {
                info.put("msg", "User doesn't exist.");
            } else {
                try {
                    if (!EncryptUtil.aesDecrypt(student.get().getPassword()).equals(password)) {
                        info.put("msg", "Wrong password!");
                    } else {
                        System.out.println("-------------------------success");
                        session.setAttribute("user", student.get().getName()); 
                        mv.setViewName("student/homework");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        return mv;
    }
}

我可以在控制台中看到------------------------success ,这意味着方法login已成功退出 ** 但页面没有改变。**它不只是 go 到 view student/homework 有人帮忙吗? 另外这是pom.xml

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7</version>
        </dependency>
    </dependencies>

- - - - - - - - - - - - -更新 - - - - - - - - - - - - ------
这是堆栈跟踪:

2018-08-11 12:21:29.824  INFO 13220 --- [nio-8080-exec-1] o.a.c.c.C.[.[localhost].[/assignment]    : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-08-11 12:21:29.824  INFO 13220 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2018-08-11 12:21:29.876  INFO 13220 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 52 ms
Hibernate: select student0_.id as id1_0_0_, student0_.name as name2_0_0_, student0_.password as password3_0_0_ from students student0_ where student0_.id=?
-------------------------success

另外,我发现另一个问题。 我尝试自定义 Spring MVC,所以我写了一个配置 class:

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                // welcome page
                registry.addViewController("/").setViewName("index");
                registry.addViewController("/index.html").setViewName("index");
            }
        };
        return adapter;
    }
}

但是 IDEA 显示WebMvcConfigurerAdapter已被弃用。 我应该怎么办? 我在 Spring 引导参考文档中找不到解决方案。

要渲染视图,您需要使用@Controller

改变这个:

@RestController
public class LoginController {
}

至:

@Controller
public class LoginController {
}

不要使用 ModelAndView,而是尝试使用Model 做以下 -

  1. 使用Controller而不是RestController

  2. 将返回类型更改为字符串。

  3. 将 thymeleaf 属性添加到您的 Model object。

  4. 返回要显示的模板名称。

  5. 在您的属性/YML 文件中配置模板路径 -

    spring.thymeleaf.prefix = 类路径:/您的文件夹名称/

暂无
暂无

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

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