簡體   English   中英

使用Maven構建Spring Boot項目

[英]Building a Spring Boot project using Maven

更新:

謝謝大家的回答。 我仍然有問題,因為它沒有返回我希望的結果。 這是文件放置的問題嗎? 它們的組織方式如下: 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是不正確的。 RestController將對象作為JSON返回,而不是用於AJAX請求的視圖的ID。 如果要返回視圖,只需使用Controller批注。

您不需要View,因為它會將返回值路由到JSP頁面。 如果要使用JSP標記,則是的,您將需要一個Model,並且需要將對象添加到Model對象。 請參見下面的示例。 第一種方法應轉到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";
    }
}

解:

步驟1:將@RestController更改為@Controller

第2步:獲取要返回視圖的URL(例如greeting.jsp)

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

第3步:對於要返回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;
}

第4步:獲取您想要視圖和模型的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM