Java教程

@RequestAttribute 注解

本文主要是介绍@RequestAttribute 注解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

@RequestAttribute 注解

@RequestAttribute

该注解可以将request中的值直接赋值给方法中的参数

controller层

package com.xiang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by IntelliJ IDEA.
 * User: xiang
 * Date: 2021/10/13 23:54
 */
@Controller
public class RequestAttributeController {
    /**
     * HttpServletRequest
     * @param request
     * @return
     */
    @RequestMapping("/fo1")
    public String fo1(HttpServletRequest request) {
//       在 request 中存储数据
        request.setAttribute("id", 001);
        request.setAttribute("name", "xiang");
        request.setAttribute("password", "***");
        request.setAttribute("age", 18);
        request.setAttribute("gender", "男");
//        转发到另一个 controller 中
        return "forward:/fo2";
    }

    /**
     * @param request
     * @param id
     * @param name
     * @param password
     * @param age
     * @param gender
     * @return
     * @RequestAttribute("a") 该注解可以将request中的值直接赋值给方法中的参数
     */
    @ResponseBody
    @RequestMapping("/fo2")
    public Object fo2(HttpServletRequest request,
                      @RequestAttribute("id") Integer id,
                      @RequestAttribute("name") String name,
                      @RequestAttribute("password") String password,
                      @RequestAttribute("age") Integer age,
                      @RequestAttribute("gender") String gender) {
        HashMap<Object, Object> map = new HashMap<>();
//        从 request 中获取数据
        Object id1 = request.getAttribute("id");
        Object name1 = request.getAttribute("name");
        Object password1 = request.getAttribute("password");
        Object age1 = request.getAttribute("age");
        Object gender1 = request.getAttribute("gender");

        ArrayList<Object> list = new ArrayList<>();
        list.add(id1);
        list.add(name1);
        list.add(password1);
        list.add(age1);
        list.add(gender1);
//        return list;
//        在 map 中添加数据
        map.put("id", 001);
        map.put("name", "xiangxiang");
        map.put("password", "******");
        map.put("age", 20);
        map.put("gender", "女");

        System.out.println(list);
        System.out.println(map);
//        return map;

        ArrayList<Object> arrayList = new ArrayList<>();
        arrayList.add(list);
        arrayList.add(map);
        return arrayList;
    }
}

运行结果

这篇关于@RequestAttribute 注解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!