Слайд 1 - ksu.ru

Report
Тема 11
XP
eXtreme Programming
Для работы по администрированию таблицы
Department создаем классы:
 DepartmentListController;
 EnterDepartmentController;
 DeleteDepartmentController;
 EnterDepartmentValidator;
 DelName – командный объект для формы
выбора удаляемого элемента;
 DeleteDepartmentController.
XP
Добавляем:
<bean name="departmentListController"
class="com.visualpatterns.timex.controller.DepartmentListC
ontroller">
<property name="departmentManager">
<ref bean="departmentManager" />
</property>
<property name="successView">
<value>departmentlist</value>
</property>
<property name="applicationSecurityManager">
<ref bean="applicationSecurityManager" />
</property>
</bean>
XP
Валидаторы:
<bean id="deleteDepartmentValidator"
class="com.visualpatterns.timex.controller.DeleteDepa
rtmentValidator" />
<bean id="enterDepartmentValidator"
class="com.visualpatterns.timex.controller.EnterD
epartmentValidator" />
Менеджер:
<bean id="departmentManager"
class="com.visualpatterns.timex.model.DepartmentM
anager" />
XP
<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
<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
Назначение перехватчика на файлы:
<bean id="urlMapAuthenticate"
ing">
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapp
<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
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
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
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
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
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
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
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
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
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
package com.visualpatterns.timex.controller;
import
import
import
import
import
import
import
import
import
import
import
import
XP
java.util.HashMap;
java.util.Map;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
org.springframework.validation.BindException;
org.springframework.web.bind.ServletRequestDataBinder;
org.springframework.web.servlet.ModelAndView;
org.springframework.web.servlet.mvc.SimpleFormController;
com.visualpatterns.timex.model.DepartmentManager;
com.visualpatterns.timex.model.Department;
com.visualpatterns.timex.model.DepartmentManager;
com.visualpatterns.timex.controller.ApplicationSecurityManager;
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
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-88591"),"Cp1251");
department.setDepartmentCode(code1);department.setName(name1);
} catch(Exception e){}
departmentManager.saveDepartment(department);
try{ String message=new
String(getMessageSourceAccessor().getMessage("message.enterdepartment.sa
vesuccess").getBytes("ISO-8859-1"),"Cp1251");
request.getSession().setAttribute("message",message);
}
catch(Exception e){}
return new ModelAndView(getSuccessView());}
// также следует добавить все set и get-методы для свойств класса
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 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
package com.visualpatterns.timex.controller;
import
import
import
import
import
import
import
import
import
import
import
import
XP
java.util.HashMap;
java.util.Map;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
org.springframework.validation.BindException;
org.springframework.web.bind.ServletRequestDataBinder;
org.springframework.web.servlet.ModelAndView;
org.springframework.web.servlet.mvc.SimpleFormController;
com.visualpatterns.timex.model.DepartmentManager;
com.visualpatterns.timex.model.Department;
com.visualpatterns.timex.controller.DelName;
com.visualpatterns.timex.controller.ApplicationSecurityManager;
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
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
<%@ 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
<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
<%@ 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
<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
<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
<%@ 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
<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

similar documents