Spring 控制器 - Spring MVC 控制器

2023-11-04

Spring Controller 注解是一个特化@成分注解。 Spring Controller 注解通常与基于 RequestMapping 注解的带注解的处理程序方法结合使用。

弹簧控制器

Spring Controller 注解只能应用于类。它用于将类标记为 Web 请求处理程序。它主要与春季MVC应用。

Spring RestController

Spring @RestController是一个方便的注释,它本身注释为@控制器 and @ResponseBody。该注释用于将类标记为请求处理程序RESTful网页服务。

弹簧控制器示例

Let’s create a simple spring application where we will implement standard MVC controller as well as REST controller. Create a “Dynamic Web Project” in Eclipse and then convert it to Maven project. This will provide us with maven based web application structure and we can build our application on top of it. Below image shows the final project structure of our Spring MVC Controller application. Spring Controller Example Project We would need following dependencies for our application.

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

<!-- Jackson for REST -->
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.9.6</version>
</dependency>

让我们看看我们将在其中配置的部署描述符 (web.xml)DispatcherServletservlet作为前端控制器。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://xmlns.jcp.org/xml/ns/javaee" 
 xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Spring-Controller</display-name>
  <!-- Add Spring MVC DispatcherServlet as front controller -->
	<servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
       		<param-name>contextConfigLocation</param-name>
       		<param-value>/WEB-INF/spring-servlet.xml</param-value>
    		</init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern> 
    </servlet-mapping>
</web-app>

最后,我们有以下 spring 上下文文件。在这里,我们将应用程序配置为基于注释,并提供用于扫描 spring 组件的根包。我们也在配置InternalResourceViewResolverbean 并提供视图页面的详细信息。

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="https://www.springframework.org/schema/mvc"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:beans="https://www.springframework.org/schema/beans"
	xmlns:context="https://www.springframework.org/schema/context"
	xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<context:component-scan base-package="com.journaldev.spring" />

	<!-- Resolves views selected for rendering by @Controllers to JSP resources 
		in the /WEB-INF/views directory -->
	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

</beans:beans>

我们的配置 XML 文件已准备就绪,现在让我们转到 Controller 类。

package com.journaldev.spring.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

	@GetMapping("/hello")
	public String home(Locale locale, Model model) {
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		String formattedDate = dateFormat.format(date);
		model.addAttribute("serverTime", formattedDate);
		return "home";
	}

}

我们定义了一个请求处理程序方法,它接受带有 URI“/hello”的 GET 请求并返回“home.jsp”页面作为响应。请注意,我们正在为模型设置一个属性,该属性将在 home.jsp 页面中使用。这是我们简单的home.jsp页面代码。

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<html>
<head>
<title>Home</title>
</head>
<body>
	<h1>Hello world!</h1>

	<p>The time on the server is ${serverTime}.</p>

</body>
</html>

Spring MVC 控制器测试

Our conventional servlet based Spring MVC application with a simple controller is ready, just export it as the WAR file and deploy on Tomcat or any other servlet container. Then go to URL https://localhost:8080/Spring-Controller/hello and you should see the following screen as output. Spring Controller Example

Spring RestController 示例

现在让我们扩展我们的应用程序以公开 REST API。创建一个将作为 JSON 响应发送的模型类。

package com.journaldev.spring.model;

public class Person {

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}

这是我们简单的 REST Controller 类。

package com.journaldev.spring.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.journaldev.spring.model.Person;

@RestController
public class PersonRESTController {

	@RequestMapping("/rest")
	public String healthCheck() {
		return "OK";
	}

	@RequestMapping("/rest/person/get")
	public Person getPerson(@RequestParam(name = "name", required = false, defaultValue = "Unknown") String name) {
		Person person = new Person();
		person.setName(name);
		return person;
	}

}

再次重新部署应用程序以测试我们的 REST API。

Spring REST 控制器测试

