Beginning Spring MVC Spencer Uresk. Notes This is a training, NOT a presentation Please ask questions This is being recorded https://tech.lds.org/wiki/Java_Stack_Training.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
Struts Portlet Copyright © Liferay, Inc. All Rights Reserved. No material may be reproduced electronically or in print without written permission.
Web Development with Karsten Schulz Terp-Nielsen Master Principal Sales Consultant Oracle Denmark.
Apache Struts Technology
A Blackboard Building Block™ Crash Course for Web Developers
INTRODUCTION TO ASP.NET MVC AND EXAMPLE WALKTHROUGH RAJAT ARYA EFECS - OIM DAWG – 4/21/2009 ASP.NET MVC.
Ruby on Rails Model of MVC. Model-View-Controller Paradigm A way of organizing a software system Benefits: Isolation of business logic from the user interface.
Spring MVC Part 2 Spencer Uresk. Notes This is a training, NOT a presentation Please ask questions This is being recorded
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
Using JavaServer Pages Harry R. Erwin, PhD CIT304/CSE301.
Object-Oriented Enterprise Application Development Tomcat 3.2 Configuration Last Updated: 03/30/2001.
J4www/jea Week 3 Version Slide edits: nas1 Format of lecture: Assignment context: CRUD - “update details” JSP models.
Struts Basics SSE USTC Qing Ding. Agenda What is and Why Struts? Struts architecture – Controller: Focus of this presentation – Model – View Struts tag.
DT211/3 Internet Application Development
DT228/3 Web Development JSP: Directives and Scripting elements.
MC365 Application Servers: Java Server Pages (JSP’s) and Session Management.
Web Applications Basics. Introduction to Web Web features Clent/Server HTTP HyperText Markup Language URL addresses Web server - a computer program that.
ECE356 – Database Systems Lab 1 – Building a Web Project with NetBeans Tiuley Alguindigue Lab Instructor – University of Waterloo, E & CE Dept. Fall 2013.
Introduction to Java web programming Dr Jim Briggs JWP intro1.
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
Struts 2.0 an Overview ( )
Struts. Agenda Preface Struts and its components An example The architecture required for Struts Applications.
UNIT-V The MVC architecture and Struts Framework.
J2EE Web Fundamentals Lesson 1 Introduction and Overview
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
Separation of Concerns Technion – Institute of Technology Author: Gal Lalouche - Technion 2015 © 1.
The New Architecture for Collaboration Brent McConnell David LaPalomento.
Copyright © 2012 Accenture All Rights Reserved.Copyright © 2012 Accenture All Rights Reserved. Accenture, its logo, and High Performance Delivered are.
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
Design Patterns Phil Smith 28 th November Design Patterns There are many ways to produce content via Servlets and JSPs Understanding the good, the.
Introduction to Java Server Pages (JSPs) Robert Thornton.
Java Server Pages Lecture July Java Server Pages Java Server Pages (JSPs) provide a way to separate the generation of dynamic content (java)
Chapter 8 Script-free pages. Problem with scripting in JSP When you use scripting (declaration, scriplet, expressions) in your JSP, you actually put Java.
Standalone Java Application vs. Java Web Application
JSF Introduction Copyright © Liferay, Inc. All Rights Reserved. No material may be reproduced electronically or in print without written permission.
Lecturer: Prof. Piero Fraternali, Teaching Assistant: Alessandro Bozzon, Advanced Web Technologies: Struts–
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Chapter 6 Server-side Programming: Java Servlets
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Forms with Spring MVC Handling Form.
WAM and the Java Stack. Disclaimer Please ask questions There are hands on labs Prerequisites: – Basic Java knowledge – Basic Spring knowledge – LDS Account.
Struts Framework Anna Paščenko. What is Struts?  An open source framework for building Java web applications.
Model View Controller Architecture of Java Web Applications Dr. M V S Peri Sastry, Ph.D.[BITS-Pilani]
CS-4220 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
Chính phủ điện tử TS. Phạm Văn Tính Khoa CNTT, ĐH Nông Lâm TP.HCM
Chapter 11 Invoking Java Code with JSP Scripting Elements.
INTEGRATION OF BACKBONE.JS WITH SPRING 3.1. Agenda New Features and Enhancements in Spring 3.1 What is Backbone.js and why I should use it Spring 3.1.
Apache Struts. J2EE Web Application using MVC design pattern Why MVC? Separate components = easier maintenance – Model component holds object data – View.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Essentials Getting started.
Introduction to Servlets Allen Day. Notes This is a training NOT a presentation Please ask questions Prerequisites.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
Preface IIntroduction Objectives I-2 Course Overview I-3 1Oracle Application Development Framework Objectives 1-2 J2EE Platform 1-3 Benefits of the J2EE.
11 Copyright © 2004, Oracle. All rights reserved. Customizing Actions.
Team Members Tyler Lamb Kirk Olson James Woestman IRP Presentation Client Zirous Inc. Faculty Advisor Tien Nguyen 1.
Implementation Struts Framework for well-architectured web applications Model-View-Controller design pattern.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Developing Rich Web Applications with.
10 Copyright © 2004, Oracle. All rights reserved. Building ADF View Components.
Apache Struts Technology A MVC Framework for Java Web Applications.
CS320 Web and Internet Programming Web Application and MVC Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Spring – Web MVC Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Spring – Web MVC Chengyu Sun California State University, Los Angeles.
J2EE Lecture 7: Spring – Spring MVC
CS5220 Advanced Topics in Web Programming Spring – Web MVC
Spring MVC Part 2 Spencer Uresk.
CS5220 Advanced Topics in Web Programming Spring – Web MVC
Presentation transcript:

