Spring MVC front-end Data Interaction summary

Source: Internet
Author: User
Tags button type reflection

    • Controller

As a controller, the general function is to receive the data as V-end and give it to the M-layer to handle, then manage the jump of V. The role of SPRINGMVC is nothing more than that, mainly divided into: receive the form or the value of the request, define the filter, jump page, in fact, is the servlet alternative.

-Append

Spring MVC plays the role of V in Web applications, is responsible for processing HTTP requests and returns the appropriate resources, it is used to configure a core dispatcher is responsible for checking the resources, when the request comes over to find whether there is a corresponding handler, There will be a request to the controller, the general use of annotations to configure exposure to the client to make the call.

@RequestMapping (value= "/json", produces= "Text/html;charset=utf-8")

Value is the externally exposed interface address.

When it comes to controllers, we think of familiar Struts2, which can easily invoke request and response to manipulate requests, and if you want to invoke a request response in spring MVC, it needs to be attached to the method parameter.

    Request Response    @RequestMapping (value= "/reqandrep", produces= "Text/html;charset=utf-8") public    Void Reqandrep (httpservletrequest request,httpservletresponse response) {            }

This allows you to control the HTTP request and write something in the response body.

    • Method of transmitting value

-Append

Glimpse, saw blinders, not see Tarzan. In the process of front-end interaction, you first need to know what the data types are and what kind of programming the Spring MVC will provide for different types.

The data on the front and back end is nothing more than: variables, objects, arrays, JSON; they may have iterative behavior, and the basic understanding is not afraid of their two-time type.

The most convenient point of SPRINGMVC is that it can be annotated to define its URL.

@Controllerpublic class Formmvc {    @RequestMapping ("/hello") public    Void login () {            }

In this way, you can access this method with Hello under the project name, which is more efficient than the STRUTS2 XML configuration and is a method-level development.

Receiving form data only needs to add a response field to the parameter of the method, corresponding to the form input's Name property, because it is implemented by reflection technology so the fields are exactly the same

Variable

    @RequestMapping ("/login") Public    String Login (string username,string password) {        System.out.println ( Username+ "" +password);        return "form.jsp";    }

-Append

Variables are typically the formal parameters of the name specified in the form, or you can use aliases in formal parameters.

    Incoming generic parameter    @RequestMapping (value= "/normal", produces= "Text/html;charset=utf-8") public    String Normal ( HttpServletRequest request, @RequestParam ("username") string username, @RequestParam ("password") string password) {        System.out.println ("Username:" +username+ "Password:" +password);        Request.setattribute ("info", "Normal server recv:" +username+ "" +password);        return "testpage.jsp";    }

Front-end data page, write a form,input corresponding alias is good.

<%@ 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" >

In this way, the form will receive a value after it is submitted. The way to jump is to use the returned string, and the Springmvc Dispatcherservlet jumps to the page of the string. You can also configure its prefix suffix. Configure the following attribute in its configuration file, which is the prefix suffix that you configured before and after the return string. For example, if you return a index.jsp, you can configure the index page in the demo package with the prefix demo/index.jsp.

    <!--Configure the Internalresourceviewresolver--and    <bean class= " Org.springframework.web.servlet.view.InternalResourceViewResolver "             id=" Internalresourceviewresolver ">        <!--prefix--        <property name= "prefix" value= ""/>        <!--suffix        ---<property name= " Suffix "value=" "/>    </bean>

Object

-Append

Pass the object this matter, said really and Struts2 no difference, Struts2 use Modeldriven or directly in the controller to create a new object, the HTTP request when the name needs to be written: the name of the object. Field name , this form. But spring MVC is as long as you are the same as the field name (the Class property name).

    The Incoming object    @RequestMapping (value= "/object", produces= "Text/html;charset=utf-8") public    String Objtransaction ( HttpServletRequest request, @ModelAttribute Demo d) {        System.out.println ("Username:" +d.getusername () + "Password: "+d.getpassword ());        Request.setattribute ("info", "Objtransaction server recv:" +d.getusername () + "" +d.getpassword ());        return "testpage.jsp";    }

Front desk is still the last page, change some action on the line.

In addition, Spring MVC can use beans to receive parameters because it is reflection technology, so attribute fields remain exactly the same.

public class User {    private String username;    private String password;    Public String GetUserName () {        return username;    }    public void Setusername (String username) {        this.username = username;    }    Public String GetPassword () {        return password;    }    public void SetPassword (String password) {        this.password = password;    }    }
    @RequestMapping (value= "/model", method=requestmethod.post) public    String Loginmodel (user u) {        System.out.println (U.getusername () + "" +u.getpassword ());        return "form.jsp";    }

-Append