Go to URL https://localhost:8080/Spring-Controller/rest and you should get following output. Spring MVC Controller Go to URL https://localhost:8080/Spring-Controller/rest/person/get and you will get following JSON response: Spring REST Controller Now let’s provide the name parameter value in the URL, go to https://localhost:8080/Spring-Controller/rest/person/get?name=Pankaj and you will get following JSON response. Spring REST Controller Example

Summary

Spring Controller 是 Spring MVC 应用程序的支柱。这是我们的业务逻辑开始的地方。此外,RestController 可以帮助我们轻松创建基于 Rest 的 Web 服务。

您可以从我们的下载示例项目代码GitHub 存储库.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring 控制器 - Spring MVC 控制器 的相关文章

随机推荐

  • Python 文件操作 - 使用 Python 读取和写入文件

    在本教程中 我们将研究 Python 中的不同文件操作 我们将介绍如何使用 Python 读取文件 写入文件 删除文件等等 所以 事不宜迟 让我们开始吧 在 Python 中处理文件 在之前的教程中 我们使用了控制台接受输入 现在 我们将使
  • 如何在 JavaScript 中编写条件语句

    介绍 在编程中 很多时候您会希望根据用户输入或其他因素运行不同的代码块 例如 如果每个字段都正确填写 您可能希望提交表单 但如果缺少某些必填字段 您可能希望阻止该表单提交 为了完成这样的任务 我们有条件语句 它们是所有编程语言的组成部分 条
  • 如何在 CentOS 7 上使用 Apache 作为带有 mod_proxy 的反向代理

    介绍 A 反向代理是一种代理服务器 它接受 HTTP S 请求并将其透明地分发到一个或多个后端服务器 反向代理非常有用 因为许多现代 Web 应用程序使用后端应用程序服务器处理传入的 HTTP 请求 这些服务器并不意味着用户可以直接访问 并
  • 如何在 Ubuntu 16.04 上安装和配置 Elasticsearch

    介绍 弹性搜索是一个实时分布式搜索和分析数据的平台 它的流行是由于它的易用性 强大的功能和可扩展性 Elasticsearch 支持 RESTful 操作 这意味着您可以将 HTTP 方法 GET POST PUT DELETE 等 与 H
  • 如何在 CentOS 7 上使用 Let's Encrypt 保护 Apache

    介绍 让我们加密是一个证书颁发机构 CA 为以下用户提供免费证书传输层安全 TLS 加密 从而在 Web 服务器上启用加密的 HTTPS 它通过提供可自动执行大部分步骤的软件客户端 简化了证书的创建 验证 签名 安装和续订过程 Certbo
  • 如何在 Ubuntu 12.04 LTS(精确穿山甲)上安装 nginx

    Status 已弃用 本文介绍不再受支持的 Ubuntu 版本 如果您当前运行的服务器运行 Ubuntu 12 04 我们强烈建议您升级或迁移到受支持的 Ubuntu 版本 升级到Ubuntu 14 04 从 Ubuntu 14 04 升级
  • R 中的 head() 和 tail() 函数 - 详细参考

    The R 中的 head 和 tail 函数通常用于读取数据集的前 n 行和后 n 行 您可能是一名在职专业人员 程序员或新手 但有时您需要阅读大型数据集并对其进行分析 消化一个拥有 20 多列甚至更多列 数千行的庞大数据集确实很困难 本
  • NoSQL 数据库管理系统和模型的比较

    介绍 当大多数人想到数据库时 他们通常会想到传统的关系数据库模型 其中涉及由行和列组成的表 虽然关系数据库管理系统仍然处理互联网上的大部分数据 但近年来 随着开发人员寻求解决关系模型局限性的方法 替代数据模型变得更加普遍 这些非关系数据库模
  • 理解 JavaScript 中的类

    介绍 JavaScript 是一种基于原型的语言 JavaScript 中的每个对象都有一个隐藏的内部属性 称为 Prototype 可用于扩展对象属性和方法 您可以在我们的文章中阅读有关原型的更多信息了解 JavaScript 中的原型和
  • 如何在角度测试中使用 Spies

    介绍 茉莉花间谍用于跟踪或存根函数或方法 间谍是一种检查函数是否被调用或提供自定义返回值的方法 我们可以使用间谍来测试依赖于服务的组件 并避免实际调用服务的方法来获取值 这有助于使我们的单元测试专注于测试组件本身的内部而不是其依赖项 在本文
  • Java 棘手面试问题

    不久前我写过一篇文章前 50 个 Java 编程问题 我们的读者非常喜欢它 所以今天我们将研究一些 Java 面试中棘手的问题 Java 棘手面试问题 这些都是编程问题 但除非您对 Java 有深入的了解 否则很难猜测输出并解释它 1 Nu
  • 了解 JavaScript 中的原型和继承

    介绍 JavaScript 是一个基于原型的语言 这意味着对象属性和方法可以通过具有克隆和扩展能力的通用对象来共享 这称为原型继承 与类继承不同 在流行的面向对象编程语言中 JavaScript 相对独特 因为 PHP Python 和 J
  • 如何在 Python 3 中使用列表方法

    介绍 Python 3 有许多内置数据结构 包括列表 数据结构为我们提供了一种组织和存储数据的方法 我们可以使用内置方法来检索或操作该数据 为了充分利用本教程 您应该熟悉列表数据类型 其语法及其索引方式 您可以通过阅读教程来查看列表理解 P
  • Mockito 教程

    Mockito 是一个基于 java 的模拟框架 与其他测试框架结合使用 例如JUnit and TestNG 它内部使用Java反射API 并允许创建服务对象 模拟对象返回虚拟数据并避免外部依赖 它通过模拟外部依赖项并将模拟应用到被测代码
  • Linux 中的存储术语和概念简介

    介绍 Linux 拥有强大的系统和工具来管理硬件设备 包括存储驱动器 在本文中 我们将从高层次上介绍 Linux 如何表示这些设备以及如何将原始存储转化为服务器上的可用空间 什么是块存储 块存储是 Linux 内核中块设备的另一个名称 A块
  • JPA EntityManager - Hibernate EntityManager

    JPA EntityManager 是 Java Persistence API 的核心 休眠是使用最广泛的 JPA 实现 JPA实体管理器 程序最重要的方面之一是与数据库的连接 数据库连接和与数据库的事务被认为是最昂贵的事务 ORM 在这
  • Apache Spark 示例:Java 中的字数统计程序

    阿帕奇火花 Apache Spark 是一个开源数据处理框架 可以在分布式环境中对大数据执行分析操作 这是加州大学伯克利分校的一个学术项目 最初由加州大学伯克利分校 AMPLab 的 Matei Zaharia 于 2009 年启动 Apa
  • 如何配置 NTP 以在 Ubuntu 16.04 上的 NTP 池项目中使用

    介绍 准确的计时对于几乎所有服务或软件都至关重要 电子邮件 记录器 事件系统和调度程序 用户身份验证机制以及在分布式平台上运行的服务都需要准确的时间戳来按时间顺序记录事件 这些服务使用网络时间协议 NTP 将系统时钟与可信的外部源同步 该源
  • 如何在 Ubuntu 16.04 上添加交换空间

    介绍 提高服务器响应能力和防止应用程序内存不足错误的最简单方法之一是添加一些交换空间 在本指南中 我们将介绍如何将交换文件添加到 Ubuntu 16 04 服务器 什么是互换 Swap是硬盘驱动器上的一个区域 被指定为操作系统可以临时存储
  • Spring 控制器 - Spring MVC 控制器

    Spring Controller 注解是一个特化 成分注解 Spring Controller 注解通常与基于 RequestMapping 注解的带注解的处理程序方法结合使用 弹簧控制器 Spring Controller 注解只能应用