EXtreme Programming XP Тема 10. XP 1. Контроллеры (SimpleFormController, UrlFilenameViewController); 2. Модель и представление соединяются посредством.

Slides:



Advertisements
Similar presentations
Servlets & JSPs - Sharad Ballepu.
Advertisements

.meetup.com/13 Example application.
Integrating with jQuery and Bootstrap
J0 1 Marco Ronchetti - Basi di Dati Web e Distribuite – Laurea Specialitica in Informatica – Università di Trento.
JSP and Servelets.
CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
Struts Portlet Adding an Action Copyright © Liferay, Inc. All Rights Reserved. No material may be reproduced electronically or in print without.
Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion.
JSF Portlet Backing Beans and UI Components Copyright © Liferay, Inc. All Rights Reserved. No material may be reproduced electronically or in.
JLab Lattice Portal – Data Grid Web Service Ying Chen, Chip Watson Thomas Jefferson National Accelerator Facility.
Dispatching, monitoring, filtering
EXtreme Programming XP Тема 11. XP Для работы по администрированию таблицы Department создаем классы: DepartmentListController; EnterDepartmentController;
Cookie in a servlet. Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Web Development with Karsten Schulz Terp-Nielsen Master Principal Sales Consultant Oracle Denmark.
CS4273: Distributed System Technologies and Programming I Lecture 11: JavaServer Pages (JSP)
Apache Tomcat as a container for Servlets and JSP
Java Server Pages (JSP)
© Yaron Kanza Advanced Java Server Pages Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 24: Servlets Outline 24.1 Introduction 24.2 Servlet Overview and Architecture Interface.
Beginning Spring MVC Spencer Uresk. Notes This is a training, NOT a presentation Please ask questions This is being recorded
1 Servlets: Leftover Odds and Ends (Most apply to JSPs as well, duh….) Representation and Management of Data on the Internet, 2007 CS Department, HUJI.
Web MVC-2: Apache Struts Rimon Mikhaiel
Программирование на стороне сервера. Языки для программирования на стороне сервера Языки программирования: Perl PHP Java Технология Microsoft для использования.
Пользовательские действия (custom actions) в JSP. JSTL.
An Introduction To the Spring M.V.C. Framework Reference From Website By Tom Kochanowicz.
Spring MVC form handling annotation example
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
Spring Framework Benefits…
BEST PRACTICES - Java By Configuration Use global-forwards/results Helps to avoid duplicate jsp files and redundancy forward mapping.
Examples of Using Servlets and JSP Representation and Management of Data on the Internet.
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
Basic Struts Architecture Client Server Database Request Response Control View Model Server Struts Framework.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
Stanisław Osiński, 2002JSP – A technology for serving dynamic web content Java Server Pages™ A technology for serving dynamic web content Stanisław Osiński,
CGS – 4854 Summer 2012 Web Site Construction and Management Instructor: Francisco R. Ortega Chapter 3 Part 1.
Chapter 9 Session Tracking. Session Tracking Basics Accessing the session object associated with the current request: Call request.getSession to get an.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Session Management.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Forms with Spring MVC Handling Form.
Java Server Pages An introduction to JSP. Containers and Components Several clients – one system.
Struts Framework Anna Paščenko. What is Struts?  An open source framework for building Java web applications.
CSC 2720 Building Web Applications Frameworks for Building Web Applications.
Top right corner for field-mark, customer or partner logotypes. See Best practice for example. Slide title 40 pt Slide subtitle 24 pt Text 24 pt Bullets.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Essentials Getting started.
Mark Dixon 1 11 – Java Servlets. Mark Dixon 2 Session Aims & Objectives Aims –To cover a range of web-application design techniques Objectives, by end.
©SoftMoore ConsultingSlide 1 Filters. Filters can be used in a web application to intercept, examine, and possibly transform requests or responses associated.
13 Copyright © 2004, Oracle. All rights reserved. Adding Validation and Error Handling.
Servlets 4 Lec 30 Web Design and Development. Looking Back… Response Redirection  Sending a standard redirect  Sending a redirect to an error page Request.
©SoftMoore ConsultingSlide 1 Overview of Servlets and JavaServer Pages (JSP)
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.
Expect the Unexpected Kito D. Mann Principal Consultant.
ClaRA web services V. Gyurjyan Clas12 Software Meeting
 Java Server Pages (JSP) By Offir Golan. What is JSP?  A technology that allows for the creation of dynamically generated web pages based on HTML, XML,
