SpringMVC Spring family bucket of (c)

    Spring MVC single data received form submission

     Single received parameters form submission  

    In the actual development through parameters receive the form in the spring MVC's Controller submitted over inside, this block of code that how to write it?

    Example:

    Written with a form of jsp (I directly here index.jsp):

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/regist1.do" method="post">
    姓名:<input type="text" name="username"><br>
    年龄:<input type="text" name="age"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

    After creating a controller to receive the value of form submission:   

package controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloSpringMVC {
    @RequestMapping("/regist1.do")
    public ModelAndView regist1(String username,int age){
        ModelAndView mv = new ModelAndView();
        mv.addObject("username",username);
        mv.addObject("age",age);
        mv.setViewName("test");
        return mv;
    }
}

    Then create a jump page test.jsp   

<%@ page language="java" contentType="text/html; charset=utf-8"
         pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Insert title here</title>
</head>
<body>
    用户名:${username}
    <br>
    年龄:${age}
</body>
</html>

    In the above controller, we are in the parameter list behind regist1 method written on two parameters username and Age , two parameters on the controller methods must be consistent with the name of the form input , this spring MVC will automatically assign a value , you can get the form of price increases by the data controller in this way.

    Here we analyze the flow parameters submitted by the form:

    First, then index.jsp page <input> input data after clicking the submit button, the form will jump to the action specified url, we have two parameters on the controller method to receive the corresponding data (respectively index.jsp in input the name attribute tag parameters must be the same as the method parameter names on the controller, otherwise the controller can not process the received data ). After receiving us again by addObject ModelAndView () method and the age received from the reception username test.jsp transmitted to the properties, so that we can input the data transmitted to the controller test.jsp index.jsp by the page request.

    The whole process needs two points to note:

    1, input tag name attribute name to be consistent with the controller method parameter names

    2, form Form action attribute corresponds to the controller RequestMapping, if not corresponding to the jump. 

    At this point you may find that a problem, method parameters before we write the controller in the list which we have written on the request and response, and there is not in writing, in fact, this will not affect spring mvc, that in controller methods inside, we can write multiple parameters, you can not write a, but will automatically spring mvc automatically assigned to the following five parameters :

  • HttpServletRequest
  • HttpServletResponse
  • HttpSession
  • Request parameters carried
  • Model for carrying data

The current example is actually spring mvc will request carries parameter assignment, this way I can get a form submission data directly. Other later in the presentation.    

    Acquisition request parameter garbled

    In the above example, if you enter the Chinese, it is likely garbled problem, we can use CharacterEncodingFilter spring MVC for developers to solve the garbage problem, this is actually a filter. We need to be arranged in the web.xml file, which is preferably disposed before the other filters because the filter is performed in the order web.xml:    

<! - character encoding Filter -> 
<filter> 
    <filter-name> characterEncodingFilter </ filter-name> 
    <filter- class > org.springframework.web.filter.CharacterEncodingFilter </ filter- class > 

    <! - specifies the character encoding -> 
    <the init-param> 
        <param-name> encoding </ param-name> 
        <param-value>. 8 UTF-</ param-value> 
    </ the init-param> 

    <-! enforce the character coding, i.e., if the request specifies a character encoding, then the character will enforce the encoding for the current settings -> 
    <the init-param> 
        <param-name> forceEncoding </ param-name> 
        <param-value> to true </ param-value> 
    </ the init-param> 

</ filter>
<filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

    Here you can see forceEncoding If set to true, then the source code by springmvc So whether you set the character encoding in the request, spring mvc will force its character encoding is set to write in our web.xml file character encoding.

   Inconsistencies parameter name    

    Inconsistencies parameter name

      There in the actual development may have this problem, is the name of the parameter name and spring mvc form input method in the inconsistent, then you can use @RequestParam annotation to solve this problem, this annotation has three attributes:

  • value : name of the parameter specifies the request, i.e., a form input value of the name.
  • name : the same value, both only use one
  • required : must specify whether the parameter is passed, boolean type. If it is true, the parameter carried in the request must contain the current parameter. If it is false, it indicates that there can be.
  • defaultValue : Specifies the current default value of the parameter. If the request is not the argument, the current method will take the default parameter value.

    In the example of modification based on prior:
    the index.jsp added in the form a sex:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/regist1.do" method="post">
