SPRINGMVC--@ModelAttribute/view, view resolver/internationalization

Source: Internet
Author: User
Tags i18n

@ModelAttribute This annotation annotation more ...

I have a bit of a look at the crazy ...

Or in the original example of the demo ....

@ModelAttribute and view parsing, and internationalization I've written it all together, and it's not separate.






Package Com.springmvc.handlers;import Com.springmvc.model.user;import Com.springmvc.model.user2;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.*;import Org.springframework.web.servlet.modelandview;import Java.util.arrays;import Java.util.date;import java.util.Map;/ * * Created by cyx on 2016/4/15. */@SessionAttributes (value = {"User"},types = {String.class}) @RequestMapping ("/main") @Controllerpublic class Main {PR    Ivate static final String SUCCESS = "SUCCESS";     /** * View and view resolver * When the request processing method finishes executing, a Modelandview object is returned.     * For those processing methods that return types such as String,view or Modemap, SPRINGMVC also assembles them internally into a Modelandview object that contains the logical name and view of the model object.     * * Springmvc with the View parser, the final view object is obtained, and the final view can make the JSP, or possibly the Excel,jfreechart, a view of various representations.     * The processor does not care about what view object is ultimately being taken to render the model data, and the processor focuses on the work of the production model data to achieve full decoupling of MVC.     * View: The function of the view is to render the model data and present the data in the model to the customer in some form.     * In order to decouple the view model and the specific implementation technology, spring defines a highly abstract view interface in the Org.springframework.web.servlet package. * The View object is instantiated by the view resolver. Because the view is stateless, so they don't have thread safety issues.     * View parser: SPRINGMVC provides different strategies for parsing logical view names, and you can configure one or more parsing strategies in the context of Springweb and specify the order of precedence between them.     * Each mapping strategy corresponds to a specific view resolver implementation class.     * View parser is a single function: Parses a logical view into a specific view object.     * All view parsers must implement the Viewresolver interface. * @return */@RequestMapping ("/testviewandviewresolver") public String Testviewandviewresolver () {System        . OUT.PRINTLN ("Testviewandresolver");    return SUCCESS;     /** * Simulates submitting user form data, not submitting it for a password, but directly going to the database to get the updated parameters. * Simulated modification operation * 1. The original data is: 1,tom,123456,[email protected],12 * 2. The password cannot be modified * 3. Form ECHO, simulation operation directly in the form fill in the corresponding property value * *       1. The method marked by the @modelattribute will be called by the SPRINGMVC before each target method is executed * [email protected] Annotations can also be used to decorate the target method Pojo type of the parameter. Its Value property values have the following effect: * (1).     SPRINGMVC uses the Value property values to find the corresponding object in the Implicitmodel, and if it exists, it is passed directly into the parameter of the target method. * (2).     Springmvc the value of the object of type Key,pojo is value, which is stored in the request. * @param ID * @param map */@ModelAttribute public void GetUser2 (@RequestParam (value = "id", required = FALSE) Integer ID, map<string,object> Map) {System.out.println ("Modelattribute method"); if (id! = NULL) {//simulates getting an object from the database User2 user2 = new User2 (1, "Tom", "123456", "[Email prot            Ected] ", 12);            System.out.println ("Get an object from the database:" +user2);        Map.put ("abc", USER2); }}/** * Run the process: * 1. Perform the @modelattribute annotation retouching method: Remove the object from the database, put the object into the map, the user * 2.SpringMVC from the map     The request parameter of the form, assigned to the corresponding property of the user object. * 3.SpringMVC put the above object, the parameters of the target method * Note: In the @modelattribute modified method, the key placed in the map, need to be consistent with the target method in the name of the parameter * * SPRINGMVC determine the target method     The process of Pojo type into the parameter.     * 1. Determine a key * (1). If the parameter of the POJO type of the target method does not use @modelattribute as the adornment, the key is the lowercase of the first letter of the POJO class name.     * (2). If @modelattribute is used, the key is the value of the @modelattribute annotation.     * 2. In Implicitmodel, find the object that corresponds to the key. If present, it is passed in as an incoming argument.     * (1). If you have saved the map in the method of the @modelattribute tag, and key and 1 determine the same key, you will get it. * 3. If no key corresponding object exists in Implicitmodel, check whether the current handler is using @sessionattributeannotation adornments.     * If the annotation is used, and the value of the @sessionattribute note contains key, the value of the value corresponding to the key is obtained from the httpsession, * if present, it is passed directly into the target method and throws an exception if it does not exist.     * 4. If handler does not indicate the value of the @sessionattribute annotation or the @SessionAttribute annotation does not contain a key, the parameter of the Pojo type is created by reflection, passing in the parameter * 5 of the target method.     * * * Source Analysis Process: * 1. The first call to the @modelattribute annotation retouching method is to put the data in the Map in the @ModelAttribute method in the Implicitmodel. * 2. Resolves the target parameter of the request processor, in effect the target parameter is derived from the target property * (1) of the Webdatabinder object. Create Webdatabinder object: * 1). OK Objectnam     E property if the value of the passed-in Attrname property is "", the objectname is the first letter of the class name lowercase. * Note: Attrname.     If the Pojo property of the target method is decorated with @modelattribute, then Attrname is the value of the @modelattribute Value property. * 2). Determine the target property * > Find Attrname corresponding property value in Implicitmodel.     If present, OK * > If not present: Verifies whether the current handler is decorated with @sessionattributes, and if so, attempts to get the property value of Attrname from the session. * If there is no corresponding attribute in the session, throw an exception * > If handler is not decorated with @sessionattribute, or @sessionattribute The key and attrname specified using value are matched by aBuild Pojo Object * * (2).     SPRINGMVC assigns the request parameters of the form to the properties of the Webdatabinder target. * (3).      SPRINGMVC will give Webdatabinder's attrname and Target to Implicitmodel * (4). Pass Webdatabinder's Tager as parameters to the parameter of the target method * (5).     SPRINGMVCH will save the key and value in the Implicitmodel, which will then be saved to the request.     * * @ModelAttribute ("abc") is equivalent to adding an alias to the name User2. This way, ABC can also find User2 this object. * * * * @param user2 * @return * * * @RequestMapping ("/testmodelattribute") public String Testmodelattrib        Ute (@ModelAttribute ("abc") User2 user2) {System.out.println ("modified:" +user2);    return SUCCESS; }/** * @SessionAttributes * If you want to share a certain type of property data across multiple requests, you can label a @sessionattributes,springmvc on the controller class to temporarily save the corresponding property in the model to httpses     The Sion.     * @SessionAttributes except that you can specify the attributes that need to be placed into the session by the property name (Value property values) * You can also specify which model properties need to be placed into the session by the object type of the model property (types property value) * This annotation can only be placed above the class. * * * @param map * @return */@RequestMapping ("/testsessionattributes") public String Testsessio Nattributes (Map<strinG,object> map) {User user = new User ("Tom", "123456", "[email protected]", 15);        Map.put ("user", user);        Map.put ("school", "Asian Faith");        System.out.println ();    return SUCCESS;     }/** * The second way to process model data * The target method can add parameters of the map type.     * It can actually be a model type, or a modelmap type. * * @param map * @return */@RequestMapping ("/testmap") public String TestMap (map<string,object> m        AP) {System.out.println (Map.getclass (). GetName ());        Map.put ("Names", Arrays.aslist ("Tom", "Jerry", "Mike"));        System.out.println ();    return SUCCESS;        } @RequestMapping ("/testmodelandview") public Modelandview Testmodelandview () {String viewName = SUCCESS;        Modelandview Modelandview = new Modelandview (viewName);        System.out.println ("Testmodelandview");        Modelandview.addobject ("Time", New Date ());        Modelandview.addobject ("str", "Hello");    return modelandview; } @RequestMapping ("/testrequestparam")   public string Testrequestparam (@RequestParam (value = "username") string username, @Re Questparam (value = "age", required = false, DefaultValue = "0") Integer age) {System.out.println ("Testrequestparam        UserName: "+username+", Age: "+age";    return SUCCESS;         } @RequestMapping ("/testpojo") public String Testpojo (user user) {System.out.println ("Testpojo User:" +user);    return SUCCESS;        } @RequestMapping ("/testpathvariable/{id}") Public String testpathvariable (@PathVariable ("id") of the Integer ID) {        SYSTEM.OUT.PRINTLN ("testpathvariable ID:" +id);    return SUCCESS; } @RequestMapping (value = "/testmethod", method = requestmethod.post) public String TestMethod () {System.out.        println ("TestMethod POST");    return SUCCESS;        } @RequestMapping ("/sayhello") public String SayHello () {System.out.println ("Hello");    return SUCCESS; }}


success.jsp

<%--Created by IntelliJ idea. User:cyx DATE:2016/4/15 time:22:38 To change this template use File | Settings | File templates.--%><%@ page contenttype= "Text/html;charset=utf-8" language= "java"%><% @taglib prefix= " FMT "uri=" http://java.sun.com/jsp/jstl/fmt "%>


I18n_zh_cn.properties
i18n.username=\u7528\u6237\u540di18n.password=\u5bc6\u7801


I18n_en_us.properties

I18n.username=usernamei18n.password=password


index.jsp

<%--Created by IntelliJ idea. User:cyx DATE:2016/4/15 time:21:53 To change this template use File | Settings | File templates.--%><%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>
Dispatcher-servlet.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:       Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context.xsd "> <context:component-scan base-package=" com.springmvc.handlers "/> <bean class=" Org.springframework.web.servlet.view.InternalResourceViewResolver "> <property name=" prefix "value="/web -inf/views/"></property> <property name=" suffix "value=". jsp "></property> </bea n> <!--configuring internationalized Resource Files--<bean id= "Messagesource" class= "Org.springframework.context.support.ResourceBu Ndlemessagesource "> <property name="BaseName "value=" i18n "></property> </bean></beans> 

The deployment can be run ...

To test internationalization, use IE browser to toggle the language settings in inter ....



SPRINGMVC--@ModelAttribute/view, view resolver/internationalization

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.