44.md 8.8 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4
# Spring Jetty 教程

> 原文: [http://zetcode.com/spring/jetty/](http://zetcode.com/spring/jetty/)

W
wizardforcel 已提交
5
Spring Jetty 教程显示了如何在 Jetty Web 服务器上运行 Spring Web 应用。
W
wizardforcel 已提交
6

W
wizardforcel 已提交
7
Spring 是用于创建企业应用的流行 Java 应用框架。
W
wizardforcel 已提交
8

W
wizardforcel 已提交
9
## Jetty
W
wizardforcel 已提交
10 11 12

Jetty Web 服务器是一个 HTTP 服务器和 Servlet 容器,能够通过独立或嵌入式实例提供静态和动态内容。

W
wizardforcel 已提交
13
## Spring Jetty 的例子
W
wizardforcel 已提交
14

W
wizardforcel 已提交
15
在以下示例中,我们创建一个简单的 Spring Web 应用并将其部署在 Jetty Web 服务器上。 为此,我们使用`jetty-maven-plugin`
W
wizardforcel 已提交
16

W
wizardforcel 已提交
17
该应用显示几个英语单词。
W
wizardforcel 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

```java
pom.xml
src
├───main
   ├───java
      └───com
          └───zetcode
              ├───config
                     MyWebInitializer.java
                     WebConfig.java
              └───controller
                      MyController.java
   └───resources
          logback.xml
       └───templates
               index.html
└───test
    └───java

```

这是项目结构。

`pom.xml`

```java
<?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>com.zetcode</groupId>
    <artifactId>SpringJettyEx</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <spring-version>5.1.3.RELEASE</spring-version>
        <thymeleaf-version>3.0.11.RELEASE</thymeleaf-version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>${thymeleaf-version}</version>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>${thymeleaf-version}</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
            </plugin>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.14.v20181114</version>
            </plugin>
        </plugins>
    </build>
</project>

```

`pom.xml`中,我们具有项目依赖项。

```java
<plugin>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-maven-plugin</artifactId>
    <version>9.4.14.v20181114</version>
</plugin>

```

`jetty-maven-plugin`允许我们使用`mvn jetty:run`运行嵌入式 Jetty 服务器。

`resources/logback.xml`

```java
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <logger name="org.springframework" level="ERROR"/>
    <logger name="com.zetcode" level="INFO"/>

    <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n
            </Pattern>
        </encoder>
    </appender>

    <root>
        <level value="INFO" />
        <appender-ref ref="consoleAppender" />
    </root>
</configuration>

```

这是`logback.xml`配置

`com/zetcode/config/MyWebInitializer.java`

```java
package com.zetcode.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.FrameworkServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

@Configuration
public class MyWebInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {

        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {

        return new String[]{"/"};
    }
}

```

W
wizardforcel 已提交
192
`MyWebInitializer`初始化 Spring Web 应用。 它包含一个配置类:`WebConfig`
W
wizardforcel 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329

`com/zetcode/config/WebConfig.java`

```java
package com.zetcode.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.zetcode"})
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public SpringResourceTemplateResolver templateResolver() {

        var templateResolver = new SpringResourceTemplateResolver();

        templateResolver.setApplicationContext(applicationContext);
        templateResolver.setPrefix("classpath:/templates/");
        templateResolver.setSuffix(".html");

        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {

        var templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);

        return templateEngine;
    }

    @Bean
    public ViewResolver viewResolver() {

        var resolver = new ThymeleafViewResolver();
        var registry = new ViewResolverRegistry(null, applicationContext);

        resolver.setTemplateEngine(templateEngine());
        registry.viewResolver(resolver);

        return resolver;
    }
}

```

`WebConfig`配置 Thymeleaf 模板引擎。

`com/zetcode/controller/MyController.java`

```java
package com.zetcode.controller;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;

@Controller
public class MyController {

    @GetMapping(value = "/", produces = MediaType.TEXT_HTML_VALUE)
    public String home(Model model) {

        var words = List.of("mountain", "noon", "rock", "river", "spring");

        model.addAttribute("words", words);

        return "index";
    }
}

```

`MyController`包含主页的一种路由。 我们向模板发送一些数据。 数据将显示在 HTML 表中。

`resources/templates/index.html`

```java
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Home page</title>
</head>
<body>

<h2>English words</h2>

<table">
    <thead>
    <tr>
        <th>Index</th>
        <th>Word</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="word : ${words}">
        <td th:text="${wordStat.index + 1}">Index</td>
        <td th:text="${word}">A word</td>
    </tr>
    </tbody>
</table>

</body>
</html>

```

这是主页。

```java
$ mvn jetty:run    

```

我们运行 Jetty 服务器。 我们导航到`localhost:8080`以获取主页。

W
wizardforcel 已提交
330
在本教程中,我们创建了一个 Spring Web 应用并将其部署在嵌入式 Jetty 服务器上。
W
wizardforcel 已提交
331

W
wizardforcel 已提交
332
您可能也对这些相关教程感兴趣: [Spring WebJars 教程](/spring/webjars/)[Spring DefaultServlet 教程](/spring/defaultservlet/)[Spring Web 应用简介](/articles/springwebfirst/)[Java 教程](/lang/java/)