1 / 45

CS520 Web Programming Spring – MVC Framework

Explore the MVC framework, web flow, controllers, validation, transactions, and more. Understand URL mapping, view resolution, and interceptors in web applications. Includes servlet configuration, Spring roadmap, and controller hierarchy.

Download Presentation

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 • Web flow • Controllers and validation • Transactions and hibernate support • Bits and pieces • Tomcat server setup • Context, data source, and connection pooling • Creating WAR files • JSP pre-compilation • Displaytag

  3. Understand Web Flow • What happens when the server received a request like http://cs3.calstatela.edu:8080/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. Web Flow of Simple J2EE Application URL Mapping Request Servlet Servlet Application Server Servlet Response

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

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

  8. Web Flow of a 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 • Optional • csns-data.xml • csns-service.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 • csns-servlet.xml, csns-data.xml, csns-service.xml • server-config.wsdd • Under /META-INF • context.xml

  11. Controller URL Mapping … • Maps a URL pattern to a controller that will handle the request BeanNameUrlHandlerMapping (default) <bean id="index" name=“/index.html /public/*index.html” class="evelyn.spring.controller.IndexController" />

  12. … Controller URL Mapping … SimpleUrlHandlerMapping <bean id="index" class="evelyn.spring.controller.IndexController" /> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/index.html">index</prop> <prop key="/public/*index.html">index</prop> </props> </property> </bean>

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

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

  15. Web Flow of a MVC Framework Controller URL Mapping URL Mapping Request Front Controller Controller View Resolution model Application Server Response View View

  16. View Resolvers • URL-based resolvers • InternalResourceViewResolver for JSP • VelocityViewResolver for Velocity • View classes resolvers • BeanNameViewResolver • XmlViewResolver • ResourceBundleViewResolver • Multiple resolvers • <property name=“order” value=“1”/>

  17. Special Views • Redirect • new ModelAndView( “redirect:” + url ) • Forward • new ModelAndView( “forward:” + url )

  18. Interceptors Response Request • Similar to Filters in J2EE specification • HandlerInterceptorAdapter • Example: AuthorizationInterceptor controller view interceptors interceptors

  19. Recap request Servlet Specification URL Mapping 404 error page welcome page DispatcherServlet Controller URL Mapping Interceptor(s) View Controller View Resolver Interceptor(s) Spring

  20. Roadmap • Web flow • Controllers and validation • Transactions and hibernate support • Bits and pieces • Tomcat server setup • Context, data source, and connection pooling • Creating WAR files • JSP pre-compilation • Displaytag

  21. Controller Class Hierarchy • org.springframework.web.servlet.mvc • Controller

  22. Select A Controller 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

  23. 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

  24. 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()

  25. Controllers in CSNS • AbstractController • Home, Logout, Download, DownloadZip • View, Grade, EmailGrades, … • SimpleFormController • Account, Register, ResetPassword • DropStudents • AbstractFormController • EmailStudents • ParameterizedViewController • Index, Login

  26. Controller Example • Delete an assignment • Create a controller • Create a view (JSP) • Add the controller to spring-servlet.xml

  27. Exception Handling • An Exception resolver catches all exceptions thrown by controllers and chooses the proper view to display • Examples • SimpleMappingExceptionResolver • ExceptionResolver in CSNS

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

  29. 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

  30. Display Errors • Spring Tag Library • http://static.springframework.org/spring/docs/1.2.5/taglib/ • <spring:hasBindErrors> • A few other useful tags • Example: account.jsp

  31. Limitation of Spring Validation • Server-side only • Takes lots of coding for anything other than empty/white spaces • Vs. Common-validator support in Struts • Spring Modules - https://springmodules.dev.java.net/

  32. Roadmap • Web flow • Controllers and validation • Transactions and hibernate support • Bits and pieces • Tomcat server setup • Context, data source, and connection pooling • Creating WAR files • JSP pre-compilation • Displaytag

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

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

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

  36. Transaction Attributes • Propagation behaviors • Isolation levels • Read-only hints • Transaction timeout period

  37. Propagation Behaviors • Determines whether the method should be run in a transaction, and if so, whether it should run within an existing transaction, a new transaction, or a nested transaction within an existing transaction.

  38. Adding Transaction Aspect • TransactionProxyFactoryBean • target • transactionManager • transactionAttributeSource

  39. Other Hibernate Support • HibernateTemplate • OpenSessionInViewFilter and OpenSessionInViewInterceptor

  40. Roadmap • Web flow • Controllers and validation • Transactions and hibernate support • Bits and pieces • Tomcat server setup • Context, data source, and connection pooling • Creating WAR files • JSP pre-compilation • Displaytag

  41. Tomcat Server Setup • Unzip the Tomcat binary release package to a directory • Copy the JDBC driver of your database to common/lib • [Optional] Edit conf/server.xml to change the default port number

  42. Context, Data Source, and Connection Pooling • Connection pooling • Configure Tomcat and DBCP • http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html

  43. Creating WAR Files • Understand the directory structure • Use the war ANT task

  44. JSP Pre-compilation • Usually a JSP is converted to a servlet and then compiled into byte code when the JSP is request for the first time. • JSP pre-compilation • Eliminate the “first request overhead” • Speed up development • Tomcat provides JSP pre-compiler which can be used as an ANT task • Need to specify the compiled servlets in web.xml

  45. Displaytag • http://displaytag.sourceforge.net/ • Sortable columns and result paging

More Related