Spring Web MVC - PowerPoint PPT Presentation

About This Presentation
Title:

Spring Web MVC

Description:

Title: PowerPoint Presentation Last modified by: AlinaD Created Date: 1/1/1601 12:00:00 AM Document presentation format: On-screen Show Other titles – PowerPoint PPT presentation

Number of Views:647
Avg rating:3.0/5.0
Slides: 77
Provided by: ltnLvaps
Category:
Tags: mvc | spring | web

less

Transcript and Presenter's Notes

Title: Spring Web MVC


1
Spring Web MVC
2
Ievads
  • Spring ir atklata koda Java/J2EE aplikaciju
    ietvars
  • Viens no interesantakiem komponentiem ir Spring
    Web MVC

3
Web aplikaciju uzdevumi
  • Svarigie uzdevumi, kuri ir jaatrisina izstradajot
    web aplikaciju
  • Stavoklu parvaldiba (state management)
  • Darba plusma (workflow)
  • Validacija
  • Spring web ietvars ir uzprojektets, lai palidzet
    izstradatajiem risinat Å¡is problemas

4
Model-View-Controller Pattern
  • Model-View-Controller (MVC) ir arhitekturas
    paraugs (aprakstits 1979. gada, Smalltalk valoda)
  • Pamata merkis atdalit datus (Model) no
  • lietotaja interfeisa (View)
  • MVC atrisina
  • problemu ievieÅ¡ot
  • starpnieka komponenti - kontrolieri (Controller)

5
Model-View-Controller Pattern
  • Model - Represents enterprise data and the
    business rules.
  • View - Renders the contents of a model. Accesses
    enterprise data through the model and specifies
    how that data should be presented.
  • Controller - Translates interactions
  • with the view (button clicks,
  • menu selections) into actions to be
  • performed by the model
  • (activating processes, changing
  • the state of the model).

6
Spring MVC
  • Spring MVC sastav no vairakiem komponentiem,
    starp kuriem notiek sadarbiba apstradajot klienta
    pieprasijumu

7
Pieprasijuma dzives cikls (1)
  • Klients suta pieprasijumu, kurÅ¡ tiek nodots
    DispatcherServlet komponentam
  • Visi pieprasijumi vienmer tiek nodoti vienam
    servletam,
  • kuru sauc par
  • priekÅ¡ejo kontrolieri
  • (front controller)

8
Pieprasijuma dzives cikls (2)
  • Komponents, kurÅ¡ atbild par pieprasijuma apstradi
    ir Controller
  • Lai nolemt kuram kontrolierim atdot
  • pieprasijumu,
  • DispatcherController
  • izmanto
  • HandlerMapping
  • komponentus
  • HandlerMapping
  • URL piesaistiÅ¡ana kontrolieriem

9
Pieprasijuma dzives cikls (3-4)
  • Kad DispatcherServlet nolemj par kontroliera
    objektu, tad parsuta tam pieprasijumu, lai
    kontrolieris izpilda biznesa logiku
  • Pec darba pabeigÅ¡anas Controller atgriež
    ModelAndView
  • objektu
  • ModelAndView satur
  • View objektu vai
  • skata logisko vardu

10
Pieprasijuma dzives cikls (5)
  • Ja ModelAndView objekts satur skata logisko
    vardu, tad DispatcherServlet izmanto ViewResolver
    komponenti
  • ViewResolver
  • atrod atbilstoÅ¡u
  • View objektu,
  • lai attelot atbildi
  • klientam

11
Pieprasijuma dzives cikls (6)
  • Visbeidzot, DispatcherServlet atdod pieprasijumu
    tam View objektam, uz kuru norada ModelAndView
  • View objekts ir
  • atbildigs par
  • pieprasijuma
  • atbildes atgrieÅ¡anu
  • un paradiÅ¡anu
  • klientam

12
Spring MVC Sequence Diagram
13
Front Controller
  • At the heart of Spring MVC is DispatcherServlet,
    a servlet that functions as front controller
  • A front controller is a common web-application
    pattern where a single servlet delegates
    responsibility for a request to other components
    of an application to perform the actual processing

14
DispatcherServlet config
  • Jakonfigure web aplikacijas web.xml faila

