Dowemo
0 0 0 0

First, get started with spring mvc, create a helloworld program

1. Fi & t, import the jar package required by spring spring.

2. Add configuration for spring spring in the web. Xml configuration file.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15<! --configure the setting of springmvcdispatcherservlet and configure the mapping--> <servlet>! setting! setting

3. Add spring mvc servlet. Xml configuration file under src.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27<? 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"xmlns : mvc ="http ://www. Springframework. Org/schema/mvc"xsi : schemaLocation ="http ://www. Springframework. Org/schema/beanshttp ://www. Springframework. Org/schema/beans/spring-beans. Xsd. Http ://www. Springframework. Org/schema/contexthttp ://www. Springframework. Org/schema/context/spring-context-4. 1. Xsdhttp ://www. Springframework. Org/schema/mvchttp ://www. Springframework. Org/schema/mvc/spring-mvc-4. 1. Xsd"> <! -- scan the package and the sub package --> <context : component-scan base-package ="test. SpringMVC"/> <! -- don 't handle the static resource --> <mvc : default-servlet-handler/> <! -- if you use annotation you must configure following setting --> <mvc : annotation-driven/> <! -- configure the InternalResourceViewResolver --> <bean class ="org. Springframework. Web. Servlet. View. InternalResourceViewResolver"id ="internalResourceViewResolver"> <! -- --> <property name ="prefix"value ="/WEB-INF/jsp/"/> <! -- --> <property name ="suffix"value =". Jsp"/> </bean> </beans&gt.

4. Create a folder named jsps under the web inf folder to hold the jsp view. Create a hello. Jsp, add hello world in body.

5. Build package and controller, as follows.

6. Writing controller code.

1 2 3 4 5 6 7 8 9A @ controller @ requestmapping ("/mvc") public class mvccontroller % 7b @ requestmapping ("/hello") public string hello ( ) % reference hello; %

7. Start the server, type http://localhost: 8080/project name mvc hello.

, configuration resolution

1. Dispatcherservlet.

A dispatcherservlet is a, configured in we. In the xml file. Blocking the matching request, the servlet blocking matching rule needs to define itself, and the interception request, according to the corresponding rules to.

2. InternalResourceViewResolver.

View name parser

3. Comments that appear above.

@ controller is responsible for registering a bean to the spring context

A @ requestmapping annotation specifies which url requests can be handled for the controller

,, spring spring.

@ controller

Responsible for registering a bean to the spring context

@ requestmapping

Annotations specify which url requests can be handled for the controller

@ requestbody

It's used to read the body portion data of request request, parse using the system 's default configuration HttpMessageConverter, then bind the corresponding data to the

@ responsebody

This annotation is used to write the object returned by the controller to the body data area of the response object after the appropriate HttpMessageConverter is converted to the

@ modelattribute

In the method definition, use the @ modelattribute annotation: Spring mvc first calls the method of @ modelattribute on the method level before calling the target processing method.

A @ modelattribute annotation is used before the input paramete & of the method: You can obtain an object from an implicit object in an implicit model data, and then bind the request parameter - bind to the object, and then pass in the

@ requestparam

A @ requestparam can be used in processing methods to pass request parameters to the request.

@ pathvariable

Bind url placeholder to argument

@.

Note that the method is executed when an exception is thrown

@ ControllerAdvice

Make a contoller a global exception handling class that can handle exceptions that occur by all controller methods in the class by using the method annotation.

, automatic matching parameters

1 2 3 4 5 6Automatically @ requestmapping ("/person") public string toPerson ( string name, double age ) % 7b System.out. khz ( name +""+ age ); return"hello"; %

, automatic boxing

1. Writing a person entity class.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19Package test. Spring mvc. Model; public class person % 7b _ name _ % _ _ _ _ setname _ ( string name ) % 7b this.name = name; % _ 7d _ age; private _ age _ age; private _ age _ age _ age _ age _ age _ age _ age _ age.

2. Write methods in controller.

