java controller,Spring Controller – Spring MVC控制器

 2023-11-19 阅读 27 评论 0

摘要:Spring Controller annotation is a specialization of @Component annotation. Spring Controller annotation is typically used in combination with annotated handler methods based on the RequestMapping annotation. Spring Controller注釋是@Component注釋的

Spring Controller annotation is a specialization of @Component annotation. Spring Controller annotation is typically used in combination with annotated handler methods based on the RequestMapping annotation.

Spring Controller注釋是@Component注釋的特化。 Spring Controller注釋通常與基于RequestMapping注釋的注釋處理程序方法結合使用。

彈簧控制器 (Spring Controller)

Spring Controller annotation can be applied on classes only. It’s used to mark a class as a web request handler. It’s mostly used with Spring MVC application.

Spring Controller注釋只能應用于類。 它用于將一個類標記為Web請求處理程序。 它主要用于Spring MVC應用程序。

Spring RestController (Spring RestController)

Spring @RestController is a convenience annotation that is itself annotated with @Controller and @ResponseBody. This annotation is used to mark a class as request handler for RESTful web services.

Spring @RestController是一個方便注釋,它本身使用@Controller和@ResponseBody進行了注釋。 該注釋用于將類標記為RESTful Web服務的請求處理程序。

彈簧控制器實例 (Spring Controller Example)

Let’s create a simple spring application where we will implement standard MVC controller as well as REST controller.

讓我們創建一個簡單的spring應用程序,在其中我們將實現標準MVC控制器以及REST控制器。

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.

在Eclipse中創建一個“動態Web項目”,然后將其轉換為Maven項目。 這將為我們提供基于Maven的Web應用程序結構,并且我們可以在此基礎上構建應用程序。

Below image shows the final project structure of our Spring MVC Controller application.

下圖顯示了我們的Spring MVC Controller應用程序的最終項目結構。

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>

Let’s look at the deployment descriptor (web.xml) where we will configure DispatcherServlet servlet as the front controller.

讓我們看一下部署描述符(web.xml),在其中我們將DispatcherServlet servlet配置為前端控制器。

<?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>

Finally, we have following spring context file. Here we are configuring our application to be annotation-based and providing root package for scanning spring components. We are also configuring InternalResourceViewResolver bean and providing details of view pages.

最后,我們有以下Spring上下文文件。 在這里,我們將應用程序配置為基于注釋,并提供用于掃描spring組件的根包。 我們還將配置InternalResourceViewResolver bean并提供視圖頁面的詳細信息。

<?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.xsdhttps://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsdhttps://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:beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><beans:property name="prefix" value="/WEB-INF/views/" /><beans:property name="suffix" value=".jsp" /></beans:bean></beans:beans>

Our configuration XML files are ready, let’s move on to the Controller class now.

我們的配置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";}}

We have defined a single request handler method, it’s accepting GET requests with URI “/hello” and returning “home.jsp” page as the response. Notice that we are setting an attribute to the model, which will be used in the home.jsp page.

我們已經定義了一個請求處理程序方法,該方法接受URI為“ / hello”的GET請求并返回“ home.jsp”頁面作為響應。 注意,我們正在為模型設置一個屬性,該屬性將在home.jsp頁面中使用。

Here is our simple home.jsp page code.

這是我們簡單的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控制器測試 (Spring MVC Controller Test)

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.

我們具有簡單控制器的基于Servlet的常規Spring MVC應用程序已準備就緒,只需將其導出為WAR文件并部署在Tomcat或任何其他Servlet容器上即可。

Then go to URL https://localhost:8080/Spring-Controller/hello and you should see the following screen as output.

然后轉到URL https://localhost:8080/Spring-Controller/hello ,您應該看到以下屏幕作為輸出。

Spring RestController示例 (Spring RestController Example)

Now let’s extend our application to expose REST APIs too. Create a model class that will be sent as JSON response.

現在,讓我們擴展應用程序以公開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;}}

Here is our simple REST Controller class.

這是我們簡單的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;}}

Redeploy the application again to test our REST APIs.

再次重新部署應用程序以測試我們的REST API。

Spring REST控制器測試 (Spring REST Controller Test)

Go to URL https://localhost:8080/Spring-Controller/rest and you should get following output.

轉到URL https://localhost:8080/Spring-Controller/rest ,您應該獲得以下輸出。

Go to URL https://localhost:8080/Spring-Controller/rest/person/get and you will get following JSON response:

轉到URL https://localhost:8080/Spring-Controller/rest/person/get ,您將獲得以下JSON響應:

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.

現在讓我們在URL中提供名稱參數值,轉到https://localhost:8080/Spring-Controller/rest/person/get?name=Pankaj ,您將獲得以下JSON響應。

摘要 (Summary)

Spring Controller is the backbone of Spring MVC applications. This is where our business logic starts. Furthermore, RestController helps us in creating rest based web services easily.

Spring Controller是Spring MVC應用程序的基礎。 這是我們的業務邏輯開始的地方。 此外,RestController幫助我們輕松創建基于休息的Web服務。

GitHub Repository.GitHub Repository下載示例項目代碼。

翻譯自: https://www.journaldev.com/21515/spring-controller-spring-mvc-controller

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/183129.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息