You are on page 1of 14

Spring Web MVC Framework

Spring Web MVC Framework provides Model- View Controller architecture to develop flexible and loosely coupled web applications !he Model encapsulates the application data and in general they will consist of "#$# !he View is responsible for rendering the model data and in general it generates %!M& output that the client's browser can interpret !he Controller is responsible for processing user re(uests and building appropriate model and passes it to the view for rendering Folllowig is the events corresponding to and incoming %ttp re(uests to )ispatcher Servlet *fter receiving an %!!" re(uest+ DispatcherServlet consults the HandlerMapping to call the appropriate Controller !he Controller takes the re(uest and calls the appropriate service methods based on used ,-! or "#S! method !he service method will set model data based on defined business logic and returns view name to the DispatcherServlet !he DispatcherServlet will take help from ViewResolver to pickup the defined view for the re(uest #nce view is finali.ed+ !he DispatcherServlet passes the model data to the view which is finally rendered on the browser

Configuration / 0servlet1
<servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup> </load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>!."sp</url-pattern> </servlet-mapping>

!he xml file will be as the form of + [servlet-name]-servlet.xml

#f we do not want to go with default filename as $servlet-name%-servlet.&ml and default location asWeb'ontent/W()-#*+, -ou can customi.e this file name and location b- adding the servlet listener'onte&t/oader/istener in -our web.&ml file as follows0 <web-app...>

<1-------- DispatcherServlet definition goes here-----> .... <conte&t-param> <param-name>conte&t'onfig/ocation</param-name> <param-value>/W()-#*+/HelloWeb-servlet.&ml</param-value> </conte&t-param>

<listener> <listener-class> org.springframework.web.conte&t.'onte&t/oader/istener

</listener-class> </listener> </web-app>

-g / %elloWeb-servlet xml %elloWeb-servlet xml 0beans xmlns23http/44www springframework org4schema4beans3


&mlns0conte&t23http0//www.springframework.org/schema/conte&t3 &mlns0&si23http0//www.w4.org/566 /78/Schema-instance3 &si0schema/ocation23 http0//www.springframework.org/schema/beans http0//www.springframework.org/schema/beans/spring-beans-4.6.&sd http0//www.springframework.org/schema/conte&t http0//www.springframework.org/schema/conte&t/spring-conte&t-4.6.&sd3> <conte&t0component-scan base-package23com.aads3 /> <bean class23org.springframework.web.servlet.view.#nternal9esource:iew9esolver3> <propert- name23prefi&3 value23/W()-#*+/"sp/3 /> <propert- name23suffi&3 value23."sp3 /> </bean> </beans>

!he [servlet-name]-servlet.xml file will be used to create the beans defined+ overriding the definitions of any beans defined with the same name in the global scope !he <context:component-scan... tag will be use to activate Spring MVC annotation scanning capability which allows to make use of annotations like 5Controller and 56e(uestMapping etc !he !nternalReso"rceViewResolver will have rules defined to resolve the view names *s per the above defined rule+ a logical view named hello is delegated to a view implementation located at #$%&-!'(#)sp#hello.)sp

De ining the Controller !


"Controller annotation defines the class as a Spring MVC controller "#e$%estMapping&method ' #e$%estMethod.()*+ is used to declare the printHello*+ method as the controller's default service method to handle %!!" ,-! re(uest 5Controller

56e(uestMapping734hello38 public class %elloController9 56e(uestMapping7method 2 6e(uestMethod ,-!8 public String print%ello7ModelMap model8 9 model add*ttribute73message3+ 3%ello Spring MVC Framework:38; return 3hello3; < < 56e(uestMapping indicates that all handling methods on this controller are relative to the 4hello path =ext annotation 56e(uestMapping7method 2 6e(uestMethod ,-!8 is used to declare the print%ello78method as the controller's default service method to handle %!!" ,-! re(uest 5Controller public class %elloController9 56e(uestMapping7value 2 34hello3+ method 2 6e(uestMethod ,-!8 public String print%ello7ModelMap model8 9 model add*ttribute73message3+ 3%ello Spring MVC Framework:38; return 3hello3; < < !he value attribute indicates the >6& to which the handler method is mapped and the method attribute defines the service method to handle %!!" ,-! re(uest

$S" 77Views8
<html> <head> <title>Hello Spring 8:'</title> </head> <bod-> <h5>;<message=</h5> </bod-> </html>

Spring Web MVC Registration Form example

. web.&ml 0

<servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup> </load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> 2. HelloWeb-servlet.xml <beans &mlns23http0//www.springframework.org/schema/beans3 &mlns0conte&t23http0//www.springframework.org/schema/conte&t3 &mlns0&si23http0//www.w4.org/566 /78/Schema-instance3 &si0schema/ocation23 http0//www.springframework.org/schema/beans http0//www.springframework.org/schema/beans/spring-beans-4.6.&sd http0//www.springframework.org/schema/conte&t http0//www.springframework.org/schema/conte&t/spring-conte&t-4.6.&sd3> <conte&t0component-scan base-package23com.aads3 /> <bean class23org.springframework.web.servlet.view.#nternal9esource:iew9esolver3> <propert- name23prefi&3 value23/W()-#*+/"sp/3 /> <propert- name23suffi&3 value23."sp3 /> </bean> </beans>

4. 'ontroller

import org.springframework.stereot-pe.'ontroller> import import import import import org.springframework.web.bind.annotation.8odel?ttribute> org.springframework.web.bind.annotation.9e@uest8apping> org.springframework.web.bind.annotation.9e@uest8ethod> org.springframework.web.servlet.8odel?nd:iew> org.springframework.ui.8odel8ap>

A'ontroller public class Student'ontroller < A9e@uest8appingBvalue 2 3/student3, method 2 9e@uest8ethod.C(DE public 8odel?nd:iew studentBE < return new 8odel?nd:iewB3student3, 3command3, new StudentBEE> = // 8odel?nd:iewB:iewname,modelname,modelob"ectE A9e@uest8appingBvalue 2 3/addStudent3, method 2 9e@uest8ethod.FGSDE public String addStudentBA8odel?ttributeB3SpringWeb3EStudent student, 8odel8ap modelE < model.add?ttributeB3name3, student.get*ameBEE> model.add?ttributeB3age3, student.get?geBEE> model.add?ttributeB3id3, student.get#dBEE> return 3result3> = = 8odel and :iew 'lass 0 Holder for both 8odel and :iew in the web 8:' framework. *ote that these are entirel- distinct. Dhis class merel- holds both to make it possible for a controller to return both model and view in a single return value.

Class to represent a model and view returned by a handler used by a )ispatcherServlet !he view can take the form of a reference to a View ob?ect+ or a String view name which will need to be resolved by a View6esolver ob?ect !he model is a Map+ allowing the use of multiple data ob?ects keyed by name Command represents whenever we are using the form tags in the html form

ModelAndViewBString view*ame, String model*ame, Gb"ect modelGb"ectE 'onvenient constructor to take a single model ob"ect.

Student."ava file 0

public class Student < private #nteger age> private String name> private #nteger id> public void set?geB#nteger ageE < this.age 2 age>

= public #nteger get?geBE < return age> = public void set*ameBString nameE < this.name 2 name> = public String get*ameBE < return name> = public void set#dB#nteger idE < this.id 2 id> = public #nteger get#dBE < return id> = = H. Student."sp 0 <IAtaglib uri23http0//www.springframework.org/tags/form3 prefi&23form3I> <html> <head> <title>Spring 8:' +orm Handling</title> </head> <bod-> <h5>Student #nformation</h5> <form0form method23FGSD3 action23/HelloWeb/addStudent3> <table> <tr> <td><form0label path23name3>*ame</form0label></td> <td><form0input path23name3 /></td> </tr> <tr> <td><form0label path23age3>?ge</form0label></td> <td><form0input path23age3 /></td> </tr> <tr> <td><form0label path23id3>id</form0label></td> <td><form0input path23id3 /></td> </tr> <tr> <td colspan2353> <input t-pe23submit3 value23Submit3/> </td> </tr> </table> </form0form> </bod-> </html>

9e@uired "ar files

commons-logging-&.-..."ar

org springframework asm-x y . ?ar org springframework beans-x y . ?ar org springframework context-x y . ?ar org springframework core-x y . ?ar org springframework expression-x y . ?ar org springframework web servlet-x y . ?ar org springframework web-x y . ?ar spring-web ?ar

Page Redirection example

Dhe complete same as with the above e&ample. 9edirection is according to controller as

Web'ontroller."ava 0 import org.springframework.stereot-pe.'ontroller> import org.springframework.web.bind.annotation.9e@uest8apping> import org.springframework.web.bind.annotation.9e@uest8ethod> A'ontroller public class Web'ontroller < A9e@uest8appingBvalue 2 3/inde&3, method 2 9e@uest8ethod.C(DE public String inde&BE < return 3inde&3> = A9e@uest8appingBvalue 2 3/redirect3, method 2 9e@uest8ethod.C(DE public String redirectBE < return 3redirect0finalFage3> = A9e@uest8appingBvalue 2 3/finalFage3, method 2 9e@uest8ethod.C(DE

public String finalFageBE < return 3final3> = =

Spring Static pages example :


mvc:reso!rces...."# tag is being used to map static pages. Dhe mapping attribute must be an ?nt pattern that specifies the J9/ pattern of an http re@uests. Dhe location attribute must specif- one or more valid resource director- locations having static pages including images, st-lesheets, KavaScript, and other static content. 8ultiple resource locations ma- be specified using a comma-seperated list of values.

HelloWeb-servlet.&ml 0 <mvc0resources mapping23/pages/!!3 location23/W()-#*+/pages/3 /> <mvc0annotation-driven/>

Spring Web MVC )x,eption -andling )xample !

Spring >ser -xception / 7$ava file8 public class Spring-xception extends 6untime-xception9
private String e&ception8sg> public Spring(&ceptionBString e&ception8sgE < this.e&ception8sg 2 e&ception8sg> = public String get(&ception8sgBE< return this.e&ception8sg> = public void set(&ception8sgBString e&ception8sgE < this.e&ception8sg 2 e&ception8sg> = =

A'ontroller public class Student'ontroller . < A9e@uest8appingBvalue 2 3/student3, method 2 9e@uest8ethod.C(DE public 8odel?nd:iew studentBE < return new 8odel?nd:iewB3student3, 3command3, new StudentBEE> = A9e@uest8appingBvalue 2 3/addStudent3, method 2 9e@uest8ethod.FGSDE A(&ceptionHandlerB<Spring(&ception.class=E public String addStudentB A8odel?ttributeB3HelloWeb3EStudent student, 8odel8ap modelE < ifBstudent.get*ameBE.lengthBE < L E < throw new Spring(&ceptionB3Civen name is too short3E> =else< model.add?ttributeB3name3, student.get*ameBEE> = ifB student.get?geBE < 6 E< throw new Spring(&ceptionB3Civen age is too low3E> =else< model.add?ttributeB3age3, student.get?geBEE> = model.add?ttributeB3id3, student.get#dBEE> return 3result3> = = HelloWeb-servlet.&ml 0 <bean class23org.springframework.web.servlet.handler. Simple8apping(&ception9esolver3> <propert- name23e&ception8appings3> <props> <prop ke-23com.tutorialspoint.Spring(&ception3> (&ceptionFage </prop> </props> </propert-> <propert- name23default(rror:iew3 value23error3/> </bean>

(&ceptionFage."sp 0

<IAtaglib uri23http0//www.springframework.org/tags/form3 prefi&23form3I> <html> <head> <title>Spring 8:' (&ception Handling</title> </head> <bod-> <h5>Spring 8:' (&ception Handling</h5> <h4>;<e&ception.e&ception8sg=</h4> </bod-> </html>

$nternationalisation Applications

messagesMen.properties 0

label.%irstname&'irst (ame label lastname2&ast =ame

label email2-mail label telephone2!elephone label addcontact2*dd Contact label menu2Menu label title2Contact Manager

messagesMde.properties 0 label firstname2Vorname label lastname2Familiename label email2-mail label telephone2!elefon label addcontact2*ddieren @ontakt label title2@ontakt Manager label menu2MenABCDC;

spring-servlet.&ml 0 0bean id23messageSource3 class23org springframework context support 6eloadable6esourceEundleMessageSource31 0property name23basename3 value23classpath0messages3 /> 0property name23default(ncoding3 value23JD+-N3/> 04bean1 0bean id23locale'hange#nterceptor3 class23org springframework web servlet iFGn &ocaleChangeHnterceptor31 0property name23param*ame3 value23lang3 /> 04bean1 0bean id23locale9esolver3 class23org springframework web servlet iFGn Cookie&ocale6esolver31 0property name23default/ocale3 value23en3/> 04bean1 0bean id23handler8apping3 class23org springframework web servlet mvc annotation )efault*nnotation%andlerMapping31 0property name23interceptors3> 0ref bean23locale'hange#nterceptor3 /> 04property1 04bean1 header ?sp / 0I5taglib uri23http/44www springframework org4tags3 prefix23spring3I1 0hJ10spring/message code23label.title3/></h4>

0span st-le23float0 right3> 0a href23Olang2en3>en</a> 0a href23Olang2de3>de</a> 04span1

contact ?sp / 0I5taglib uri23http/44www springframework org4tags3 prefix23spring3I1 0I5taglib uri23http/44www springframework org4tags4form3 prefix23form3I1 0html1 0head1 0title1Spring J MVC Series - Contact Manager04title1 04head1 0body1 0form/form method23post3 action23add'ontact.html3> 0table1 0tr1 0td10form/label path23firstname3><spring0message code23label.firstname3/></form0label></td> 0td10form/input path23firstname3 /></td> 04tr1 0tr1 0td10form/label path23lastname3><spring0message code23label.lastname3/></form0label></td> 0td10form/input path23lastname3 /></td> 04tr1 0tr1 0td10form/label path23lastname3><spring0message code23label.email3/></form0label></td> 0td10form/input path23email3 /></td> 04tr1 0tr1 0td10form/label path23lastname3><spring0message code23label.telephone3/></form0label></td> 0td10form/input path23telephone3 /></td> 04tr1 0tr1 0td colspan2353>

0input t-pe23submit3 value23<spring0message code23label.addcontact3/>3/> 04td1 04tr1 04table1 04form/form1 04body1 04html1

You might also like