Beginning Spring MVC Spencer Uresk

Notes This is a training, NOT a presentation Please ask questions This is being recorded Prerequisites – Basic Java – Installed LDSTech IDE (or other equivalent) – Spring, Servlet, and JSP Trainings

A Note About Security The scope of this training is limited to teaching you how to use Spring MVC The way we output values in JSPs is insecure – they contain XSS vulnerabilities We have documented ways to do this properly: bs bs sites/stack/module.html?module=security-web sites/stack/module.html?module=security-web

Objectives By the end of this training, you should: - Have a general understanding of MVC in general and Spring MVC in particular - Understand how Spring MVC is configured and be able to add it to any project - Know how to create a simple controller - Know how to map an incoming request to a controller

What is MVC? Well-established architectural pattern for dealing with UI Model manages the behavior and data of the application View renders the model into UI elements Controller processes user inputs and generates a response by operating on model objects

MVC in a Web Application The model is the data and business/domain logic for your application The view is typically HTML generated by your application The controller receives HTTP requests and decides which domain objects to use to carry out specific tasks

Benefits of MVC Decoupling views and models Reduces the complexity of your design Makes code more flexible Makes code more maintainable

What is Spring MVC? MVC Web Framework Developed by the Spring team in response to what they felt were deficiencies in frameworks like Struts Deeply integrated with Spring Allows most parts to be customized (ie, you can use pretty much any view technology) RESTful functionality (URI templates, Content Negotiation)

Spring MVC Features Clear separation of roles Simple, powerful annotation-based configuration Controllers are configured via Spring, which makes them easy to use with other Spring objects and makes them easy to test Customizable data binding Flexible view technology Customizable handler mapping and view resolution

DispatcherServlet [1] Copyright © Rod Johnson, Juergen Hoeller, et al. See copyright slide for full copyright information.copyright slide

Adding Spring MVC to a project Spring MVC is relatively easy to add to any existing Spring project When you create a Stack Starter (3.x) project, the default is to include Spring MVC But we’ll go through the configuration steps so you know what is going on 3 basic steps

Step 1: Add dependencies First, you need to add the Spring MVC dependency to your web POM org.springframework spring-webmvc

Step 2: Configure web.xml We need to define the DispatcherServlet, give it a name (yourapp in this case), and map it to a url pattern (/ in this case, which is the default servlet) yourapp org.springframework.web.servlet.DispatcherServlet 2 yourapp /

Step 3: Add the configuration file We need to create a configuration file name [servlet-name]-servlet.xml, where [servlet-name] is the name we gave our servlet in Step 2 (yourapp) This is a normal Spring configuration file that defines a web context

Step 3, Continued First, we tell it to look for classes in the org.lds.yourapp namespace, annotated We also need to tell Spring MVC that we are going to configure it via annotations:

Step 3, Continued If you map the DispatcherServlet to the default servlet (we did), you need to add the following: Finally, we need to configure a ViewResolver to find our JSPs

Hierarchy of Contexts When we create the [servlet-name]-servlet.xml file, we are creating a new Spring context that is a child of your application context It can resolve beans from the root context, but other contexts can’t resolve beans from it You can create as many of these as you need (ie, you might have another one for web services) You need to make sure you don’t redefine beans, though

