springMVC-model data processing

 1. Put the data into the request field

1. Put the obtained data into the request field to facilitate display on the jump page. 

<a>添加主人信息</a>
<form action="vote/vote04" method="post" >
    主人id:<input type="text" name="id"><br>
    主人名:<input type="text" name="monsterName"><br>
    宠物名:<input type="text" name="pet.petName"><br>
    <input type="submit" value="提交" ><br>
   @RequestMapping(value = "/vote04")
    public String vote04(Monster monster, HttpServletRequest request,
                         HttpServletResponse response){
        System.out.println("请求到vote04");
        request.setAttribute("monster", monster);
        request.setAttribute("address","湖州");
        return "voteOK";
    }
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>获取参数成功

    地址:   ${address}<br>
    主人名字:${requestScope.monster.monsterName}<br>
    主人信息:${requestScope.monster}<br>
</body>
</html>

2. Through the requested method parameter Map<String,Object>, springMVC automatically puts the content of the map parameter into the reguest domain.

<%--确保这里的name与bean的属性名一致,否则拿不到值--%>
<a>添加主人信息</a>
<form action="vote/vote05" method="post" >
    主人id:<input type="text" name="id"><br>
    主人名:<input type="text" name="monsterName"><br>
    宠物名:<input type="text" name="pet.petName"><br>
    <input type="submit" value="提交" ><br>
</form>
   @RequestMapping(value = "/vote05")
    public String vote05(Monster monster, Map <String,Object> map){
        map.put("monster", monster);
        map.put("Address", "BEIJING");
        return "voteOK";
    }
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>获取参数成功

    地址:   ${address}<br>
    主人名字:${requestScope.monster.monsterName}<br>
    主人信息:${requestScope.monster}<br>

3. Implement request field data by returning a ModelAndView object

1>In essence, the request response method returns "xx", which seems to return a string. In fact, it essentially returns a ModeIAndView object, but it is encapsulated by default.

2>ModelAndView can contain both model data and view information.
3>The addObject method of the ModelAndView object can add key-val data. The default is in the request field. 4>The setView method of the ModelAndView object can specify the view name.

<%--确保这里的name与bean的属性名一致,否则拿不到值--%>
<a>添加主人信息</a>
<form action="vote/vote06" method="post" >
    主人id:<input type="text" name="id"><br>
    主人名:<input type="text" name="monsterName"><br>
    宠物名:<input type="text" name="pet.petName"><br>
    <input type="submit" value="提交" ><br>
</form>
  @RequestMapping(value = "/vote06")
    public ModelAndView vote06(Monster monster){
        //创建一个modleANDView
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("monster", monster);
        modelAndView.addObject("address", "杭州");
        modelAndView.setViewName("voteOK");
        return modelAndView;
    }
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>获取参数成功

    地址:   ${address}<br>
    主人名字:${requestScope.monster.monsterName}<br>
    主人信息:${requestScope.monster}<br>
</body>

2. Put the data into the session field

1. Put data into the session domain through @SessionAttributes

First, write a @SessionAttributes annotation on the handler

@SessionAttributes(value = "myMaster")
@RequestMapping(value = "/vote")
@Controller
public class VoteHandler {
   
   

As long as there is a map parameter, the put method is called, and the key value is the same as @SessionAttributes, it will be automatically placed in the session domain. 

@RequestMapping(value = "/vote07")
    public String vote07(Map <String,Object> map,Monster monster){
       map.put("myMonster",monster);
       map.put("address","SHANGHAI");
        return "voteOK";
    }
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>获取参数成功

    地址:   ${address}<br>
    主人名字:${requestScope.monster.monsterName}<br>
    主人信息:${requestScope.monster}<br>

