SPRINGMVC @SessionAttributes use of detailed and source analysis

Source: Internet
Author: User

@sessionattributes

@Target ({elementtype.type}) @Retention (retentionpolicy.runtime) @Inherited @documentedpublic @interface sessionattributes {    string[] value () default {};    Class[] Types () default {};}

@sessionattributes annotations are applied to the controller, you can synchronize the properties in the model to the session.

Let's look at one of the most basic methods.

@Controller @requestmapping ("/demo.do") @SessionAttributes (value={"attr1", "ATTR2"}) public class Demo {        @ Requestmapping (params= "Method=index") public    Modelandview Index () {        Modelandview Mav = new Modelandview (" Index.jsp ");        Mav.addobject ("attr1", "Attr1value");        Mav.addobject ("Attr2", "Attr2value");        return MAV;    }        @RequestMapping (params= "method=index2") public    Modelandview Index2 (@ModelAttribute ("attr1") String attr1, @ Modelattribute ("attr2") String attr2) {        Modelandview Mav = new Modelandview ("success.jsp");        return MAV;    }
}

The index method returns a Modelandview that includes the view index.jsp and two key values into the model, and when the @sessionattributes annotation is not added, the key value in the model is the request level.

Now because the @sessionattributes (value={"attr1", "ATTR2"}) is marked on the controller, the ATTR1,ATTR2 in the model is synchronized to the session so that when you access the index You will also get the values of these two properties when you visit Index2.

When it's time to clear the session, we just need to pass in a Sessionstatus type object in the controller's method to clear it by calling the SetComplete method.

@RequestMapping (params= "method=index3") public Modelandview index4 (sessionstatus status) {Modelandview Mav = new Modela  Ndview ("success.jsp");  Status.setcomplete (); return MAV;}

The following is a direct analysis of the code to see if spring is encapsulated.

First we need to look at 2 classes of Defaultsessionattributestore and Sessionattributeshandler

Defaultsessionattributestore This class is a tool class for accessing data to WebRequest, WebRequest is the httpservletrequest of spring packaging, Everyone understands it as an ordinary httpservletrequest on the line.

