加油,新时代打工人!
Spring MVC 响应数据和结果视图
目录结构
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/24b8d6c5ced6d7e100a8e0d551f85cd4.png)
pom.xml文件配置
<?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.itboy</groupId>
<artifactId>springmvc_day02_response</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>springmvc_day02_response Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!--版本锁定 也方便修改-->
<spring.version>5.0.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<finalName>springmvc_day01_start</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
UserController
package com.itboy.controller;
import com.itboy.domin.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author wh
* @date 2021年11月13日16:43
*/
@RequestMapping("/user")
@Controller
public class UserController {
@RequestMapping("/teststring")
public String testString(Model model){
User user=new User();
user.setUsername("小明");
user.setPassword("123456");
model.addAttribute("user",user);
return "success";
}
/**
* 请求转发执行一次
*/
@RequestMapping("/testvoid")
public void testVoid(HttpServletRequest request,HttpServletResponse response) throws Exception{
System.out.println("testVoid方法执行了");
// 请求转发执行一次
// request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
//重定向
// response.sendRedirect(request.getContextPath()+"/index.jsp");
//解决中文乱码
response.setCharacterEncoding("UTF-8");
response.setContentType("text/http;charset=utf-8");
//服务器直接响应给客户端
response.getWriter().print("你好,世界");
return;
}
/**
* 和model方法类似
* @return
*/
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
ModelAndView mv= new ModelAndView();
User user=new User();
user.setUsername("小明");
user.setPassword("123456");
//将user对象存入到model对象中,把user对象存入到request对象
mv.addObject("user",user);
//视图调整到哪个对象
mv.setViewName("success");
return mv;
}
@RequestMapping("/testForwordorRedirect")
public String testForwordorRedirect(){
System.out.println("testForwordorRedirect方法执行了");
//forword转发一次执行
// return "forward:/WEB-INF/pages/success.jsp";
//redirect重定向
return "redirect:/index.jsp";
}
//模拟异步请求1
@RequestMapping("/testJson")
public void testJson(@RequestBody String body){
System.out.println(body);
}
//异步请求响应对象2
@RequestMapping("/testAjax")
public @ResponseBody User testJson(@RequestBody User user) {
//前端发送的是ajax请求,传的是json,后端把json字符封装到user对象中
System.out.println(user);
//修改前端username
user.setUsername("小华");
return user;
}
}
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="com.itboy"></context:component-scan>
<!--视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 设置静态资源不过滤 -->
<!--1. location元素表示webapp目录下的包下的所有文件-->
<!--2. mapping元素表示以/static开头的所有请求路径,如/static/a 或者/static/a/b-->
<mvc:resources location="/css/" mapping="/css/**"/> <!-- 样式 -->
<mvc:resources location="/images/" mapping="/images/**"/> <!-- 图片 -->
<mvc:resources location="/js/" mapping="/js/**"/> <!-- javascript -->
<!--开启注解支持-->
<mvc:annotation-driven ></mvc:annotation-driven>
</beans>
response.jsp
<%--
Created by IntelliJ IDEA.
User: 儒雅
Date: 2021/11/13
Time: 16:56
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
$(function () {
$("#btn").click(function () {
// alert("hello world");
$.ajax({
url:"user/testAjax",
contentType:"application/json;charset=utf-8",
data:'{"username":"小明","password":"1223"}',
type:"post",
success:function(data){
alert(data);
alert(data.username);
alert(data.password);
}
});
});
});
</script>
</head>
<body>
<h3>Spring MVC响应方式</h3>
<a href="user/teststring">teststring</a><hr/>
<a href="user/testvoid">testvoid</a><hr/>
<a href="user/testModelAndView">testModelAndView</a><hr/>
<a href="user/testForwordorRedirect">testForwordorRedirect</a><hr/>
<button id="btn">测试json</button>
</body>
</html>