The Chain of Responsibility Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
OOSD Using Java CBTS Framework. 11/2/04CBTS2 Servlet  A servlet is a Java program that can extends Web server’s functionality.  Servlets interact with.
CS 562 Advanced Java and Internet Application Computer Warehouse Web Application By Team Alpha :-  Puja Mehta (102163)  Mona Nagpure (102147)
Spring Filters Spring Interceptors SoftUni Team Spring Interceptors
Developing JavaServer Pages
Java Servlets.
Pre-assessment Questions
An Introduction To the Spring M.V.C. Framework
Sessions.
Generating the Server Response: HTTP Status Codes
null, true, and false are also reserved.
In Class Assg 2 - solution
CS320 Web and Internet Programming Cookies and Session Tracking
CS288 Lab Exercise 2.
Introduction to Java Servlets
Presentation transcript:

eXtreme Programming XP Тема 10

XP 1. Контроллеры (SimpleFormController, UrlFilenameViewController); 2. Модель и представление соединяются посредством класса org.springframework.web.servlet.ModelAndView 3. Для поддержки работы с формой используется командный объект (JavaBean, который заполняется значениями из полей формы) 4. Представления реализуются с помощью JSP страниц. Для упрощения сценариев существуют специальные теги из библиотеки дескрипторов Spring. 5. Используются объекты, раскрывающие интерфейс Validator (для проверки правильности ввода данных в форму) 6. Перехватчики – классы, которым передается управление перед (после) тем, как будет выполнен контроллер 7. Преобразователи представления – класс InternalResourceViewResolver. Осуществляет преобразование имен представлений (файл с расширением htm) в фактическое представление (файл с расширением jsp)

Перенаправление на контроллеры осуществляет класс org.springframework.web.servlet.DispatcherServlet Управление на него передается с помощью настройки в файле web.xml приложения. XP

В корневой папке приложения – index.jsp В папке WEB-INF содержатся файлы настройки приложения web.xml и timex-servlet.xml Файлы настройки Hibernate находятся в папке classes XP

XP

XP

<war destfile="${war.file}" webxml="${src.dir}/conf/web.xml"> <delete dir="${webinf.dir}/${src.dir}" failonerror="false" /> XP

<web-app xmlns=" xmlns:xsi=" xsi:schemaLocation=" version="2.4"> Time Expression Example index.jsp

XP timex org.springframework.web.servlet.DispatcherServlet 1 timex *.htm

XP Файл контекста приложения задает JavaBean’ы, используемые в приложении и их отношения внедрения. Разберем сначала функциональность авторизации пользователя.

XP <beans xmlns=" xmlns:xsi=" xsi:schemaLocation=" <bean id="urlMap" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> signInController signOutController urlFilenameController

XP <bean id="httpRequestInterceptor" class="com.visualpatterns.timex.controller.HttpReques tInterceptor"> signin.htm

XP true /signin redirect:ok.htm com.visualpatterns.timex.controller.SignLogin

XP <bean name="signOutController" class="com.visualpatterns.timex.controller.SignOutCon troller"> redirect:signin.htm

XP <bean id="urlFilenameController" class="org.springframework.web.servlet.mvc.UrlFilenameViewCo ntroller" />

XP <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResour ceViewResolver"> org.springframework.web.servlet.view.JstlView /WEB-INF/jsp/.jsp

XP <bean id="messageSource" class="org.springframework.context.support.Resourc eBundleMessageSource"> messages Файл messages.properties должен содержать строки: Id сообщения = текст сообщения

XP <bean id="urlMapAuthenticate" class="org.springframework.web.servlet.handler.SimpleUrlHandle rMapping">...

XP package com.visualpatterns.timex.controller; public class SignLogin { String login, password; public String getLogin() {return login;} public void setLogin(String login){this.login=login;} public String getPassword(){return password;} public void setPassword(String pass){ password=pass;} }