public class Defaultsessionattributestore implements Sessionattributestore {private String attributenameprefix = "";  public void Setattributenameprefix (String attributenameprefix) {This.attributenameprefix = (attributenameprefix ! = null?    Attributenameprefix: ""); } public void Storeattribute (WebRequest request, String AttributeName, Object attributevalue) {Assert.notnull (R        Equest, "WebRequest must not being null");        Assert.notnull (AttributeName, "Attribute name must not being null");        Assert.notnull (AttributeValue, "Attribute value must not being null");        String storeattributename = getattributenameinsession (request, AttributeName);    Request.setattribute (Storeattributename, AttributeValue, webrequest.scope_session); The public Object Retrieveattribute (WebRequest request, String AttributeName) {assert.notnull (Request, "webreques        T must not is null ");        Assert.notnull (AttributeName, "Attribute name must not being null"); StRing Storeattributename = getattributenameinsession (request, AttributeName);    Return Request.getattribute (Storeattributename, webrequest.scope_session); } public void Cleanupattribute (WebRequest request, String AttributeName) {assert.notnull (Request, "WebRequest m        UST not is null ");        Assert.notnull (AttributeName, "Attribute name must not being null");        String storeattributename = getattributenameinsession (request, AttributeName);    Request.removeattribute (Storeattributename, webrequest.scope_session); } protected string Getattributenameinsession (WebRequest request, String attributename) {return This.attributena    Meprefix + attributename; }}


Spring Initializes a Sessionattributeshandler instance for each controller to record the property information in @sessionattributes (value={"attr1", "ATTR2"}), When a model's value needs to be synchronized, it is first judged whether it is defined in sessionattributes.

public class Sessionattributeshandler {private final set<string> attributenames = new hashset<string> ();    Private final set<class<?>> attributetypes = new hashset<class<?>> ();    Private final set<string> knownattributenames = Collections.synchronizedset (New hashset<string> (4));    Private final Sessionattributestore Sessionattributestore; Public Sessionattributeshandler (class<?> handlertype, Sessionattributestore sessionattributestore) {ASSERT.N        Otnull (Sessionattributestore, "Sessionattributestore May is not null.");        This.sessionattributestore = Sessionattributestore;        sessionattributes annotation = annotationutils.findannotation (Handlertype, Sessionattributes.class);            if (annotation! = null) {This.attributeNames.addAll (Arrays.aslist (Annotation.value ()));        This.attributeTypes.addAll (Arrays.<class<?>>aslist (Annotation.types ())); } This.knownattributenAmes.addall (This.attributenames); } public boolean hassessionattributes () {return ((this.attributeNames.size () > 0) | |    (This.attributeTypes.size () > 0)); } public boolean Ishandlersessionattribute (String attributename, class<?> attributetype) {assert.notnull (        AttributeName, "Attribute name must not being null"); if (This.attributeNames.contains (attributename) | | this.attributeTypes.contains (attributetype)) {This.knownatt            Ributenames.add (AttributeName);        return true;        } else {return false; }} public void Storeattributes (WebRequest request, map<string,?> attributes) {for (String Name:att            Ributes.keyset ()) {Object value = attributes.get (name); Class<?> Attrtype = (value = null)?            Value.getclass (): null; if (Ishandlersessionattribute (name, Attrtype)) {This.sessionAttributeStore.storeAttribute (request, name, V Alue);           }}} public map<string, object> retrieveattributes (WebRequest request) {Map<stri        ng, object> attributes = new hashmap<string, object> (); for (String name:this.knownAttributeNames) {Object value = This.sessionAttributeStore.retrieveAttribute (requ            EST, name);            if (value! = null) {attributes.put (name, value);    }} return attributes;            } public void Cleanupattributes (WebRequest request) {for (String attributeName:this.knownAttributeNames) {        This.sessionAttributeStore.cleanupAttribute (Request, AttributeName); }} Object Retrieveattribute (WebRequest request, String AttributeName) {return this.sessionAttributeStore.re    Trieveattribute (Request, AttributeName); }}

When we visit a method in the controller, we call the Invokehandlemethod method in the Requestmappinghandleradapter class.

View Code

Let's look at this line of code

Modelfactory.initmodel (WebRequest, Mavcontainer, Requestmappingmethod);

Follow up to see the source code

View Code

These two sentences are the key place, the value of the session is taken out to all into the modelandviewcontainer, so that I can be the controller in the method to obtain, of course, directly from the session can also be taken.

map<string,?> attributesinsession = this.sessionAttributesHandler.retrieveAttributes (request);
Mavcontainer.mergeattributes (attributesinsession);

There are only two ways to get sessionattributes in a controller.

I. Public Modelandview INDEX2 (@ModelAttribute ("attr1") string attr1, @ModelAttribute ("Attr2") string attr2)

Ii. public Modelandview index2 (Modelmap map)

The difference between the two is that if you use the @modelattribute property to get the value, and the attribute is set in the @sessionattributes annotation, the exception will run out when the property is null because of these lines of code.

For (String name:findsessionattributearguments (Handlermethod)) {            if (!mavcontainer.containsattribute (name)) {                Object value = this.sessionAttributesHandler.retrieveAttribute (request, name);                if (value = = null) {                    throw new Httpsessionrequiredexception ("expected session attribute '" + name + "'");                }                Mavcontainer.addattribute (name, value);}            }

The above analysis is the value of the process, then spring is how to synchronize the model data into the session.

We look at the last sentence of the Invokehandlemethod method above return Getmodelandview (Mavcontainer, Modelfactory, webRequest); We follow up to see the source code.

View Code

One line of code is Modelfactory.updatemodel (WebRequest, Mavcontainer); We are following up to see the source code.

We see first to determine whether the sessionstatus in the Modelandviewcontainer is a complete state, and if true, clears the value in the session. Instead, the model value in the Modelandviewcontainer is set in.

View Code

See here there may be a question, that is, our data is set to Modelandview inside, then how this data to go to the modelandviewcontainer, in fact, after the completion of the implementation of the method spring help us Do,

For details, see the last line of code in the Modelandviewmethodreturnvaluehandler method Mavcontainer.addallattributes (Mav.getmodel ());

View Code

SPRINGMVC @SessionAttributes use of detailed and source analysis

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.