姓名:<input type="text" name="username"><br>
年龄:<input type="text" name="age"><br>
性别:<input type="text" name="sex"><br>
<input type="submit" value="提交">
</form>
</body>
</html>

    In the process controller in the parameter name and the name of the form is inconsistent, use @RequestParam:

@Controller
public class HelloSpringMVC {
@RequestMapping("/regist1.do")
public ModelAndView regist1(@RequestParam(name = "username") String t_username,@RequestParam(name="age",defaultValue = "18") int t_age,@RequestParam(required = true) String sex){
ModelAndView mv = new ModelAndView();
mv.addObject("username",t_username);
mv.addObject("age",t_age);
mv.addObject("sex",sex);
mv.setViewName("test");
return mv;
}
}

    name: t_username and t_age parameter name and the name attribute of the form is inconsistent, so the use of the name attribute @RequestParam (property names consistent with the form).

    defaultValue: If we age nothing input, controller will go automatically assigned based on the value defaultValue property settings.

    required: if we set to true, then the sex in this column index.jsp we must enter a value, if you do not enter, then the system will report a 400 error because the request parameter is not sex.   

   

   Objects using the form parameters    

     Use objects to receive parameters form submission

    In the example parameters have submitted the form before receiving a problem, if more forms of argument, the method requires the controller to which these parameters are written on, so it is not convenient, we can define a javabean, the parameters are written in a form which javabean attribute, then the controller writes the bean as a parameter method.

    Example:

    Define a Student class, which is the property name with the form name consistent

package bean;

public class Student {
    private String username;
    private int age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

    Defined Controller, the Student object as a parameter in the method:  

package controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloSpringMVC {
    @RequestMapping("/regist2.do")
    public ModelAndView regist2(Student student) throws Exception{
        ModelAndView mv = new ModelAndView();
        mv.addObject("username", student.getUsername());
        mv.addObject("age", student.getAge());
        mv.setViewName("result");
        return mv;
    }
}

    index2.jsp front page   

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/regist2.do" method="post">
    姓名:<input type="text" name="username"><br>
    年龄:<input type="text" name="age"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

    A jump needs to be received username and jsp age here is not simple to write, as long as the controller corresponds to the setViewName.

    In this way, we can more easily receive data in a form submission.

    Receiving object attribute parameters

    When the request parameter is a property of the object attributes, we can write the object properties in a form of the name. Manner attribute processing.

    Define a class School: 

package bean;

public class School {

    private String schoolName;

    private String address;

    public String getSchoolName() {
        return schoolName;
    }

    public void setSchoolName(String schoolName) {
        this.schoolName = schoolName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

    Student in class School on object properties add up:    

package bean;

public class Student {

    private String username;

    private int age;

    private School school;

    public School getSchool() {
        return school;
    }

    public void setSchool(School school) {
        this.school = school;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

    Modify index2.jsp:   

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/regist3.do" method="post">
    姓名:<input type="text" name="username"><br>
    年龄:<input type="text" name="age"><br>
    学校名:<input type="text" name="school.schoolName"><br>
    地址:<input type="text" name="school.address"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

    Modify Controller class:

package controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloSpringMVC {
    @RequestMapping("/regist3.do")
    public ModelAndView regist3(Student student) throws Exception{
        ModelAndView mv = new ModelAndView();
        mv.addObject("username", student.getUsername());
        mv.addObject("age", student.getAge());
        mv.addObject("schoolName", student.getSchool().getSchoolName());
        mv.addObject("address", student.getSchool().getAddress());
        mv.setViewName("result");
        return mv;
    }
}

    result.jsp    

<% @ Page contentType = "text / HTML; charset = UTF-. 8" Language = "Java"%> 
<HTML> 
<head> 
    <title> the Title </ title> 
</ head> 
<body> 

Username: $ { } name
 <br> 
Age: Age $ {}
 <br> 
password: $ {password}
 <br> 
school name: $ {} schoolName
 <br> 
school address: $ {address}
 </ body> 
</ HTML>

    Then we completed the receiving object attribute parameters.

 

    

 

 

 

Guess you like

Origin www.cnblogs.com/scm2019/p/11345548.html