XP package com.visualpatterns.timex.controller; import javax.servlet.http.HttpServletRequest; public class ApplicationSecurityManager { public static final String USER = "user"; public Object getUser(HttpServletRequest request) { return request.getSession(true).getAttribute(USER); } public void setUser(HttpServletRequest request, Object user) { request.getSession(true).setAttribute(USER, user);} public void removeUser(HttpServletRequest request) { request.getSession(true).removeAttribute(USER);} }

XP package com.visualpatterns.timex.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.visualpatterns.timex.controller.SignLogin; import com.visualpatterns.timex.controller.ApplicationSecurityManager; public class HttpRequestInterceptor extends HandlerInterceptorAdapter { private String signInPage; private ApplicationSecurityManager applicationSecurityManager; public String getSignInPage() { return signInPage;} public void setSignInPage(String signInPage) { this.signInPage = signInPage;} public ApplicationSecurityManager getApplicationSecurityManager() { return applicationSecurityManager;} public void setApplicationSecurityManager( ApplicationSecurityManager applicationSecurityManager) { this.applicationSecurityManager = applicationSecurityManager;}

XP public void setApplicationSecurityManager( ApplicationSecurityManager applicationSecurityManager) { this.applicationSecurityManager = applicationSecurityManager;} public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String log = (String)applicationSecurityManager.getUser(request); if (log == null) { response.sendRedirect(this.signInPage); return false; } return true; }

XP 1. Обращение к форме: - formBackingObject – создание командного объекта - initBinder – регистрация редакторов свойств - showForm - referenceData – формирование списков 2. Данные в форме некорректные: - initBinder - onBind - onBindAndValidate - processFormSubmission - showForm - referenceData 3. Данные были корректными: - initBinder - onBind - onBindAndValidate - processFormSubmission - onSubmit

XP package com.visualpatterns.timex.controller; import org.springframework.validation.Errors; import com.visualpatterns.timex.controller.SignLogin; public class SignInValidator implements org.springframework.validation.Validator { public boolean supports(Class clazz) { return clazz.equals(SignLogin.class); } public void validate(Object command, Errors errors) { SignLogin log = (SignLogin) command; if (log == null) return; String login = log.getLogin(); String password = log.getPassword(); if (!(login.equals("admin") && password.equals("admin"))) errors.reject("error.login.invalid"); }

XP package com.visualpatterns.timex.controller; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import com.visualpatterns.timex.controller.ApplicationSecurityManager; import com.visualpatterns.timex.controller.SignLogin; public class SignInController extends SimpleFormController { private ApplicationSecurityManager applicationSecurityManager; protected Object formBackingObject(HttpServletRequest request) throws Exception { return new SignLogin(); }

XP public ModelAndView showForm( HttpServletRequest request, HttpServletResponse response, BindException errors, Map controlModel) throws Exception { if (applicationSecurityManager.getUser(request) != null) return new ModelAndView(getSuccessView()); return super.showForm(request, response, errors, controlModel); } public void onBindAndValidate( HttpServletRequest request, Object command, BindException errors) throws Exception { if (errors.hasErrors()) return; SignLogin formUser = (SignLogin) command; applicationSecurityManager.setUser(request, formUser.getLogin()); }

XP public ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { return new ModelAndView(getSuccessView());} public ApplicationSecurityManager getApplicationSecurityManager() { return applicationSecurityManager; } public void setApplicationSecurityManager( ApplicationSecurityManager applicationSecurityManager) { this.applicationSecurityManager = applicationSecurityManager; }

XP package com.visualpatterns.timex.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import com.visualpatterns.timex.controller.ApplicationSecurityManager; public class SignOutController implements Controller { private ApplicationSecurityManager applicationSecurityManager; private String successView; public String getSuccessView() { return successView; } public void setSuccessView(String successView) { this.successView = successView; }

XP public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response) throws Exception { applicationSecurityManager.removeUser(request); return new ModelAndView(getSuccessView()); } public ApplicationSecurityManager getApplicationSecurityManager() { return applicationSecurityManager;} public void setApplicationSecurityManager( ApplicationSecurityManager applicationSecurityManager) { this.applicationSecurityManager = applicationSecurityManager; }

XP Цель – перенаправление на страницу авторизации

XP Авторизация

XP Логин: ' value=' ' type="text" size="6" maxlength="6"> Пароль: ' value=' ' type="password" size="8" maxlength="10">

XP Вы успешно вошли в систему Выйти из системы