SPRINGMVC Special study précis-writers-annotated albums

Source: Internet
Author: User
Tags bind constructor lowercase modifier valid
1. @Controller, any Java class can be used as a controller, as long as it is @controller annotated 2. @RequestMapping

2.1@requestmapping can modify Java classes
* The request is from the original ******/hello.do
* Become ******/springmvc/hello.do

@Controller
@RequestMapping ("/springmvc") public
class SpringMVCHelloWorld2 {
	@RequestMapping ("/ Hello2.do ") Public
	String Hello () {
		System.out.println (" Enter Request Method class ... ");
		Return "Success";
	}
	
}

The four attributes of the 2.2@requestmapping to precisely map:

value= "Request URL", if an annotation has only one value property, then value can be omitted, such as: @RequestMapping ("/hello.do")

Method= "Method=requestmethod.get" or method=requestmethod.post .... Requestmethod-is an enumeration class

params={"id"} must have a parameter named ID in the request parameter.

params={"id=12", "Name!=tom"} request parameter must have a parameter named Id=12,name. =tom .....

The headers={"accept"} must contain an accept in the request header.

The code is as follows:

@RequestMapping (value= "/testrequestmapping.do", method=requestmethod.post,params={"id"},headers={"accept"}) Public
	String testrequestmapping () {
		System.out.println ("Enter Testrequestmapping Request method class ...");
		Return "Success";
	}
3. @RequestParam

==> @RequestParam (value= "", Required=true/false)
The value in parentheses is the parameter name, required-whether it is a required parameter.

Front-end page JSP:

<form action= "testrequestparam.do" method= "get" >
	<input type= "text" name= "id" value= "all"/>
	< Input type= "text" name= "name" value= "Xuxu"/>
	...
</form>

Back-End Request method:

@RequestMapping (value= "/testrequestparam.do", method=requestmethod.get) public
String testpathvariable (@ Requestparam (value= "id", required=true) int id, @RequestParam (value= "name", Required=false) String name) {
	//@ Requestparam () in parentheses, value is the parameter name and whether required-is a required parameter.
	return "Success";
}

(@requestparam can be omitted if the formal parameter name matches the request parameter name) 3.1@requestparam Extension: ===>pojo bind request Parameter Pojo class: User, with attribute Id,name,set, get method, ToString () method, constructor .....

Front-end page JSP:

<form action= "testrequestparam.do" method= "get" >
	<input type= "text" name= "id" value= "all"/>
	< Input type= "text" name= "name" value= "Xuxu"/>
	...
</form>

Back-End Request method: If id,name in the request parameter is consistent with the Pojo property, the property of the user object is automatically bound to

