SpringMVC的请求和响应

本文详细介绍了SpringMVC中的控制器功能,包括数据响应的多种方式(字符串、ModelAndView、JSON),页面跳转的配置,以及如何处理请求参数、文件上传、自定义转换器等,帮助理解SpringMVC的工作原理。
摘要由CSDN通过智能技术生成

@Controller注解是让spring找到这个这个对象
@RequestMapping("/名字") 这个是在输入地址的时候要加上 /名字/… 才能访问

SpringMVC的数据响应

页面跳转

返回字符串

直接返回字符串
    public String save(){
        System.out.println("Controller save running....");
        return "success";
    }

在springmvc.xml配置文件里面配置了前缀后缀所以只需要输入文件名就能跳转到正确的位置

 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--  /jsp/success.jsp  -->
        <property name="prefix" value="/jsp/"></property>
        给直接返回字符串的前面加上/jsp/
        <property name="suffix" value=".jsp"></property>
        给直接返回字符串的后面加上 .jsp
    </bean>

因为视图解析器的配置 最后它跳转到了 …/jsp/success.jsp 这个网页里面

返回ModelAndView对象
    public ModelAndView save1(){
        System.out.println("modelandview Controller save running....");
         ModelAndView modelAndView = new ModelAndView();
         modelAndView.setViewName("success");
         //setviewname是设置你要跳转到那 
        //success前面可以加前缀 forward:是转发
       //  redirect: 是重定向
         
         modelAndView.addObject("username","itcast");
			//这是设置你要存的数据
         return modelAndView;
    } 

向request域存储数据

通过request对象setAttribute()方法设置
@RequestMapping("/quick")
public String quickMethod(HttpServletRequest request){
request.setAttribute("name","zhangsan");
return "index";
}
通过ModelAndView的addObject()方法设置
@RequestMapping("/quick3")
public ModelAndView quickMethod3(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("forward:/WEB-INF/views/index.jsp");
modelAndView.addObject("name","lisi");
return modelAndView;
}

回写数据

通过response对象
@RequestMapping("/quick4")
public void quickMethod4(HttpServletResponse response) throws 
IOException {
response.getWriter().print("hello world");
}
直接返回字符串

需要通过@ResponseBody注解告知SpringMVC框架,方法返回的字符串不是跳转是直接在http响应体中返回。

@RequestMapping("/quick5")
@ResponseBody //因为有这个注释所以springmvc把下面返回的字符串直接写出了

public String quickMethod5() throws IOException {
return "hello springMVC!!!";
}
返回json样式
 @RequestMapping("/quick6")
    @ResponseBody
    public String save6() throws JsonProcessingException {
        User user = new User();
        user.setAge(30);
        user.setName("alibb");
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(user);
        return json;
    }

获取请求数据

返回对象

需要在springMVC里面配置

<bean class="org.springframework.web.servlet.mvc.method.annotation
.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json
.MappingJackson2HttpMessageConverter">
</bean>
</list>
</property>
</bean>

还需要加入注解驱动
<mvc:annotation-driven/>

直接将user对象输出到页面上 user里面有tostring方法

//返回对象
@RequestMapping("/quick7")
    @ResponseBody
    public User save7() {
        User user = new User();
        user.setAge(30);
        user.setName("alibb");
        return user;
    }

在这里插入图片描述

回写数据
@RequestMapping("/quick8")
    @ResponseBody
    public void save8(String name,int age) {
        System.out.println(name);
        System.out.println(age);
    }

在这里插入图片描述
在这里插入图片描述

获得POJO(一个普通的对象)类型参数

Controller中的业务方法的POJO参数的属性名与请求参数的name一致,参数值会自动映射匹配。

http://localhost:8080/itheima_springmvc1/quick9?username=zhangsan&age=12
public class User {
private String username;
private int age;
getter/setter…
}
@RequestMapping("/quick10")
@ResponseBody
public void quickMethod10(User user) throws IOException {
System.out.println(user);
}
获取集合类型参数

如果客户端传入一个集合的时候不能直接传到方法里面 需要把它包装成一个对象才能放进去
比如

<form action="${pageContext.request.contextPath}/quick12" method="post">
<input type="text" name="userList[0].username"><br>
<input type="text" name="userList[0].age"><br>
<input type="text" name="userList[1].username"><br>
<input type="text" name="userList[1].age"><br>
<input type="submit" value="提交"><br>
</form>

包装对象如下

package com.itheima.domain;

import java.util.List;

public class VO {
    private List<User> userList;

    @Override
    public String toString() {
        return "VO{" +
                "userList=" + userList +
                '}';
    }

    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }
}

@RequestMapping("/quick12")
@ResponseBody
public void quickMethod12(Vo vo) throws IOException {
System.out.println(vo.getUserList());
}

也可以在jsp文件里面通过ajax直接给包装成json形式
然后在springmvc方法里面的参数位置加入@RequestBody就可以了

