Spring Controller – Spring MVC控制器

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值