@RequestMapping (value= "/testrequestparam.do", method=requestmethod.get) public
String Testrequestparam (User) {
	//If id,name in the request parameter is consistent with the Pojo property, the property of the user object is automatically bound to
	return "success";
Pojo class: User, with Properties Id,name,address object Properties, set, Get method, ToString () method, constructor ..... The Address object property is automatically bound to the properties of the user object if the request parameter id,name is consistent with the Pojo property, and the City,road attribute in the request parameter is consistent with the Address property.
4. @PathVariable ==> binding parameters in URLs with placeholders

Front page jsp:<a href= "/TESTPATHVARIABLE.DO/12" >.....</a><!--12 is parameter--

Back-End Request method:

@RequestMapping (value= "/testpathvariable.do/{id}", Method=requestmethod.get)//map URL {ID} is a placeholder, parameter name ID public
	String testpathvariable (@PathVariable ("id") int id) {
		//@PathVariable ("id") is the parameter name of the placeholder in parentheses and is automatically bound to the parameter ID
		of the method System.out.println ("Enter Testpathvariable Request method class ...");
		SYSTEM.OUT.PRINTLN (ID);
		Return "Success";
	}

5. @RequestHeader


6. @CookieValue

7. @ModelAndView (Pojo object + view) ===> Scope: Only within this request Requset, ${requestscope. Model data parameter name}

Background Request Method Code:

@RequestMapping (value= "Testmodelandview") public
Modelandview Testmodelandview () {
	Modelandview mv = new Modelandview ();
	1. Add a model data
	mv.addobject ("id", "n");
	2. Set the Jump View
	mv.setviewname ("Success");
	3. Returns the Modelandview object return
	mv;
}

Extension: Map, model, Modelmap ===>SPRINGMVC Auto-created data for each request (these three types)

Same scope: Requestscope


Front Code:


Background Request Method:

@RequestMapping (value= "TestMap") public
Modelandview TestMap (map<string,object> Map) {
	map.put (' age ' ,);
	Return "Success";
}
@RequestMapping (value= "Testmodel") public
Modelandview Testmodel (model model) {
	Model.addattribute ("Mail", "123@123.com");
	Return "Success";
}
8. @ModelAttribute ==> Effect: The model data is bound to be read from DB prior to the crud operation. Scenario: User class: Id,name,birthday Three properties do update: The update name value changes from Tom to Jim, and the other is unchanged. If the foreground only passes a name=jim value, with hidden id=12

The background method is bound to the parameter user (only: id=1,name=jim,birthday=null), after the update BirthDay is empty, the previous data is lost. So, this time @modelattribu

The method that is modified by the @modelattribute, before all mapping methods (Request method), the first execution, do the preparatory work.

8.1-@ModelAttribute--modifier * NO * return value method:

The first way to perform @modelattribute adornments:

@ModelAttribute public
void Firstmodelattribute (map<string, object> Map) {
	//here with the new object-simulates reading the user object from DB ....
	User user = new User ("1", "Tom", "2016-1-1");
	Map.put ("user", user),//Do not alias the binding model, auto default is the Pojo class lowercase full name
	map.put ("abc", user);//alias binding model
}
To perform the mapping request method/testmodelattribute1.do:
@RequestMapping (value= "/testmodelattribute1.do") public
String Testmodelattribute (@ModelAttribute ("abc") User User) {
	//If the binding model does not have an alias, the formal parameter of the mapping method: User User, without @modelattribute ("Alias")
	System.out.println (user);
	Return "Success";
}

8.2-@ModelAttribute--modifier * has * return value method:

@ModelAttribute (value= "abc")//alias The binding model, if the binding model is not aliased, automatically defaults to the Pojo class of the lowercase letter full name: User public
	user FirstModelAttribute2 ( Map<string, object> map) {
		//here with the new object-simulates reading the user object from DB ....
		User user = new User ("1", "Tom", "2016-1-1");
		return user;
	}
   
	@RequestMapping (value= "/testmodelattribute2.do") public
	String TestModelAttribute2 (@ModelAttribute ("abc") User user) {
		//If the binding model does not have an alias, the parameter of the mapping method: User User, no @modelattribute ("Alias")
		System.out.println (user);
		Return "Success";
	}
9. @SessionAttributes ==> Scope: Sessions session. Class used to decorate the entire controller
Package Com.controller;

Import Java.util.Map;
Import Org.springframework.stereotype.Controller;
Import Org.springframework.web.bind.annotation.ModelAttribute;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RequestMethod;
Import org.springframework.web.bind.annotation.SessionAttributes;
Import Com.pojo.User;

@Controller
@SessionAttributes (value={"id", "name"}) public
class Springmvchelloworld {
@ Requestmapping (value= "/test.do") public
String test (map<string, object> Map) {
	map.put ("id", 12);    C13/>return "Success";
}
}
The Id,name value of all requests is stored in the session.

The front desk is valued from ${sessionscope.**} . @Component ===> Custom View and parser step 1th. Customizing views in Java Classes

Precautions: @Component
@component alone, the default Bean-id (required by configuration in. xml) is the lowercase letter name of the Java class MyView

If @component (value= "abc"), the logical view name is ABC

Package Com.controller;

Import Java.util.Map;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import org.springframework.stereotype.Component;
Import Org.springframework.web.servlet.View;

@Component
//@component, the default Bean-id (required by configuration in. xml) is the lowercase name of the Java class MyView
//If @component (value= "abc"), The logical view name is the ABC public
class MyView implements view{//implements the view interface

	@Override public
	String getContentType () {
		//Tell spring, Content format contenttype:
		return "text/html";
	}

	@Override//Render public
	void render (map<string,?> Map, httpservletrequest request,
			HttpServletResponse Response) throws Exception {
									//Here is a custom (physical) view
		response.getwriter (). Write ("

2nd Step: Configure the Custom view resolver beannameviewresolver in Springmvc.xml. (Take a good look at the comments in the XML.) )

<!-- 
    	Configuring a view resolver for custom Views: beannameviewresolver---
    <bean class= " Org.springframework.web.servlet.view.BeanNameViewResolver ">
    	<property name=" order "value=" ">< /property>
    	<!--name= "order" defines the priority, and the
    		default view resolver of Internalresourceviewresolver is infinitely large,
    		So the custom beannameviewresolver takes a random value of 100, prioritized at Internalresourceviewresolver--
    </bean>
    <MVC : View-controller path= "/myview" view-name= "MyView"/>
    <!--Note: In spring,
    	if <MVC is configured for a map: view-controller>!
    	The other controller methods will fail ...
    	so configure the <mvc:annotation-driven> again, and make the other controller methods valid:
    -
    <mvc:annotation-driven></mvc:annotation-driven>

Precautions:

<!--precautions: in Springmvc.xml,

If a <mvc:view-controller>! is configured for a mapping
The other controller methods will fail ...
So configure the <mvc:annotation-driven> again, and make the other controller methods valid:
-

<mvc:view-controller path= "/myview" view-name= "MyView"/>

<mvc:annotation-driven></mvc:annotation-driven>

<mvc:view-controller>, <mvc:annotation-driven> to appear in pairs.


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.