ltservletgt ltservlet-namegttraininglt/servlet-namegt
ltservlet-classgtorg.springframework.web.servlet.D
ispatcherServlet lt/servlet-classgt
ltload-on-startupgt1lt/load-on-startupgt lt/servletgt
  • Nakamais solis ir nodefinet servlet mapping

ltservlet-mappinggt ltservlet-namegttraininglt/servlet
-namegt lturl-patterngt.htmlt/url-patterngt lt/servlet
-mappinggt
15
DispatcherServlet context
  • WebApplicationContext tiek ieladets no faila
  • training-servlet.xml
  • kurÅ¡ atrodas direktorija WEB-INF
    (lidzigi web.xml failam)
  • Ir iespejams ari sadalit
  • konfiguraciju starp
  • vairakiem failiem

16
Vienkaršas Web lapas izveidošana
  • NepiecieÅ¡amie soli, lai izveidot web lapu ar
    Spring MVC
  • Uzrakstit kontroliera klasi, kas izpildis biznesa
    logiku
  • Iekonfiguret kontrolieri DispatcherServlet
    konteksta konfiguracijas faila (training-servlet.x
    ml)
  • Iekonfiguret view resolver, kurÅ¡ piesaistis
    kontrolieri pie JSP
  • Uzrakstit JSP, kas attelos lapu klientam

17
Kontroliera izveidošana
public class HomeController implements Controller
public ModelAndView handleRequest(HttpServl
etRequest request,
HttpServletResponse response) throws Exception
return new ModelAndView("home", "message",
greeting) private String greeting
public void setGreeting(String greeting)
this.greeting greeting
  • Nodarbojas ar pieprasijuma apstradaÅ¡anu
  • Pamata metodes signatura ir lidziga servleta
    service() metodei
  • Atgriež ModelAndView objektu

18
Kontroliera konfigurešana
  • Kontrolieri ir jaieraksta DispatcherServlet
    konteksta konfiguracijas faila

ltbean name"/home.htm" class"com.springinacti
on.training.mvc.HomeController"gt ltproperty
name"greeting"gt ltvaluegtWelcome to Spring
Training!lt/valuegt lt/propertygt lt/beangt
  • The default handler mapping is BeanNameUrlHandlerM
    apping, which uses the base name as the URL
    pattern
  • When a request comes with a URL that ends with
    /home.htm, DispatcherServlet will dispatch the
    request to HomeController

19
View Resolver deklarešana
  • View resolver darbs ir pec skata logiska varda
    (kurš ir atgriezts ModelAndView objekta) atrast
    pašu skatu
  • Viens no variantiem ir izmantot skata vardu ka
    JSP faila vardu

ltbean id"viewResolver" class"org.springframework
.web. servlet.view.InternalResourceViewResolver"gt
ltproperty name"prefix"gt
ltvaluegt/WEB-INF/jsp/lt/valuegt lt/propertygt
ltproperty name"suffix"gt
ltvaluegt.jsplt/valuegt lt/propertygt lt/beangt
home ? /WEB-INF/jsp/home.jsp
20
JSP izveidošana
  • Pedejais kas palika izveidot paÅ¡u JSP

lthtmlgt ltheadgtlttitlegtSpring Training,
Inc.lt/titlegtlt/headgt ltbodygt lth2gtmessagelt/h2gt lt/b
odygt lt/htmlgt
  • Failu ir janosauc par home.jsp un ir janoliek
    zem /WEB-INF/jsp/ direktorijas

21
Kopsavilkums
22
HandlerMapping
  • Tipiski piesaista specifisku kontrolieri pie URL
    adreses parauga
  • Spring piedava cetras noderigas HandlerMapping
    implementacijas
  • BeanNameUrlHandlerMapping
  • SimpleUrlHandlerMapping
  • CommonsPathMapHandlerMapping

23
BeanNameUrlHandlerMapping
  • Piesaista URL adresi pie kontroliera, kurÅ¡ ir
    registrets konfiguracijas faila ar tadu pašu
    vardu
  • e.g. /simple.htm maps to a bean named
    /simple.htm
  • Ir jaizmanto name atributu, jo / nav atlauts
    XML atributa id