<%--
  Created by IntelliJ IDEA.
  User: hp
  Date: 2021/12/7
  Time: 20:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--<%@ page isELIgnored="false" %>--%>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
    //这个引入我真的是要吐了一直说找不到jquery 我找了好久错误没找到我重启一下idea就能找到这个jquery文件了

    <script>
        var userList = new Array();
        userList.push({name:"张三",age:18});
        userList.push({name:"lisi",age:28});

        $.ajax({
            type:"POST",
            url:"${pageContext.request.contextPath}/user/quick11",
            data:JSON.stringify(userList),
            contentType:"application/json;charset=utf-8"
        });

    </script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
  @RequestMapping("/quick11")
    @ResponseBody
    public void quickMethod13(@RequestBody List<User> userList) throws
            IOException {
        System.out.println(userList);
    }
参数绑定注解@requestParam

当请求的参数名称与Controller的业务方法参数名称不一致时,就需要通过@RequestParam注解显示的绑定。

<form action="${pageContext.request.contextPath}/quick14" method="post">
<input type="text" name="name"><br>
<input type="submit" value="提交"><br>
</form>
@RequestMapping("/quick14")
@ResponseBody
public void quickMethod14(@RequestParam("name") String username) throws 
IOException {
//通过这个注释下面就不用再用name了
//可以用spring的username
System.out.println(username);
}

value:与请求参数名称
required:此在指定的请求参数是否必须包括,默认是true,提交时如果没有此参数则报错
defaultValue:当没有指定请求参数时,则使用指定的默认值赋值

@RequestMapping("/quick14")
@ResponseBody
public void quickMethod14(@RequestParam(value="name",required = 
false,defaultValue = "itcast") String username) throws IOException {
//上面的注释的意思是name这个可以不填 不填的话它的默认值是itcast
System.out.println(username);
}
获得Restful风格的参数 (不用写?username=这种)
@RequestMapping("/quick13/{name}")
    @ResponseBody
    public void quick13(@RequestBody @PathVariable("name")  String name) throws
            Exception {
        System.out.println(name);
    }

这种的话需要的访问是
http://localhost:8080/itheima_spring_mvc_war/user/quick13/aaa
这样aaa就被当作name传入进去了

自定义类型转换器
<bean id="converterService" 
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.itheima.converter.DateConverter"/>
</list>
</property>
</bean>

引入转换器

<mvc:annotation-driven conversion-service="converterService"/>
获得Servlet相关API

SpringMVC支持使用原始ServletAPI对象作为控制器方法的参数进行注入,常用的对象如下:
HttpServletRequest
HttpServletResponse
HttpSession

@RequestMapping("/quick15")
    @ResponseBody
    public void quick15(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, HttpSession httpSession) throws
            Exception {
        System.out.println(httpServletResponse);
        System.out.println(httpServletResponse);
        System.out.println(httpSession);
    }

获得请求头

@RequestHeade
@RequestMapping("/quick17")
@ResponseBody
public void quickMethod17(
@RequestHeader(value = "User-Agent",required = false) String 
headerValue){
//value:请求头的名称
// required:是否必须携带此请求头
System.out.println(headerValue);
}
@CookieValue

@CookieValue注解的属性如下:
value:指定cookie的名称
required:是否必须携带此cookie

@RequestMapping("/quick18")
@ResponseBody
public void quickMethod18(
@CookieValue(value = "JSESSIONID",required = false) String jsessionid){
System.out.println(jsessionid);
}

文件上传

文件上传客户端三要素

1.表单项type=“file”
2.表单的提交方式是post
3.表单的enctype属性是多部分表单形式,及enctype=“multipart/form-data”

<form action="${pageContext.request.contextPath}/user/quick17" method="post" enctype="multipart/form-data">
  .......
</form>

文件上传步骤

  1. 导入fileupload和io坐标
  2. 配置文件上传解析器
  3. 编写文件上传代码
导入fileupload和io坐标
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
配置文件上传解析器
<bean id="multipartResolver" 
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上传文件总大小-->
<property name="maxUploadSize" value="5242800"/>
<!--上传单个文件的大小-->
<property name="maxUploadSizePerFile" value="5242800"/>
<!--上传文件的编码类型-->
<property name="defaultEncoding" value="UTF-8"/>
</bean>
单文件上传实现
<form action="${pageContext.request.contextPath}/user/quick17" method="post" enctype="multipart/form-data">
    名称<input type="text" name="username"><br>
    文件<input type="file" name="uploadFile"><br>
    <input type="submit" value="提交按钮">

</form>
 @RequestMapping("/quick17")
    @ResponseBody
    public void quick17(String username, MultipartFile uploadFile) throws
            Exception {
        System.out.println(username);
        System.out.println(uploadFile);
        String name = uploadFile.getOriginalFilename();
        uploadFile.transferTo(new File("C:\\Users\\hp\\Desktop\\t1\\"+name+".txt"));
    }
多文件上传实现
<form action="${pageContext.request.contextPath}/quick21" method="post" 
enctype="multipart/form-data">
名称:<input type="text" name="name"><br>
文件1:<input type="file" name="uploadFiles"><br>
文件2:<input type="file" name="uploadFiles"><br>
文件3:<input type="file" name="uploadFiles"><br>
<input type="submit" value="提交"><br>
</form>

跟单文件输入也差不多

@RequestMapping("/quick21")
@ResponseBody
public void quickMethod21(String name,MultipartFile[] uploadFiles) throws 
IOException {
for (MultipartFile uploadFile : uploadFiles){
String originalFilename = uploadFile.getOriginalFilename();
uploadFile.transferTo(new File("C:\\upload\\"+originalFilename));
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值