新建com.example.controller.ResponseController
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author Administrator
*/
@Controller
public class ResponseController {
@RequestMapping("/toPage")
public String toPage() {
System.out.println("toPage");
return "test.jsp";
}
}
新建src/main/webapp/test.jsp文件
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2024/1/30
Time: 17:50
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Test</title>
</head>
<body>
hello Spring MVC!!!!
</body>
</html>
启动测试
返回的是一个页面
添加代码
@RequestMapping("/toText")
@ResponseBody
public String toText() {
System.out.println("toText");
return "test.jsp";
}
启动测试
返回的是一个文本,这是因为加了@ResposeBody这个注解,对返回值不做解析操作,不加会把返回结果当作一个页面来解析。
添加代码
@RequestMapping("/toJson")
@ResponseBody
public User toJson(){
User user = new User();
user.setName("张三");
user.setAge(18);
System.out.println("toJson");
return user;
}
启动测试
返回的是json形式的字符串