1 / 31

Spring MVC – разработка сценариев доступа к базе данных

Тема 11. Spring MVC – разработка сценариев доступа к базе данных. XP. eXtreme Programming. Файл контекста приложения timex-servlet.xml. Для работы по администрированию таблицы Department создаем классы: DepartmentListController ; EnterDepartmentController ;

oihane
Download Presentation

Spring MVC – разработка сценариев доступа к базе данных

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. Тема 11 SpringMVC – разработка сценариев доступа к базе данных XP eXtreme Programming

  2. Файл контекста приложения timex-servlet.xml Для работы по администрированию таблицы Department создаем классы: • DepartmentListController; • EnterDepartmentController; • DeleteDepartmentController; • EnterDepartmentValidator; • DelName – командный объект для формы выбора удаляемого элемента; • DeleteDepartmentController. XP

  3. Файл timex-servlet.xml Добавляем: <bean name="departmentListController" class="com.visualpatterns.timex.controller.DepartmentListController"> <property name="departmentManager"> <ref bean="departmentManager" /> </property> <property name="successView"> <value>departmentlist</value> </property> <property name="applicationSecurityManager"> <ref bean="applicationSecurityManager" /> </property> </bean> XP

  4. Файл timex-servlet.xml Валидаторы: <bean id="deleteDepartmentValidator" class="com.visualpatterns.timex.controller.DeleteDepartmentValidator" /> <bean id="enterDepartmentValidator" class="com.visualpatterns.timex.controller.EnterDepartmentValidator" /> Менеджер: <bean id="departmentManager" class="com.visualpatterns.timex.model.DepartmentManager" /> XP

  5. Файл timex-servlet.xml <bean name="enterDepartmentConroller" class="com.visualpatterns.timex.controller.EnterDepartmentController"> <property name="sessionForm"><value>true</value></property> <property name="formView“><value>/enterdepartment</value></property> <property name="successView"> <value>redirect:departmentlist.htm</value> </property> <property name="commandClass"> <value>com.visualpatterns.timex.model.Department</value> </property> <property name="validator"> <ref bean="enterDepartmentValidator" /> </property> <property name="departmentManager“><ref bean="departmentManager"/> </property> <property name="applicationSecurityManager"> <ref bean="applicationSecurityManager" /> </property> </bean> XP

  6. Файл timex-servlet.xml <bean name="deleteDepartmentConroller" class="com.visualpatterns.timex.controller.DeletDepartmentController"> <property name="sessionForm"><value>true</value></property> <property name="formView"><value>/deletedepartment</value></property> <property name="successView"> <value>redirect:departmentlist.htm</value> </property> <property name="commandClass"> <value>com.visualpatterns.timex.controller.DelName</value> </property> <property name="validator"> <ref bean="deleteDepartmentValidator" /> </property> <property name="departmentManager"> <ref bean="departmentManager"/> </property> <property name="applicationSecurityManager"> <ref bean="applicationSecurityManager" /> </property> </bean> XP

  7. Файл timex-servlet.xml Назначение перехватчика на файлы: <bean id="urlMapAuthenticate" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="interceptors"> <list><ref bean="httpRequestInterceptor" /></list> </property> <property name="urlMap"> <props> <prop key="/departmentlist.htm">departmentListController </prop> <prop key="/enterdepartment.htm">enterDepartmentConroller</prop> <prop key="/deletedepartment.htm">deleteDepartmentConroller</prop> </props> </property> </bean> XP

  8. Для входа в систему создаем командный объект 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

  9. Менеджер класса Department (DepartmentManager) – обращение к таблице. Содержит методы: public List getDepartments() { List departmentList = null; SessionFactory SessionFactory=new Configuration().configure().buildSessionFactory(); Session session =SessionFactory.getCurrentSession(); session.beginTransaction(); try{ departmentList = session.createQuery( "from Department ORDER BY name").list(); session.getTransaction().commit(); } catch (HibernateException e){ session.getTransaction().rollback(); throw e;} return departmentList; } XP

  10. Менеджер класса Department (DepartmentManager) – обращение к таблице. Содержит методы: public Department getDepartment(String departmentCode) { Department department = null; SessionFactory SessionFactory=new Configuration().configure().buildSessionFactory(); Session session =SessionFactory.getCurrentSession(); session.beginTransaction(); try{ department = (Department) session.createQuery( "from Department" + " where departmentCode = ?").setString(0, departmentCode).uniqueResult(); session.getTransaction().commit(); SessionFactory.close();} catch (HibernateException e) { session.getTransaction().rollback(); throw e;} return department; } XP

  11. Менеджер класса Department (DepartmentManager) – обращение к таблице. Содержит методы: public void saveDepartment(Department department) { SessionFactory SessionFactory=new Configuration().configure().buildSessionFactory(); Session session =SessionFactory.getCurrentSession(); session.beginTransaction(); try{ session.saveOrUpdate(department); session.getTransaction().commit(); SessionFactory.close(); } catch (HibernateException e) { session.getTransaction().rollback();throw e;} } XP

  12. Менеджер класса Department (DepartmentManager) – обращение к таблице. Содержит методы: public void deleteDepartment(String departmentCode) { SessionFactory SessionFactory=new Configuration().configure().buildSessionFactory(); Session session =SessionFactory.getCurrentSession(); session.beginTransaction(); try{ session.delete(session.load(Department.class, departmentCode)); session.flush(); session.getTransaction().commit(); SessionFactory.close();} catch (HibernateException e) { session.getTransaction().rollback();throw e;} } XP

  13. Класс DepartmentListController package com.visualpatterns.timex.controller; import java.util.List; 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.model.Department; import com.visualpatterns.timex.model.DepartmentManager; import com.visualpatterns.timex.controller.ApplicationSecurityManager; public class DepartmentListController implements Controller { private DepartmentManager departmentManager; public static final String MAP_KEY = "departments"; private ApplicationSecurityManager applicationSecurityManager; private String successView; XP

  14. Класс DepartmentListController public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response) throws Exception { List departments = departmentManager.getDepartments(); return new ModelAndView(getSuccessView(), MAP_KEY, departments); } public ApplicationSecurityManager getApplicationSecurityManager() { return applicationSecurityManager; } public void setApplicationSecurityManager(ApplicationSecurityManager app) { applicationSecurityManager=app; } XP

  15. Класс DepartmentListController public DepartmentManager getDepartmentManager() {return departmentManager;} public void setDepartmentManager(DepartmentManager departmentManager) {this.departmentManager = departmentManager;} public String getSuccessView() {return successView;} public void setSuccessView(String successView) { this.successView = successView; } } XP

  16. Валидатор - EnterDepartmentValidator package com.visualpatterns.timex.controller; import org.springframework.validation.Errors; import com.visualpatterns.timex.model.Department; public class EnterDepartmentValidator implements org.springframework.validation.Validator { public boolean supports(Class clazz) {return clazz.equals(Department.class);} public void validate(Object command, Errors errors) { Department log = (Department) command; if (log == null) return; String code = log.getDepartmentCode(); if (code.length()>2 || code.length()<2) errors.reject("error.enterdepartment.codeiswrong"); } } XP

  17. Класс - EnterDepartmentController package com.visualpatterns.timex.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.validation.BindException; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import com.visualpatterns.timex.model.DepartmentManager; import com.visualpatterns.timex.model.Department; import com.visualpatterns.timex.model.DepartmentManager; import com.visualpatterns.timex.controller.ApplicationSecurityManager; XP

  18. Класс - EnterDepartmentController public class EnterDepartmentController extends SimpleFormController { private DepartmentManager departmentManager = null; private ApplicationSecurityManager applicationSecurityManager; public static final String TID = "tid"; protected Object formBackingObject(HttpServletRequest request) {if (request.getParameter(TID) != null && request.getParameter(TID).trim().length() > 0) { String code1=""; try{ code1=new String(request.getParameter(TID). trim().getBytes("ISO-8859-1"),"Cp1251"); } catch(Exception e){} return departmentManager.getDepartment(code1); } Department department = new Department(); return department; } XP

  19. Класс - EnterDepartmentController protected ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) { Department department = (Department) command; try{ String code1=new String(department.getDepartmentCode().getBytes("ISO-8859-1"),"Cp1251"); String name1=new String(department.getName().getBytes("ISO-8859-1"),"Cp1251"); department.setDepartmentCode(code1);department.setName(name1); }catch(Exception e){} departmentManager.saveDepartment(department); try{ String message=new String(getMessageSourceAccessor().getMessage("message.enterdepartment.savesuccess").getBytes("ISO-8859-1"),"Cp1251"); request.getSession().setAttribute("message",message); } catch(Exception e){} return new ModelAndView(getSuccessView());} // также следует добавить все set и get-методы для свойств класса XP

  20. Создание валидатора формы(метод validate вызывается в onBindAndValidate) 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

  21. ВалидаторDeleteDepartmentValidator package com.visualpatterns.timex.controller; import org.springframework.validation.Errors; import com.visualpatterns.timex.controller.DelName; public class DeleteDepartmentValidator implements org.springframework.validation.Validator { public boolean supports(Class clazz) {return clazz.equals(DelName.class);} public void validate(Object command, Errors errors) { DelName log = (DelName) command; if (log == null) return; String code = log.getCode(); if (code.length()!=2) errors.reject("error.login.invalid"); } } XP

  22. Класс DeleteDepartmentController package com.visualpatterns.timex.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.validation.BindException; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import com.visualpatterns.timex.model.DepartmentManager; import com.visualpatterns.timex.model.Department; import com.visualpatterns.timex.controller.DelName; import com.visualpatterns.timex.controller.ApplicationSecurityManager; XP

  23. Класс DeleteDepartmentController public class DeletDepartmentController extends SimpleFormController { private DepartmentManager departmentManager = null; private ApplicationSecurityManager applicationSecurityManager; protected Object formBackingObject(HttpServletRequest request) { return new DelName(); } protected Map referenceData(HttpServletRequest request) throws Exception { // для создания списка выбора HashMap model = new HashMap(); model.put("departments", departmentManager.getDepartments()); return model; } XP

  24. Класс DeleteDepartmentController protected ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) { DelName code= (DelName) command; String code1=""; try{ code1=new String(code.getCode().getBytes("ISO-8859-1"),"Cp1251"); }catch(Exception e){} departmentManager.deleteDepartment(code1); request.getSession().setAttribute("message",getMessageSourceAccessor(). getMessage("message.deletedepartment.deletesuccess")); return new ModelAndView(getSuccessView()); } // а также get и set-методы для всех свойств контроллера XP

  25. Сценарий просмотра отделовdepartmentlist.jsp <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ page contentType="text/html; charset=windows-1251" %> <html> <head> <title>Список всех отделов</title> </head> <body> <h1>Список всех отделов</h1> <div align="right" nowrap="nowrap"><a href="signout.htm">Выйти из системы</a></div> <p align="center"> <!-- status messages --> <c:if test="${not empty message}"> <font color="green"><c:out value="${message}" /></font> <c:set var="message" value="" scope="session" /> </c:if></p> XP

  26. Сценарий просмотра отделовdepartmentlist.jsp <p align="center"><a href="enterdepartment.htm">Добавить отдел</a> </p> <p align="center"><a href="deletedepartment.htm">Удалить отдел</a> </p> <table border="1" align="center" cellpadding="8" cellspacing="0"> <tr><th>Code</th><th>Name</th></tr> <c:forEach items="${departments}" var="department"> <tr><td align="center"> <a href='enterdepartment.htm?tid=<c:out value="${department.departmentCode}"/>'><c:out value="${department.departmentCode}"/></a> </td> <td align="center"><c:out value="${department.name}" /></td> </tr> </c:forEach> </table> </body> </html> XP

  27. Сценарий редактирования информации об отделе enterdepartment.jsp <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@ page contentType="text/html; charset=windows-1251" %> <html> <head><title>Добавление/редактирование отдела</title></head> <body> <form method="post"> <h1>Информация об отделе</h1> <a href="signout.htm" align="rignt">Выйти из системы</a></td> <tr> <td colspan="2" align="center"> <center><spring:bind path="command.*"> <c:if test="${not empty status.errorMessages}"> <c:forEach var="error" items="${status.errorMessages}"> <font color="red"><c:out value="${error}" escapeXml="false" /> </font> <br /> </c:forEach> </c:if> </spring:bind> XP

  28. Сценарий редактирования информации об отделе enterdepartment.jsp <c:if test="${not empty message}"> <font color="green"><c:out value="${message}" /></font> <c:set var="message" value="" scope="session" /> </c:if></center><br/> <table border="1" align="center"> <tr> <th>Код отдела</th> <th>Название отдела</th> </tr> <tr> <td><spring:bind path="command.departmentCode"> <input name='<c:out value="${status.expression}"/>' value='<c:out value="${status.value}"/>' type="text" size="4" maxlength="6"> </spring:bind></td> <td><spring:bind path="command.name"> <input name='<c:out value="${status.expression}"/>' value='<c:out value="${status.value}"/>' type="text" size="4" maxlength="6“> </spring:bind></td> </tr></table> XP

  29. Сценарий редактирования информации об отделе enterdepartment.jsp <p align="center"><input name="save" type="submit" value="Save"> <input name="cancel" type="button" value="Cancel" onClick="javascript:window.location='departmentlist.htm'"> <br> <br> </p> </td> </tr> </table> </form> </body> </html> XP

  30. Сценарий удаления отделаdeletedepartment.jsp <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@ page contentType="text/html; charset=windows-1251" %> <html> <head><title>Удаление отдела</title></head> <body> <form method="post"> <h1>Выберите отдел для удаления</h1> <a href="signout.htm" align="rignt">Выйти из системы</a></td> <tr><spring:bind path="command.code"> <select name='<c:out value="${status.expression}"/>'> <option value=""></option> <c:forEach items="${departments}" var="department"> <option value='<c:out value="${department.departmentCode}"/>'> <c:out value="${department.name}"/> </option> </c:forEach> </select> XP

  31. Сценарийудаления отделаdeletedepartment.jsp <br/><br/></spring:bind> <p align="center"><input name="save" type="submit" value="Save"> <input name="cancel" type="button" value="Cancel" onClick="javascript:window.location='departmentlist.htm'"> <br> <br> </p> </form> </body> </html> XP

More Related