    主人名字(session):${sessionScope.myMonter.monsterName}<br>
    主人信息(session):${sessionScope.myMonter}<br>

</body>

3. Implement the prepare method through @ModelAttribute

summary

Note that when we add the annotation @ModelAttribue before a method of Handler, the method will be called before any target method, so that programmers can prepare the corresponding model and do preprocessing before calling the target method. .

1. What is the prepare method?

@ModelAttribute is modified by this method,
    // will be called before all methods of this handler are called.

public class VoteHandler {
    @ModelAttribute //@ModelAttribute 被这个方法修饰,
    // 会在该handler的所有方法被调用前,去调用
    public void testPrepare(){
        System.out.println("preparing......");
    }
 @RequestMapping(value = "/vote08")
    public String vote08(){
        System.out.println("update......");
        return "voteOK";
    }
<a href="vote/vote08">测试prepare</a>

 

2. @ModelAttribute best practices

Overview of the case:

When doing the update operation, we only submit the number and name, so the backend also needs to determine which fields were submitted by the frontend, and it is troublesome to update them. So the following case appeared. Preprocessing is done before the update operation.

Let’s take a look at the schematic diagram first and see if you remember it.

<body>
<a href="vote/vote08">测试prepare</a>

<h1>修改人员</h1>
<form action="person/person01" method="POST">
<%--    为了让handler获取到id,将id值藏入隐藏域--%>
    <input type="hidden" name="id" value="100">
<%--    指定我们的请求方式,让HiddenHttpMethodFilter转换--%>
    <input type="hidden" name="_method" value="PUT">
    编号:<input type="text" disabled="disabled" name="id" value="100"><br>
    名字:<input type="text" name="name" ><br>
    <input type="submit" value="点击修改">

</body>

@RequestMapping(value = "/person")
@Scope(value = "prototype")
@Controller
public class PersonHandler {
    @ModelAttribute
    public void personPre(@RequestParam(value = "id" ,required= false)
                         Integer id, Map<String,Object> map){
        //获取到要修改的person的id
        if(id != null){
            //然后通过id到数据库去查找对应的person
            //假定我们从数据库中获取到这个id = 100 的person
            Person person = new Person();
            person.setId(100);
            person.setName("jkl");
            person.setAddress("china");
            //把这个person放入到mapzhong ,注意名字,一定要和目标方法的javabean的
            // @ModelAttribute中的名字一样!!!!!!!
            map.put("person",person);
            System.out.println("hashCode1 = "+person.hashCode());

            //然后给updatePerson
        }
    }

    /***1.在当目标方法的参数中有一个和页面对应的javabean信息时,
     *    springMVC就会将jsp提交的数据封装到目标方法的javabean(person)中
     *2.并将javabean对象放入到request域。
     *3.在默认情况下,放入到request域中的javabean对象的属性是该Javabean的类名首字母***小写的Person person2,
     *   即这里的Person类名的person
     *4.其实,如果你的目标方法有一个javabean对象,那么该java对象前,默认会有*@ModelAttribute(value="person")
     *即public String updatePerson(Person person2)等价
     * public String updatePerson(@ModelAttribute(value="person") Person person2)
     *5.如果我们改变默认放在request域中的javabean的属性名,则可以直接修改
     *@ModelAttribute(value="person")的值@ModelAttribute(value="myperson")
     */
    @RequestMapping(value = "/person01",method = RequestMethod.PUT)
    public String updatePerson(Person person) {
        System.out.println("person01 = "+person);
        System.out.println("hashCode2 = "+person.hashCode());
        return "personOK";
    }
}

 Console output, please note that hashCode1 = hashCode2 (please see the schematic to fully understand)

<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true"
isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
    personid: ${requestScope.person.id} <br>
    personname:${requestScope.person.name}<br>
    personAddress:${requestScope.person.address}<br>
</head>
<body>

 4. The process of obtaining javaBean by the target method

Precautions for use (test points):
5. The actual process of obtaining the javabean object by the target method is
(1). First obtain the corresponding from the implicit Map (similar to the value stack in Struts2, that is, the Map is created before the method call) Object. If there is, return the target parameter
(2) passed to the target method. If not, check whether it needs to be obtained from the Session. If necessary, obtain it from the Session. If there is one in the Session, return directly. If If not, an exception will be thrown.
(3) If there is no need to obtain it from the Session and it is not in the Map, create the object directly through reflection and put it into the map (that is, in the request field)
(4) Put the form The parameters are projected to the corresponding attributes of the bean, so that these data can also be used on the jsp page.

Guess you like

Origin blog.csdn.net/qq_36684207/article/details/135026297