1 / 80

CS520 Web Programming Spring – MVC Framework

CS520 Web Programming Spring – MVC Framework. Chengyu Sun California State University, Los Angeles. Roadmap. Request Processing Controllers and validation Transactions and hibernate support Bits and pieces Displaytag Logging Exception Handling JSP pre-compilation Application Deployment.

jcoyle
Télécharger la présentation

CS520 Web Programming Spring – MVC Framework

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS520 Web ProgrammingSpring – MVC Framework Chengyu Sun California State University, Los Angeles

  2. Roadmap • Request Processing • Controllers and validation • Transactions and hibernate support • Bits and pieces • Displaytag • Logging • Exception Handling • JSP pre-compilation • Application Deployment

  3. Understand Request Processing • What happens when the server received a request like http://sun.calstatela.edu/csns/instructor/home.html

  4. Direct Resource Mapping http://cs3.calstatela.edu/~cysun/home.html /home/cysun/public_html/home.html http://cs3.calstatela.edu:8080/cysun/home.jsp /home/cysun/www/home.jsp

  5. URL Mapping in a Java EE Application URL Mapping Request Servlet Servlet Application Server Servlet Response

  6. URL Mapping … • Configured in web.xml • <servlet> and <servlet-mapping> • <welcome-file-list> • <error-page> • Specified in the Servlet Specification

  7. … URL Mapping HTTP Request URL Mapping Matches servlet mapping pattern no match Directory Listing (/) 404 error page welcome file servlet

  8. Request Processing in an MVC Framework Controller URL Mapping Controller URL Mapping Controller Request Front Controller Controller Application Server model Response View

  9. Spring Configuration File(s) • <name>-servlet.xml • <name> must be the same as the <servlet-name> of the DispatcherServlet specified in web.xml • Can have additional bean configurations files • E.g. csns-data.xml, csns-email.xml, csns-acegi.xml ...

  10. More About Configuration Files (Welcome to Metadata Hell!) • Under classpath (/WEB-INF/classes) • hibernate.cfg.xml • ehcache.xml • *.properties • Under /WEB-INF • web.xml • Spring configuration files • server-config.wsdd • Under /META-INF • context.xml

  11. Configuration Files in CSNS ... • All configuration files are under /conf • init target in build.xml • Copy configuration files to the right places • Rename spring-*.xml to ${app.name}-*.xml • Insert some parameter values into the configuration files

  12. ... Configuration Files in CSNS • Advantages • One folder (i.e. /conf) for all metadata files • One file (i.e. build.properties) for all configurable parameters • Reusable for other applications • Disadvantages • Non-standard • “Resource out of sync” error in Eclipse

  13. Controller URL Mapping … • Maps a URL pattern to a controller that will handle the request BeanNameUrlHandlerMapping (default) <bean name="/instructor/home.html" class="csns.spring.controller.instructor.ViewSectionsController">

  14. … Controller URL Mapping … SimpleUrlHandlerMapping <bean id="home" class="csns.spring.controller.HomeController" /> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/home.html">home</prop> </props> </property> </bean>

  15. … Controller URL Mapping • More than one URL handler • <property name=“order” value=“0”/> • No mapping found • 404 error

  16. Request Processing in an MVC Framework Controller URL Mapping URL Mapping Request Front Controller Controller View Resolution model Application Server Response View View

  17. Model and View Examples • AddInstructorController • TakeSurveyController

  18. ModelAndView ModelAndView ( String viewName, String modelName, Object modelObject ) Resolve to a view Attribute in Request scope ModelAndView( String viewName ) .addObject( String modelName, String modelObject ) .addObject( String modelName, String modelObject ) ...

  19. View Resolvers ... • http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/web/servlet/ViewResolver.html

  20. ... View Resolvers • InternalResourceViewResolver for JSP • Support for non-JSP view technologies • Velocity, FreeMarker, JsperReports, XSLT • Views generated by Java classes • BeanNameViewResolver • XmlViewResolver • ResourceBundleViewResolve • Multiple view resolvers • <property name=“order” value=“0”/>

  21. InternalResourceViewResolver Example <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix“ value=".jsp" /> </bean> Prefix + ViewName + Suffix = JSP File

  22. Special Views • Redirect • new ModelAndView( “redirect:” + url ) • E.g. LogoutController • Forward • new ModelAndView( “forward:” + url ) • null • E.g. DownloadController

  23. Interceptors Response Request • A.K.A. Handler Interceptors (as oppose to Method Interceptors) • Similar to Filters in J2EE specification controller view interceptors interceptors

  24. About Interceptors • Implement interceptors • HnndlerInterceptor • HandlerInterceptorAdapter • Configure interceptors • In URL mapping bean <bean id="urlMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"> <property name="interceptors"> <list> <ref bean="openSessionInViewInterceptor" /> </list> </property> </bean>

  25. Excercises • csns/instructor/viewSubmissions.html?assignmentId=1234567

  26. Recap request web.xml URL Mapping 404 error page welcome page DispatcherServlet Controller URL Mapping Interceptor(s) View Controller View Resolver Interceptor(s) Spring

  27. Roadmap • Request Processing • Controllers and validation • Transactions and hibernate support • Bits and pieces • Displaytag • Logging • Exception Handling • JSP pre-compilation • Application Deployment

  28. Controller Interface • org.springframework.web.servlet.mvc.Controller - http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/web/servlet/mvc/Controller.html ModelAndView handleRequest ( HttpServletRequest request, HttpServletResponse response )

  29. Select A Controller ParameterizableViewController Simply display a view, i.e. the request does not need to be processed Controller (interface) AbstractController do not use request parameters or use only simple parameters request parameters can be mapped to an object; can use validators to validate request parameters BaseCommandController AbstractCommandController AbstractFormController SimpleFormController Handles form input AbstractWizardFormController Handles multi-page form input

  30. Example: Find Email by Name • Given the first name and/or the last name of a user, display the user’s email address First name: Name Email Last name: sun Sun,Chengyu cysun@cs Sun,Steve stesun@cs search

  31. So What Do We Need to Do? Controller URL Mapping URL Mapping Request Front Controller Controller View Resolution model Application Server Response View

  32. Models and Views • Models • UserDao.getUsersByName()  List<User> • Views • searchEmail.jsp • displayEmail.jsp

  33. Controllers • ParameterizableViewController + AbstractController • SimpleFormController

  34. Command Object HTML Form Command Object • Any class can be used as a command class in Spring • vs. ActionForm in Struts Binding public class User { String username; String password; … } Usename: Password: Login

  35. Simple Form Handling • The controller needs to handle two cases: • Display form • Process input data Handle first request: Handle input: Create a command object and expose the object as a page scope variable Bind the request parameters to the command object Display the form view Call controller.onSubmit()

  36. org.springframework.validation Validator Errors Validation Handle input: Bind the request parameters to the command object fail Validator(s) Form view success Call controller.onSubmit()

  37. messages.properties • <name,value> pairs • A single place for output messages • Easy to change • I18N • Need to declare a messageSource bean in Spring configuration file • Can be used by <fmt> tags in JSTL

  38. Spring’s form Tag Library • Documentation - http://static.springframework.org/spring/docs/2.5.x/reference/view.html#view-jsp-formtaglib • Tag reference –http://static.springframework.org/spring/docs/2.0.x/reference/spring-form.tld.html • Example • admin/survey/addQuestion.jsp

  39. Limitation of Spring Validation • Server-side only • Takes lots of coding for anything other than checking for empty/white spaces

  40. Commons-Validator • http://commons.apache.org/validator/ • Provide both declarative and programmatic validation • Provide both client-side and server-side validation • Automatically generate cross-browser JavaScript code for client-side validation

  41. Commons-Validator Declarative Validation Example <form name=“fooForm"> <field property=“name“depends="required"> <arg0 key=“fooForm.definition"/> </field> <fieldproperty="difficultyLevel" depends="required, integer"> <arg0 key=“fooForm.difficultyLevel"/> </field> </form>

  42. Commons-Validator Routines • http://commons.apache.org/validator/api-1.3.1/org/apache/commons/validator/routines/package-summary.html • Independent of the declarative validation framework • A set of methods to validate • Date and time • Numeric values • Currency • ...

  43. Use Commons-Validator with Spring • Use the validation routines • Use declarative validation • Spring Modules - https://springmodules.dev.java.net/

  44. Recap • Controller • Choose the right controller • Configure controller in Spring bean configuration file • Validation • Validator • message.properties and Spring form tag library • Commons-Validator

  45. Roadmap • Request Processing • Controllers and validation • Transactions and hibernate support • Bits and pieces • Displaytag • Logging • Exception Handling • JSP pre-compilation • Application Deployment

  46. Programmatic vs. Declarative Transaction Management Programmatic: Declarative: <transaction> <method> saveUser </method> </transaction> void saveUser( User u ) { transaction.start(); … transaction.end(); }

  47. Spring Transaction Managers • JDBC • Hibernate • V3 • Before V3 • JTA • Object-Relational Bridge (ORB)

  48. Configure Hibernate Transaction Manager Hibernate Transaction manager Session Factory Data Source

  49. Transaction Manager in CSNS • /conf/spring-data.xml

  50. Connection Pooling • Connection pooling • DBCP • http://jakarta.apache.org/commons/dbcp/configuration.html

More Related