【问题标题】:Building a Spring Boot project using Maven使用 Maven 构建 Spring Boot 项目
【发布时间】:2016-10-14 15:20:35
【问题描述】:

更新:

感谢大家的回答。我仍然有问题,因为它没有返回我希望的结果。是文件放置的问题吗?它们是这样组织的:i63.tinypic.com/2by8g2.png

再次提前致谢。


我正在学习使用 Spring Boot 和 JDBC(没有 JPA)创建一个 Web 应用程序;我在做这件事时遇到了几个问题。 我不明白如何正确创建控制器,以及如何让它返回我想要的 .jsp 页面。 我搜索了很多解决方案,但找不到合适的解决方案。 这是我的 pom.xml:

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>---myprojectname</groupId>
    <artifactId>tesieasy</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>tesieasy</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.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>
    </properties>

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

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

我的 application.properties:

> spring.h2.console.enabled=true
server.port=8000
spring.view.prefix=/WEB-INF/jsp/
spring.view.suffix=.jsp

我的 ServetInizializer:

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(TesieasyApplication.class);
    }

}

我的实体:

import java.util.Date;
import java.text.SimpleDateFormat;

public class Journal {

    private Long id;
    private String title;
    private Date created;
    private String summary;
    private SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");

    /** costruttori**/
    public Journal() {}

    public Journal(Long id, String title, String summary, Date date){
        this.id = id;
        this.title = title;
        this.summary = summary;
        this.created = date;
    }

    /** getters and setters omitted **/

我的服务:

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import name of my package-.entity.Journal;


@Service
public class JournalService {
    private static final Logger log = LoggerFactory.getLogger(JournalService.class);

    @Autowired
    JdbcTemplate jdbcTemplate;

    public void insertData() {
        log.info("> Table creation");
        jdbcTemplate.execute("DROP TABLE JOURNAL IF EXISTS");
        jdbcTemplate
                .execute("-cut for brevity-");
        log.info("> Done.");
    }

    public List<Journal> findAll() {
        List<Journal> entries = new ArrayList<>();
        jdbcTemplate
                .query("SELECT * FROM JOURNAL",
                        new Object[] {}, (rs, row) -> new Journal(rs.getLong("id"), rs.getString("title"),
                                rs.getString("summary"), new Date(rs.getTimestamp("created").getTime())))
                .forEach(entry -> entries.add(entry));
        return entries;

    }

        public int countEntries() {
        int rowCount = this.jdbcTemplate.queryForObject("SELECT count(*) FROM JOURNAL", Integer.class);
        return rowCount;

    }

    public Journal insertJournal() {
        Journal journal = null;
        this.jdbcTemplate.update(
                -cut for brevity-");
        return journal;

    }
}

我的一个 .jsp 页面:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>A title</title></head>
<body>
Hello! JSP is working fine!
</body>
</html>

最后是我的控制器:

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import *my package name.entity.Journal;
import *my package name.service.JournalService;

@RestController
public class HelloController {

    @Autowired
    private JournalService journalService;

    @RequestMapping(value="/")
    public String home() {
    return "home";
    }

    @RequestMapping("/greeting")
    public String greeting() {
        return "greeting";
    }


    @RequestMapping("/findAll")
    public String index() {
        List<Journal> all;
        all = journalService.findAll();
        return all.toString();
    }

    @RequestMapping("/count")
    public int countElements() {
        int count;
        count = journalService.countEntries();
        return count;
    }

    @RequestMapping("/insert")
    public Journal insertElements() {
        Journal insert;
        insert = journalService.insertJournal();
        return insert;
    }

}

我的理解:

  • 我不需要 web.xml 文件
  • 如何将服务与控制器连接(即使我的 findAll 方法将我的数据返回到 {},我也必须了解如何正确编写)

我不明白的:

  • 为什么它没有正确链接到我的 JSP 页面 - 我需要什么?
  • 我需要模型和视图吗?

我希望你能给我一些建议和/或一些适合我范围的例子。 提前致谢并致以最诚挚的问候!

【问题讨论】:

  • @RestController 不应用于返回视图。虽然可能有使用它返回视图的方法,但从根本上说它是不正确的。

标签: java maven jsp model-view-controller spring-boot


【解决方案1】:

解决方案:

Step1:将@RestController 改为@Controller

Step2:对于您要返回视图的 URL(例如 greeting.jsp)

@RequestMapping("/greeting")
public String greeting() {
    return "greeting";
}

Step3:对于要返回 JSON 对象的 URL,没有视图(可能是 AJAX 调用)

@RequestMapping("/findAll")
@ResponseBody
public List<Journal> index() {
    List<Journal> all = journalService.findAll()
    return all;
}

或者这个

@RequestMapping("/findAll")
@ResponseBody
public Model index(Model model) {
    List<Journal> all =journalService.findAll();
    model.addAttribute("journalList", all);
    return model;
}

Step4:对于你想要的视图和模型的 URL(例如 java 对象)

参考 Rob Baily 示例代码

@RequestMapping("/findAll")
public String index(Model model) {
    List<Journal> all;
    all = journalService.findAll();
    model.addAttribute("journalList", all);
    return "listall";
}

您可以使用 ${journalList} 访问 listall.jsp 中的对象

说明: 当你在你的类上使用@RestController 时,它相当于为你的类中的每个方法添加@ResponseBody。因此,它将始终在页面上返回一个 object.toString(),而不是链接到您的 JSP。

此代码使用 Spring 4 的新 @RestController 注解,它将类标记为控制器,其中每个方法都返回域对象而不是视图。它是 @Controller 和 @ResponseBody 组合在一起的简写。 参考:https://spring.io/guides/gs/rest-service/

jsp示例参考:https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-jsp

【讨论】:

  • 感谢您的回答。我仍然有问题,因为它没有返回我希望的结果。是文件放置的问题吗?它们的组织方式如下:i63.tinypic.com/2by8g2.png
  • 嗨,蒂娜,我无法查看链接(我不知道为什么)。根据您的 application.properties 文件,您的 jsp 应该在 webapp/WEB-INF/jsp/{myPage}.jsp 中。如果访问 url:localhost:8080/greeting,它将寻找 WEB-INF/jsp/greeting.jsp。
【解决方案2】:

正如评论指出的那样,如果您想返回要呈现的视图,RestController 是不正确的。 RestController 以 JSON 形式返回对象,而不是用于 AJAX 请求的视图的 id。如果要返回视图,只需使用 Controller 注释即可。

您不需要视图,因为它应该将返回值路由到 JSP 页面。如果您想使用 JSP 标记,那么是的,您将需要一个模型,并且您需要将对象添加到您的模型对象中。请参见下面的示例。第一种方法应该去welcome.jsp 并且没有可用的模型。第二种方法应该转到 listall.jsp 并使 journalList 属性可用于 JSP 标记。

@Controller
 public class ApplicationController {
    @RequestMapping("/")
    public String index() {
        return "welcome";
    }

    @RequestMapping("/findAll")
    public String index(Model model) {
        List<Journal> all;
        all = journalService.findAll();
        model.addAttribute("journalList", all);
        return "listall";
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-28
    • 2018-12-01
    • 2018-02-11
    • 1970-01-01
    • 2017-06-26
    • 2020-04-13
    • 2018-02-23
    相关资源
    最近更新 更多