Context Hierarchy a DefaultWebContext / b GWT Context /*.gwtrpc c Web Services /ws/

Simple request mapping We can do simple mappings to static content in the xml configuration, which maps /hello to /WEB-INF/views/hello.jsp

Simple request mapping Thankfully, Spring MVC has a Namespace Handler to make this simpler. The following does the exact same thing:

Lab 1: Configure a project Take a basic project (with no view) created via Stack Starter Add dependencies, web.xml config, and servlet config Add a simple request mapping Verify that it works

Simple Controller For most cases, you’ll need to create a controller Create a class and annotate it Then, create a method annotated with package public class HelloController public String hello() { return “hello"; }

Advanced Request Mapping RequestMappings are really flexible You can define on a class and all will be relative to it. There are a number of ways to define them: – URI Patterns – HTTP Methods (GET, POST, etc) – Request Parameters – Header values

@RequestMapping – Class level The url for this (relative to your context root) would be: /portfolio/create public class PortfolioController public String create() { return “create"; }

@RequestMapping – HTTP Methods Same URL as the previous example, but responds to POSTs public class PortfolioController = "/create“, method = RequestMethod.POST) public String save() { return “view"; }

@RequestMapping – Request Params This will respond to /portfolio/view?details=all public class PortfolioController = "/view“, params=“details=all”) public String viewAll() { return “viewAll"; }

@RequestMapping – URI Templates The url for this (relative to your context root) would be: /portfolio/1/viewProject/10 We’ll discuss how to use the values from these placeholders later public class PortfolioController public String viewProject() { return "viewProject"; }

Lab 2: Create a controller Create a simple controller for /hello Return a jsp Experiment with some more advanced request mappings

Controller Method Arguments Sometimes you need access to the request, session, request body, or other items If you add them as arguments to your controller method, Spring will pass them public String getProject(HttpServletRequest request, HttpSession Long String contentType) { return "index"; }

Supported Method Arguments Request/Response objects Session object Spring’s WebRequest object java.util.Locale java.io.Reader (access to request content) java.io.Writer (access to response content) java.security.Principal ModelMap org.springframework.validation.Errors org.springframework.validation.BindingResult

Supported Annotations

Method Arguments (Samples) This gives you access to the request/response and public String getProject(HttpServletRequest request, HttpServletResponse response, HttpSession session) { return "index"; }

Method Arguments (Samples) This gives you access to request parameters and public String Long String contentType) { return "index"; }

Method Arguments ties dynamic elements of the URI to method public String Long Long portfolioId) { return "index"; }

The Model You populate the view with data by via the ModelMap or ModelAndView (which has a ModelMap underneath) This is basically a Map All attributes are added to the request so that they can be picked up by JSPs

ModelMap Add it as a parameter to your controller method We’d consume it in our JSP like this: public String doController(ModelMap modelMap){ modelMap.addAttribute(user); modelMap.addAttribute(“otherUser”, user); return “index”; } User: ${user} Other User: ${otherUser}

ModelAndView Combines the model and view into one object We’d consume it in our JSP like this: public ModelAndView doController() { ModelAndView mav = new ModelAndView(“index”); mav.addObject(user); mav.addObject(“otherUser”, user); return mav; } User: ${user} Other User: ${otherUser}

Lab 3: Putting it all together Add a more complex controller that takes a path param and displays it back to the user Also, have it echo back a header

Next Steps Part II of this training in 2 weeks Spring MVC reference documentation spring-framework-reference/html/mvc.html spring-framework-reference/html/mvc.html

Sources view%E2%80%93controller view%E2%80%93controller Model-view-controller_framework Model-view-controller_framework spring-framework-reference/html/mvc.html spring-framework-reference/html/mvc.html

Copyright Notice 1. DispatcherServlet image copyright info: Copyright © Rod Johnson, Juergen Hoeller, Keith Donald, Colin Sampaleanu, Rob Harrop, Alef Arendsen, Thomas Risberg, Darren Davison, Dmitriy Kopylenko, Mark Pollack, Thierry Templier, Erwin Vervaet, Portia Tung, Ben Hale, Adrian Colyer, John Lewis, Costin Leau, Mark Fisher, Sam Brannen, Ramnivas Laddad, Arjen Poutsma, Chris Beams, Tareq Abedrabbo, Andy Clement, Dave Syer, Oliver Gierke Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically. servlet servlet