20-spring Learning-spring MVC Basic Operations

Source: Internet
Author: User

This time to implement the CRUD function of data, data still in the form of VO data reception.

First, establish the Message.java class operation, responsible for the data receiving operation.
 Packagecom. Springmvc.vo; Public classType {PrivateString title;  PublicString GetTitle () {returntitle; }     Public voidSettitle (String title) { This. title =title; } @Override PublicString toString () {return"Type [title=" + title + "]"; }    }

And

 Packagecom. Springmvc.vo;Importjava.io.Serializable;Importjava.util.Date; @SuppressWarnings ("Serial") Public classMessageImplementsserializable{PrivateInteger mid; PrivateString title; PrivateDouble Price; PrivateDate pubdate; Privatetype type;  PublicInteger Getmid () {returnmid; }     Public voidSetmid (Integer mid) { This. mid =mid; }     PublicString GetTitle () {returntitle; }     Public voidSettitle (String title) { This. title =title; }     PublicDouble GetPrice () {returnPrice ; }     Public voidSetprice (Double price) { This. Price =Price ; }     PublicDate getpubdate () {returnpubdate; }     Public voidsetpubdate (Date pubdate) { This. pubdate =pubdate; }     PublicType GetType () {returntype; }     Public voidsetType (Type type) { This. Type =type; } @Override PublicString toString () {return"Message [mid=" + Mid + ", title=" + title + ", price=" + Price + ", pubdate=" + pubdate + ", type=" + type + "]"; }    }

2, define the action.

Example: Defining messageaction
 Packagecom. springmvc.action;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;Importcom. SpringMVC.vo.Message; @Controller//Defining the Controller@RequestMapping ("/pages/back/message/*")//Overall access Path Public classmessageaction {@RequestMapping ("Hello_demo")//to define a mapped subpath for the demo method     Public voidDemo (Message msg) {System.out.println (msg); }}

As a result of the first execution, you can pass the required data directly using the address rewriting method.

http://localhost:8080/springmvc/pages/back/message/hello_demo.action? mid=12&title= Today Headlines &price=8&type.title= Daily News  

Background Server results:

The above address consists of the following structure:

Parent path of 1,action: http://localhost:8080/SpringMVC/pages/back/message/

2, configure the method path:/hello_demo.action.

3, which represents the composition of the message object:? mid=12&title= today's headline &price=8&type.title= news every day .

The biggest feature of the code at this point is that the controller does not need to write class attribute receive parameters, and all receive parameters are placed on the business method being processed.

It also avoids the problem of instantiating objects.

The most critical problem during the entire operation is that the passed parameter only needs to pass the property name. If the relationship is a reference, you only need to follow the "." Arrangement (as in the type.title above).

You can also set the request type of a business method in Springmvc. If the previous action was modified:

 Packagecom. springmvc.action;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;Importcom. SpringMVC.vo.Message; @Controller//Defining the Controller@RequestMapping ("/pages/back/message/*")//Overall access Path Public classmessageaction {@RequestMapping (value= "Hello_demo",Method=requestmethod.get)//to define a mapped subpath for the demo method     Public voidDemo (Message msg) {System.out.println (msg); }}

Using this syntax means that the configured method can only be triggered using the GET request mode. can also be modified as a POST request.

// Define controller @RequestMapping ("/pages/back/message/*")         // Overall access path publicclass  messageaction {        @RequestMapping (value= "Hello_demo",method=requestmethod.post)    // define the mapping subpath    for the demo method  Public void Demo (Message msg)    {        System.out.println (msg);}    }

If the business processing method is set to a POST request, it means that the form can only be blamed for submission to this method.

If a business operation method, which supports post, can also support get, then do not write Requestmethod.

For the processing of return values, Spring MVC has some requirements that, in normal development, will often provide altogether forword.jsp pages. The function of this page is to make the information prompt after the operation function is completed.

Example: Define FORWORD.JSP page:
<%@ page language= "Java"Import= "java.util.*" pageencoding= "Iso-8859-1"%><%String Path=Request.getcontextpath (); String BasePath= Request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" ><script type= "Text/javascript" > Window.alert ("${msg}");        window.location= "<%=basepath%>${url}"; </script></body>

If by a total controller, jump to the forword.jsp page, you need at least the following:

1, the controller needs to know the path of the forword.jsp page.

2, the controller needs to pass several request attributes (such as the above $ (msg) and $ (URL)).

Because of this, a class is specifically designed in SPRINGMVC: Modelandview, and this class defines the following methods:

1, construction Method: Public Modelandview ().

2, Construction Method: Public Modelandview (String viewName), ViewName, the path address of the jump;

3, Save property: Public Modelandview addobject (String attrivbutename,object attrivatevalue);

Example: Better handling jumps:
 Packagecom. springmvc.action;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.portlet.ModelAndView;Importcom. SpringMVC.vo.Message; @Controller//Defining the Controller@RequestMapping ("/pages/back/message/*")//Overall access Path Public classmessageaction {@RequestMapping (value= "Hello_demo")//to define a mapped subpath for the demo method     PublicModelandview Demo (Message msg) {Modelandview MD=NewModelandview ("/pages/forword.jsp"); Md.addobject ("msg"," message information added successfully "); Md.addobject ("URL","/index.jsp");        SYSTEM.OUT.PRINTLN (msg); returnMD; }}

Here through the Modelandview, jump to the forword.jsp page, at the same time, to this page to pass two attribute values, MSG and URL.

Effect:

And then jumps to the next page.

Through the above program analysis can summarize the advantages of MVC design

1, avoids the complex path jump configuration operation.

2, avoid excessive "." In the project. The case as a parameter.

  

 

20-spring Learning-spring MVC Basic Operations

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.