    Array

Form submission is sure to have a batch submission requirements, batch submission although not always can be seen, but learning must learn the whole. Batch submission is name sharing a name, which is usually a framework for you to handle, so spring MVC writes a list in a method parameter to receive a batch submission of the same variable.

    Incoming array    @RequestMapping (value= "/array", produces= "Text/html;charset=utf-8") public    String arraytransaction (HttpServletRequest request, @RequestParam ("username") string[] usernames) {        if (usernames! = null)        {for            (int i=0;i<usernames.length;i++)                System.out.println ("Username:" + Usernames[i]);        }        Request.setattribute ("info", "Arraytransaction server recv");        return "testpage.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" >

    Json

-Append

Spring MVC provides annotations for automating the serialization of JSON data, which can be easily converted when the JSON data is provided at the front end. Why JSON is so important, because in a restful architecture, it is almost a standard to pass data using JSON, and even a microservices architecture, where each service is generally seen as a restful interface designed to design a restful style spring MVC has a natural support, just need to use its annotations, and the returned string can be constructed on its own.

Package Common.controller;import Org.springframework.stereotype.controller;import net.sf.json.jsonobject;/** * Interface output JSON form * RESTful * {"status": "0|1|2", "info": message, "result": result} * status:0. Failure; 1. Success 2. (undecided); * Info: Return Server information * Result: Return query result * @author CTK * */@Controllerpublic class Outputstringcontroller {//Return success Information public String success (Stri        ng info) {jsonobject result = new Jsonobject ();        Result.put ("status", 1);        if (info = = null) result.put ("info", "");        else Result.put ("info", info);        Result.put ("Result", "");    return result.tostring ();        }//Return failure information public string failure (string info) {Jsonobject result = new Jsonobject ();        Result.put ("status", 0);        if (info = = null) result.put ("info", "");        else Result.put ("info", info);        Result.put ("Result", "");    return result.tostring (); }//Returns the result-successful public string resultsuccess (String info,string resul) for use by the front endTSTR) {jsonobject result = new Jsonobject ();        Result.put ("status", 1);        if (info = = null) result.put ("info", "");        else Result.put ("info", info);        if (ResultStr = = null) result.put ("Result", "");        else Result.put ("result", resultstr);    return result.tostring (); }//Returns the result-failed public string resultfailure (String info,string resultstr) for front-end use {jsonobject result = new JSON        Object ();        Result.put ("status", 0);        if (info = = null) result.put ("info", "");        else Result.put ("info", info);        if (ResultStr = = null) result.put ("Result", "");        else Result.put ("result", resultstr);    return result.tostring (); }}

After the top-level class is defined, the authoring interface inherits. The interface style is as follows.

    RESTful interface    @RequestMapping (value = "/start/{name}", produces = "text/html;charset=utf-8")    @ResponseBody Public     string Start2 (@PathVariable ("name") string name1) {        System.out.println (name1);        return "Start";    }

    

Back to the point, to pass the JSON, its process is the foreground waiting for the user input, the user input after the data is constructed into JSON, and then access the interface. The code of the foreground is what I wrote.

<%@ 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" >

Note DataType If you use JSON that the server returns what will go to error, I initially understand it as the return data type.

Spring MVC unpacking needs Jackson this thing, the author stepped over the pit, no jar package has been visited return 415, does not support such media. The author uses the 2.5 version, and spring is 4.0.

Import it into the project, and then configure Applicationcontext.xml, which is the spring configuration file.

    <!--JSON Converter--    <bean class= " Org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter ">        <property name=" Messageconverters ">            <list >                <ref bean=" Mappingjacksonhttpmessageconverter "/>            </ list>        </property>    </bean>    <bean id= "Mappingjacksonhttpmessageconverter"        class = "Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >        <property name= " Supportedmediatypes ">            <list>                <value>text/html;charset=UTF-8</value>            </ list>        </property>    </bean>

Then the background interface is as follows.

    Incoming JSON    @RequestMapping (value= "/json", produces= "Text/html;charset=utf-8")    @ResponseBody     Public String jsontransaction (httpservletrequest request, @RequestBody Demo ds) {        System.out.println ("Username:" + Ds.getusername () + "Password:" +ds.getpassword () + "Name:" +ds.getname () + "Email:" +ds.getemail ());        Request.setattribute ("info", "JSON server recv");        Return "Success";    }

@ResponseBody is that the return value is written to the response body, @RequestBody to convert the contents of the request body information into the demo class.

    

Finally, the data sent from the front end is wrapped in JSON and can still be received using the bean at the backend.

<%@ 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" >

Finally, there is an unsolved mystery, the object array to submit how to do, the data has not been found, first do not do this.

Spring MVC front-end Data Interaction summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.