ltbean class"org.springframework.web.servlet.
handler.BeanNameUrlHandlerMapping"/gt ltbean
name"/simple.htm" class"com.mvc.web.Si
mpleController"gt . . . lt/beangt
24
SimpleUrlHandlerMapping
  • Pats visparigs veids ka piesaistit pieprasijuma
    URLus kontrolieriem
  • Tiek konfigurets ka saraksts no name/value pariem
    (URL/kontrolieru vards)

ltbean id"simpleUrlMapping" class"org.springframe
work.web .servlet.handler.SimpleUrlHandler
Mapping"gt ltproperty name"mappings"gt ltpropsgt
ltprop key"/listCourses.htm"gtlistCoursesController
lt/propgt ltprop key"/register.htm"gtregisterStuden
tControllerlt/propgt ltprop key"/displayCourse.htm
"gtdisplayCourseControllerlt/propgt lt/propsgt
lt/propertygt lt/beangt
25
CommonsPathMapHandlerMapping
  • Considers source-level metadata placed in a
    controllers source code to determine the URL
    mapping
  • Need to set up build to
  • include the Commons
  • Attributes compiler so
  • that the attributes will
  • be compiled into
  • application code

ltbean id"urlMapping" class"org.springframework.w
eb. servlet.handler.metadata.CommonsPathMapHandle
rMapping"/gt
/ _at__at_org.springframework.web.servlet.
handler.commonsattributes.PathMap( "/displayCours
e.htm") / public class DisplayCourseController ex
tends AbstractCommandController
26
Multiple handler mappings
  • Ir iespejams deklaret vairakus handler mappings
    viena aplikacija
  • Handler mapping klases implemente Springa
    Ordered interfeisu
  • Var uzstadit order ipaÅ¡ibu, lai noradit izpildes
    kartibu attieciba uz citiem handler mapping
    komponentiem

27
Multiple handler mappings
  • ltbean id"beanNameUrlMapping" class"org.springfra
    mework.web.
  • servlet.handler.BeanNameUrlHandlerMapping"gt
  • ltproperty name"order"gtltvaluegt1lt/valuegtlt/propert
    ygt
  • lt/beangt
  • ltbean id"simpleUrlMapping" class"org.springframe
    work.web.
  • servlet.handler.SimpleUrlHandlerMapping"gt
  • ltproperty name"order"gtltvaluegt0lt/valuegtlt/propert
    ygt
  • ltproperty name"mappings"gt
  • lt/propertygt
  • lt/beangt

28
Kontrolieri
  • Ja DispatcherServlet ir Spring MVC sirds, tad
    kontrolieri ir smadzenes

29
Kontrolieru hierarhija
  • Spring piedava
  • bagatu kontrolieru
  • hierarhiju
  • Hierarhijas virsotne
  • atrodas Controller
  • interfeiss
  • Parasti ir jaizmanto
  • kadu no
  • implementacijas
  • apakÅ¡klasem

30
AbstractController
  • Pats vienkarÅ¡akais kontrolieris

public class SampleController extends
AbstractController public ModelAndView
handleRequestInternal( HttpServletRequest
request, HttpServletResponse response)
throws Exception return new
ModelAndView( "hello, message, "Hello
World!")
31
ModelAndView objekts
  • Iekapsule skatu un modela datus, kurus skats
    attelos
  • Modelis ir realizets ka java.util.Map
  • Erts konstruktors viena modela objekta gadijumam
  • ModelAndView(
  • String viewName,
  • String modelName,
  • Object modelObject)

32
ModelAndView objekts
  • Ir iespejams ari pievienot modelim vairakus
    objektus

public ModelAndView handleRequestInternal(
HttpServletRequest request,
HttpServletResponse response) throws Exception
ModelAndView mav new ModelAndView(welcom
e") mav.addObject("message1", Welcome!")
mav.addObject("message2", "Nice to see you!")
return mav
33
Parametru apstrade
  • Web pieprasijums bieži satur vienu vai vairakus
    parametrus

ltform action"/login" method"POST"gt Login
ltinput idlogin" name"login"/gt Password
ltinput id"password" name"password"
type"password"/gt ltinput type"submit"
value"Login"/gt lt/formgt
Kada veida varetu pieklut parametriem kontroliera
koda???
34
Risinajums
  • Varetu izmantot AbstractController un nolasit
    parametrus no HttpServletRequest

public ModelAndView handleRequestInternal(
HttpServletRequest request,
HttpServletResponse response) throws Exception
String login request.getParameter("login"
) String pass request.getParameter(
"password") . . .
Spring piedava ertaku iespeju!
35
AbstractCommandController
  • Automatiski ieraksta parametrus specialaja
    komandas objekta (command object)
  • Ir iespeja pievienot validatoru, lai nodroÅ¡inat
    to, ka parametri ir pareizi
  • Galvena izpildes metode
  • handle(
  • HttpServletRequest request,
  • HttpServletResponse response,
  • Object command,
  • BindException errors)

36
AbstractCommandController
  • public class DisplayCourseController extends
    AbstractCommandController
  • public DisplayCourseController()
  • setCommandClass(DisplayCourseCommand.class)
  • protected ModelAndView handle(HttpServletRequest
    request,
  • HttpServletResponse response, Object command,
  • BindException errors) throws Exception
  • DisplayCourseCommand displayCommand
  • (DisplayCourseCommand) command
  • Course course courseService.getCourse(displ
    ayCommand.getId())
  • return new ModelAndView("courseDetail",
    "course", course)

37
Command Object
  • A command object is a bean that is meant to hold
    request parameters for easy access

public class DisplayCourseCommand private
Integer id public void setId(Integer id)
this.id id public Integer getId()
return id
  • Spring will attempt to match any parameters
    passed in the request to properties in the
    command object

38
Parskats
39
Formu apstrade
  • Tipiska web aplikacija satur vismaz vienu formu
  • Lietotajs aizpilda formu un aizsuta to
  • Dati tiek nosutiti serverim
  • Kad datu apstrade ir pabeigta, tad lietotajs
    sanem vienu no variantiem
  • Lapa ar veiksmigas izpildes pazinojumu
  • Formas lapa ar kludu pazinojumiem

Kada veida varetu to realizet???
40
Risinajums
  • Izmantot AbstractController formas atteloÅ¡anai
  • Izmantot AbstractCommandController formas
    apstradei
  • Trukums vajag uzturet divus dažadus
    kontrolierus, kuri kopa nodarbojas ar viena
    uzdevuma risinašanu

41
SimpleFormController
  • Formu kontroliera funkcionalitate
  • Attelo formu uz HTTP GET pieprasijuma
  • Apstrada formu uz HTTP POST pieprasijuma
  • Ja notiek kluda, tad atkartoti parada formu

public class RegisterStudentController extends
SimpleFormController public RegisterStudentCont
roller() setCommandClass(Student.class) p
rotected void doSubmitAction(Object
command) throws Exception Student student
(Student) command studentService.enrollStudent(
student)
42
SimpleFormController config
  • Kontrolieris ir uzprojektets tada veida, lai pec
    iespejas vairak atdalit skatu detalas no
    kontroliera koda

ltbean id"registerStudentController"
class"com.springinaction. training.mvc.Registe
rStudentController"gt ltproperty
name"formView"gt ltvaluegtnewStudentFormlt/valuegt
lt/propertygt ltproperty name"successView"gt ltvalu
egtstudentWelcomelt/valuegt lt/propertygt . .
. lt/beangt
HTTP GET
  • Ja ir nepiecieÅ¡ams aizsutit datus skatam, tad
    vajag izmantot onSubmit() metodi

43
Formu validacija
  • Viens no svarigiem uzdevumiem ir formas datu
    validacija
  • Par validaciju atbild sekojoÅ¡ais interfeiss

public interface Validator void
validate(Object obj, Errors errors) boolean
supports(Class clazz)
  • Implementejot Å¡i interfeisa validate() metodi
    vajag parbaudit objekta atributu vertibas un
    noraidit nepareizas vertibas izmantojot Errors
    objektu

44
Validatora registrešana
  • Validatoru vajag piesaistit kontrolierim
    konfiguracijas faila

ltbean id"registerStudentController"
class"com.springinaction.training.mvc.
RegisterStudentController"gt ltproperty
name"validator"gt ltbean class"com.springinac
tion.training. mvc.StudentValidator"/gt
lt/propertygt lt/beangt
45
Wizard (daudzekranu) formas
  • Uzdevums realizet aptaujas formu ar 40
    jautajumiem

Kada veida varetu to realizet???
  • Variants izmantot SimpleFormController,
    izvietot visus jautajumus viena lapa
  • Bet tas nav erti lietotajam!

46
Wizard formas
  • Spring piedava kontrolieri, kas atbild par secigu
    virzišanos cauri vairakam lapam
  • AbstractWizardFormController
  • Lidzigs parastai formai, bet ir iespejams validet
    datus pa dalam (katra ekrana savu dalu)
  • Formas apstrade parasti notek paÅ¡as beigas
  • Ir iespeja visu procesu atcelt (cancel) jebkura
    bridi

47
Wizard formas kontrolieris
  • public class FeedbackWizardController
  • extends AbstractWizardFormController
  • public FeedbackWizardController()
  • setCommandClass(FeedbackSurvey.class)
  • protected ModelAndView processFinish(
  • HttpServletRequest request,
  • HttpServletResponse response, Object command,
  • BindException errors) throws Exception
  • FeedbackSurvey feedback (FeedbackSurvey)
    command
  • feedbackService.submitFeedback(feedback)
  • return new ModelAndView("thankyou")

48
Wizard formas konfigurešana
  • Formas kontroliera konfigureÅ¡ana

ltbean id"feedbackController" class"com.springina
ction. training.mvc.MyWizardController"gt ltprope
rty name"pages"gt ltlistgt
ltvaluegtgenerallt/valuegt ltvaluegtinstructorlt/
valuegt ltvaluegtcourselt/valuegt
lt/listgt lt/propertygt lt/beangt
  • Å eit tiek definetas visas lapas

49
Wizard formas lapas
  • Pa lapam var parvietoties ierakstot pieprasijuma
    parametru ar vardu "_targetX", kur X ir lapas
    numurs

ltform method"POST" action"feedback.htm"gt ltinpu
t type"submit" value"Back" name"_target1"gt
ltinput type"submit" value"Next"
name"_target3"gt lt/formgt
50
Wizard formas finish/cancel
  • Formas pabeigÅ¡ana - tiks izsaukta metode
    processFinish()

ltinput type"submit" value"Finish"
name"_finish"gt
  • Formas atcelÅ¡ana - tiks izsaukta metode
    processCancel()

ltinput type"submit" value"Cancel"
name"_cancel"gt
51
Wizard formas validacija
  • Formas komandas objekts tiek validets pa lapam

protected void validatePage( Object command,
Errors errors, int page) FeedbackSurvey
feedback (FeedbackSurvey) command FeedbackValid
ator validator (FeedbackValidator)
getValidator() if(page 0)
validator.validateEmail(feedback.getEmail(),
errors)
52
Vairaku darbibu apstrade
  • Visi lidz Å¡im apskatitie kontrolieri pildija kadu
    vienu uzdevumu
  • Veidot vairakus kontrolierus lai pildit lidzigus
    uzdevumus nav isti racionali
  • Piemeram, vajag attelot kursu sarakstu dažados
    variantos
  • Nesakartota veida
  • Sakartoti pec datuma
  • Sakartoti pec nosaukuma

Kada veida varetu to realizet???
53
MultiActionController
  • public class ListCoursesController
  • extends MultiActionController
  • public ModelAndView coursesUnsorted(
  • HttpServletRequest request, HttpServletResponse
    response)
  • . . .
  • public ModelAndView coursesSortedByStartDate(
  • HttpServletRequest request, HttpServletResponse
    response)
  • . . .
  • public ModelAndView coursesSortedByName(
  • HttpServletRequest request, HttpServletResponse
    response)
  • . . .

54
Metodes varda noteikšana
  • Pec noklusejuma metodes vards tiek noteikts
    izmantojot URL sastavdalu
  • http///coursesUnsorted.htm ?
    coursesUnsorted()
  • http///coursesSortedByStartDate.htm ?
    coursesSortedByStartDate()
  • http///coursesSortedByName.htm ?
    coursesSortedByName()

55
Metodes varda noteikšana
  • Ir pieejami ari citi varianti
  • ParameterMethodNameResolver - Resolves the
    execution method name based on a parameter in the
    request
  • PropertiesMethodNameResolver -Resolves the name
    of the execution method by consulting a list of
    key/value pairs

56
Parskats
57
ThrowawayController
  • Nav Controller hierarhijas dala
  • Netiek izmantots HTTP pieprasijums vai komandas
    objekts
  • Parametri tiek ierakstiti tieÅ¡i kontrolieri
  • Ir noderigi, kad nav modela objekta, kuru varetu
    izmantot
  • AtÅ¡kiriba no citiem kontrolieriem, nav singleton

public interface ThrowawayController
ModelAndView execute() throws Exception
58
ThrowawayController
  • public class DisplayCourseController
  • implements ThrowawayController
  • private Integer id
  • public void setId(Integer id) this.id id
  • public ModelAndView execute() throws Exception
  • Course course courseService.getCourse(id)
  • return new ModelAndView(
  • "courseDetail", "course", course)

59
Interceptors
  • Iespeja pievienot papildus funkcionalitati pirms
    un pec pieprasijuma
  • Satur divas interception metodes
  • preHandle un postHandle
  • Satur vienu callback metodi
  • afterCompletion
  • Tiek piesaistits kontrolieru kopai kopa ar
    HandlerMapping

60
Piemers Interceptor config
  • ltbeansgt
  • ltbean id"handlerMapping" class"org.springfra
    mework.web.
  • servlet.handler.SimpleUrlHandlerMapping"gt
  • ltproperty name"interceptors"gt
  • ltlistgt
  • ltref bean"officeHoursInterceptor"
    /gt
  • lt/listgt
  • lt/propertygt
  • ltproperty name"mappings"gt
  • ltvaluegt
  • /.formeditAccountFormController
  • lt/valuegt
  • lt/propertygt
  • lt/beangt
  • ltbean id"officeHoursInterceptor"
  • class"samples.TimeBasedAccessIntercepto
    r"gt
  • ltproperty name"openingTime" value"9"/gt
  • ltproperty name"closingTime" value"18"/gt

61
Piemers Interceptor kods
  • public class TimeBasedAccessInterceptor extends
    HandlerInterceptorAdapter
  • . . .
  • public boolean preHandle(HttpServletRequest
    request,
  • HttpServletResponse response,
  • Object handler) throws Exception
  • Calendar cal Calendar.getInstance()
  • int hour cal.get(HOUR_OF_DAY)
  • if (openingTime lt hour lt closingTime)
  • return true
  • else
  • response.sendRedirect(
  • "http//host.com/outsideOfficeHours.html")
  • return false

62
View Resolving
  • A view is a bean that renders results to the user
  • Spring MVC consults view resolvers when trying to
    determine which View bean to use

63
ViewResolver implementacijas
  • Spring piedava cetras pamata ViewResolver
    interfeisa implementacijas
  • InternalResourceViewResolver
  • Resolves logical view names into View objects
    that are rendered using template file resources
    (such as JSPs and Velocity templates)
  • BeanNameViewResolver -
  • Resolves logical view names into View beans in
    the DispatcherServlets application context

64
ViewResolver implementacijas
  • ResourceBundleViewResolver
  • Mappings are contained within a properties file
  • Supports internationalization
  • XmlViewResolver
  • Mappings are contained within a XML file that is
    separate from the DispatcherServlets application
    context
  • VelocityViewResolver
  • FreeMarkerViewResolver

65
View klases
  • Spring piedava sekojoÅ¡as skatu apakÅ¡klases
  • JstlView
  • Attelo viewName par JSP lapu, kura uzstaditi ari
    JSTL tagu bibliotekam vajadzigie mainigie,
    piemeram, lokalizacija.
  • RedirectView
  • Veic HTTP Redirect
  • VelocityLayoutView, VelocityToolboxView,
    VelocityView
  • Velocity skati ar vai bez papildu objektiem, ko
    konfigure toolbox.xml
  • FreeMarkerView

66
Internacionalizacija
  • Spring dod iespeju automatiski izveleties
    zinojumu tekstus izmantojot lietotaja lokali
  • DispatcherServlet izmanto LocaleResolver lai
    noteikt klienta lokali
  • AcceptHeaderLocaleResolver
  • izmantot HTTP "Accept-language" hederi lokales
    atrašanai
  • CookieLocaleResolver
  • izmantot cookies lokales atraÅ¡anai
  • SessionLocaleResolver
  • lokale liek glabata sesija

67
Internacionalizacija
  • Lokales izmainas funkcionalitatei var izmantot
    klasi LocaleChangeInterceptor, to ir japieliek
    klat kadam HandlerMapping
  • Visbeidzot, teksta zinojumus ir jaieraksta failos
    zem /WEB-INF/classes/
  • messages_en.properties
  • messages_de.properties
  • utml
  • JSP lapa zinojumus var ielikt izmantojot tagu
  • ltfmfmessage key"ltmsg_namegt"gt
  • ltfmfmessage keyhello"gt

msg_namemsg_text greetingsHello! trueYes false
No
68
Springa temas
  • Viegli konfigurejamas un izpildes laika
    nomainamas aplikacijas "adas

69
Springa temas
  • Tema (theme) ir statisko resursu kolekcija, kas
    ietekme aplikacijas vizualo stilu
  • style sheets (css), images
  • ResourceBundleThemeSource ielade properties
    failus no classpath saknes
  • /WEB-INF/classes/
  • Daudz lidzibas ar internacionalizacijas
    konfigurešanu

70
Springa temas
  • Properties faila piemers

styleSheet/themes/cool/style.css
background/themes/cool/img/coolBg.jpg
  • JSP lapa ir jaizmanto ltspringthemegt tagu

lt_at_ taglib prefix"spring" uri"http//www.sprin
gframework.org/tags"gt lthtmlgt ltheadgt
ltlink rel"stylesheet" href"ltspringtheme
code"styleSheet"/gt" type"text/css"/gt
lt/headgt ltbody background"ltspringtheme
code"background"/gt"gt ... lt/bodygt lt/htmlgt
71
Failu augšupielade
  • Spring piedava failu augÅ¡upielades
    funkcionalitati (multipart file upload)
  • Atbalsta CommonFileUpload un COS FileUpload

lth1gtPlease upload a filelt/h1gt ltform method"post"
action"upload.form" enctype"multipart/form-dat
a"gt ltinput type"file" name"file"/gt ltinput
type"submit"/gt lt/formgt
ltbean id"multipartResolver class"org.springfram
ework. web.multipart.commons.CommonsMultipartRes
olver"gt ltproperty name"maxUploadSize"
value"100000"/gt lt/beangt
72
Iznemumu apstrade
  • Viena no Springa ipatnibam - vairums iznemumu ir
    RuntimeException apakštipi, tos nevajag metodes
    kert vai deklaret
  • Ir piedavata iespeja apstradat negaiditas kludas
  • SimpleMappingExceptionResolver
  • Iespeja piesaistit skatu iznemuma klasei
    konfiguracijas faila
  • HandlerExceptionResolver
  • Interfeiss, kuru vajag implementet, lai apstradat
    kontrolieru kludas

73
SimpleMappingExceptionResolver
  • ltbean id"exceptionResolver" class"org.springfra
    mework.web.
  • servlet.handler.
  • SimpleMappingExceptionResolver"gt
  • ltproperty name"exceptionMappings"gt
  • ltpropsgt
  • ltprop key"java.lang.Exception"gt
  • friendlyError
  • lt/propgt
  • lt/propsgt
  • lt/propertygt
  • lt/beangt

74
Countries piemers
  • Spring piemeru, kuru var palaist un apskatities
    kodu var atrast zem
  • \spring-framework-2.0.6\samples\countries\
  • Special Spring MVC features
  • paged list navigation
  • locale and theme switching
  • localized view definitions
  • page composition through
  • view definitions
  • generation of PDF and
  • Excel views

75
Resursi
  • Spring Home
  • http//www.springframework.org
  • C. Walls, R.Breidenbach. Spring in Action
    http//www.manning.com/walls2/
  • Spring Web MVC Framework http//www.springframewor
    k.org/docs/reference/mvc.html
  • Spring MVC step-by-step Tutorial
  • http//www.springframework.org/docs/MVC-step-by-s
    tep/Spring-MVC-step-by-step.html

76
Resursi
  • Model-View-Controller pattern by Sun
    http//java.sun.com/blueprints/patterns/MVC.html
  • Core J2EE Patterns - Front Controller
    http//java.sun.com/blueprints/corej2eepatterns/Pa
    tterns/FrontController.html
Write a Comment
User Comments (0)
About PowerShow.com