1 2 3 4 5 6Automatically @ requestmapping ("/person1") public string toPerson ( person p ) % 7b System.out. ( p. Getname ( ) + & + p. Getage ( ) ); return"hello";//boxing _ _ 7d.

, using initbinder to handle date types parameters

1 2 3 4 5 6 7 8 9 10 11 12 13The//the parameter was in initbinder @ requestmapping ( date date ) public string date ( ) % ( date ); return hello; %

,,.

1 2 3 4 5 6 7 8 9A//pass the parameters to front-end @ requestmapping ("/show") public string showperson ( map <string, object> map ) % person p = new person (

The front desk can be removed from the request domain.".

, using ajax calls

1 2 3 4 5 6 7 8 9A//pass the parameters to front-end using ajax @ requestmapping ("/getPerson") public void getPerson ( string name ) % pw. Write ( hello, + ); % @ ("/name") public string sayhello ("/") public string sayhello.

The front desk calls the following jquery code

1 2 3 4 5 6 7A $ ( function ( ) % $ ("#"). Click ( function ( ) % $. Post ("mvc/getPerson", % 7bname: $ ("#"), val ( ) %, function ( data ) % ( data ), % ( data ); %.

, using redirect mode in controller to handle requests

1 2 3 4 5A//redirect @ requestmapping ("/redirect") public string redirect ( ) % 7b 'redirect: hello '; %

, file upload

1. You need to import two jar packages.

2. Join in spring mvc configuration file.

1 2 3 4<! -- upload settings --> <bean id ="multipartResolver class ="org. Springframework. Commons. CommonsMultipartResolver."> <property name/bean>/bean.

3. Method code.

1 2 3 4 5 6 7 8 9 10 11 12 13 14The @ requestmapping ( value ="/upload", method = RequestMethod. Post ) public string upload ( httpservletrequest ) throws an exception % 7b MultipartHttpServletRequest mreq = ( MultipartHttpServletRequest ) req; MultipartFile file = mreq. Diacritics ("file"); string ( yyyymmddhhmmss ); string ( ( ); getServletContext ( ); simpledateformat ( ); fos ( ); fos ( ); fos ( ); fos ( ); fos ( ); fos ( ); fos ( ); fos ( ); fos ( ); fos ( ).

4. form form.

1 2 3 4<form action ="mvc/upload"method ="post form-data"> <input type ="file name ="file> <br> <input type ="submit"value ="submit"= form

, using the requestparam annotation to specify name for the parameter

1 2 3 4 5 6 7 8 9 10A @ controller @ requestmapping ("/test") public class mvccontroller1 % 7b @ requestmapping ( value ="/param") public string testrequestparam ( @ _ requestparam ) integer id, @ ( value ="id") string name

, sringmvc,.

1. RestController.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28@ controller @ requestmapping ("/rest") public class RestController % 7b @ requestmapping ( value ="/user/% 7bid % 7d", method = RequestMethod. Get ) public string get ( @ pathvariable ("id") integer id ) % 7b System.out. println ("get"+ id ); return"/hello"; % 7d @ requestmapping ( value ="/user/% 7bid % 7d", method = RequestMethod. Post ) public string post ( @ pathvariable ("id") integer id ) % 7b System.out. println ("post"+ id ); return"/hello"; % 7d @ requestmapping ( value ="/user/% 7bid % 7d", method = RequestMethod. Put ) public string put ( @ pathvariable ("id") integer id ) % 7b System.out. println ("put"+ id ); return"/hello"; % 7d @ requestmapping ( value ="/user/% 7bid % 7d", method = RequestMethod. Delete ) public string delete ( @ PathVariable ("id") Integer id ) % 7B System.out. println ("delete"+ id ); return"/hello"; % 7d % 7d.

2. Form forms send put and delete requests.

Configure in web. Xml.

1 2 3 4 5 6 7 8 9<! -- configure the HiddenHttpMethodFilter, convert the post method to put or delete --> <filter! configure

In the front desk, the request can be generated with the following code

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17<form action ="rest/user/1"method ="post"> <input type ="hidden"name ="_method"value ="put"> <input type ="submit"value ="put"> </form> <form action ="rest/user/1"method ="post"> <input type ="submit"value ="post"> </form> <form action ="rest/user/1"method ="get"> <input type ="submit"value ="get"> </form> <form action ="rest/user/1"method ="post"> <input type ="hidden"name ="_method"value ="delete"> <input type ="submit"value ="delete"> </form>

. Returning a string in json format.

1. Import the following jar packages.

2. Method code.

1 2 3 4 5 6 7 8 9 10 11 12 13 14A @ controller @ requestmapping ("/json") public class JSONController % 7b @ responsebody @ requestmapping ("/user") public user get ( ) % 7b user u = new user ( ); u. Setid ( 1 ); u ( jayjay ); return ( new date ( ) ).

, .

1. Handling local exceptio ( within controller ).

1 2 3 4 5 6 7 8 9 10 11 12 13@ modelandview mv = new modelandview ("error") % exceptionhandler ( exception ex ) 7b ("error"); System.out. ("in"); ("")

2. Handling global exceptio ( all controlle ).

1 2 3 4 5 6 7 8 9 10A @ ControllerAdvice public % testcontrolleradvice 7b modelandview exceptionhandler ( exception ex ) % 7b modelandview mv = new modelandview ("error"); mv ("in"); System.out. (""); return

Another way to handle global exceptio &

Configure in the spring mvc configuration file

1 2 3 4 5 6 7 8<! -- configure SimpleMappingExceptionResolver --> <bean class ="org. Framework. Web. Servlet. Handler. SimpleMappingExceptionResolver"> <property name ="exceptionMappings">/property/bean/bean.

Error page

, set a custom interceptor

1. Create a MyInterceptor class and implement the HandlerInterceptor interface.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23Public class MyInterceptor implements HandlerInterceptor % @ override public void afterCompletion ( httpservletrequest ) throws exception % 7b System.out. ( exception, HttpServletResponse, object, modelandview ) throws exception % 7b ( ) throws exception % println (. Object, ) throws exception 7b (").

2. Configure in the configuration file.

1 2 3 4 5 6 7<! -- interceptor setting --> <mvc: interceptors> <mvc: resolver> <mvc: mapping path ="/mvc/*"/> bean ="test. Mvc. Interceptor. MyInterceptor/mvc: interceptor"</mvc: interceptors.

3. Interceptor execution order.

, forms validation ( using hibernate validate ) and internationalization

1. Import the jar packages required by hibernate validate.

( no import is selected )

2. Write entity class user and add validation notes.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31Public class user % 7b public int getid ( ) % 7b return id; % 7d public void setid ( int id ) % 7b this.id = id; % 7d public string getname ( ) % 7b return name; % 7d public void setname ( string name ) % 7b this.name = name; % 7d public date getbirth ( ) % 7b return birth; % 7d public void setbirth ( date birth ) % 7b this.birth = birth; % 7d @ override public string tostring ( ) % 7b return"user [ id ="+ id +", name ="+ name +", birth ="+ birth +"]"; % 7d private int id; @ notempty private string name; @ past @ datetimeformat ( pattern ="yyyy-mm-dd") private date birth; % 7d

Ps: @ past indicates that time must be a past value

3. Use the springmvc form form in jsps.

1 2 3 4 5 6<form: form action = 'form/add 'method = 'post 'modelattribute = 'user> id: <form: input path = 'id '/> <form: error path ="id"/> <: <: error path =""/

Ps: path corresponding name

Code in 4. Controller.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17The @ controller @ requestmapping ("/form") public class FormController % 7b @ requestmapping ( value ="/add", method = RequestMethod. Post ) public string add ( @ _ valid ( ) ) ) % 7b.

备注:

1. Because the modelattribute property is used in the jsp, there must be a"user"in the request field.

2. @ valid indicates that the parameter is validated according to the annotation marked on the entity.

3. Return back to the original page error message echo, and the form echo.

5. Error message customization.

Add locale. Properties under the src directory.

NotEmpty.user.name=name can't not be empty
Past.user.birth=birth should be a past value
DateTimeFormat.user.birth=the format of input is wrong
typeMismatch.user.birth=the format of input is wrong
typeMismatch.user.id=the format of input is wrong

Configure in the spring mvc configuration file

1 2 3 4<! -- configure the locale resource --> <bean id ="messagesource"class ="org. Framework. Context. Support. ResourceBundleMessageSource"> <="basename"value ="locale">/property </bean.

6. Internationalization display.

Add locale zh cn. Properties under src.

username=账号
password=密码

Locale. Properties.

username=user name
password=password

Create a locale. Jsp.

1 2 3 4<body> <fmt: message ="username"> </fmt: message> <fmt: message _ _ _ fmt: message> <</fmt: message/body

Configure in spring mvc

1 2<! -- make the jsp page can be visited --> <mvc path ="locale"/> ="locale"/

Let the locale. Jsp access directly under web inf.

Finally, access the locale, jsp, switch browser language, and can see the language of account and password.

,,, and spring.

1. Create a package for test. Spring mvc. Integrate to demo & trate integration and create various types of.

2. User entity class.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31Public class user % 7b public int getid ( ) % 7b return id; % 7d public void setid ( int id ) % 7b this.id = id; % 7d public string getname ( ) % 7b return name; % 7d public void setname ( string name ) % 7b this.name = name; % 7d public date getbirth ( ) % 7b return birth; % 7d public void setbirth ( date birth ) % 7b this.birth = birth; % 7d @ override public string tostring ( ) % 7b return"user [ id ="+ id +", name ="+ name +", birth ="+ birth +"]"; % 7d private int id; @ notempty private string name; @ past @ datetimeformat ( pattern ="yyyy-mm-dd") private date birth; % 7d

3. Userservice class.

1 2 3 4 5 6 7 8 9 10The @ component public class userservice % userservice ("userservice constructor. Nnnnnn"); % logically _ void _ save ( ) % 7b ("save"); % %.

4. Usercontroller.

1 2 3 4 5 6 7 8 9 10 11 12 13A @ controller @ requestmapping ("/integrate") public class usercontroller % 7b userservice userservice; @ pk ("/user") public string mar ( @ ), 7b ( u ), userservice ( u ), ( u ), ( ), return ( );

5. Spring profile.

Create the springioc profile applicationcontext. Xml in the src directory.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22<? xml version ="1. 0"encoding ="UTF-8"?> <beans xmlns ="http ://www. Springframework. Org/schema/beans"xmlns : xsi ="http ://www. W3. Org/2001/XMLSchema-instance"xsi : schemaLocation ="http ://www. Springframework. Org/schema/beanshttp ://www. Springframework. Org/schema/beans/spring-beans. Xsdhttp ://www. Springframework. Org/schema/utilhttp ://www. Springframework. Org/schema/util/spring-util-4. 0. Xsd. Http ://www. Springframework. Org/schema/contexthttp ://www. Springframework. Org/schema/context/spring-context. Xsd"xmlns : util ="http ://www. Springframework. Org/schema/util"xmlns : p ="http ://www. Springframework. Org/schema/p"xmlns : context ="http ://www. Springframework. Org/schema/context"> <context : component-scan base-package ="test. SpringMVC. Integrate"> <context : exclude-filter type ="annotation"expression ="org. Springframework. Stereotype. Controller"/> <context : exclude-filter type ="annotation"expression ="org. Springframework. Web. Bind. Annotation. ControllerAdvice"/> </context : component-scan> </beans&gt.

Adding configuration to web. Xml.

1 2 3 4 5 6 7 8<! -- configure the springioc --> <> <listener-class> org. Springframework. Web. Context. ContextLoaderListener/listener-class </listener/listener>.

6. Some configuration is made in spring mvc to prevent springmvc and springioc from being managed on the same object.

1 2 3 4 5 6 7<! -- scan the package the sub package package package --> <context: component-scan base-package ="test. Mvc. Integrate".

,, springmvc flow chart


More detailed source reference sources: . Http://minglisoft. Cn/technology.

Welcome to learn about the related technologies, source access, please add ( craig ): 2042849237.




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs