Новичок
Профиль
Группа: Участник
Сообщений: 2
Регистрация: 29.11.2011
Репутация: нет Всего: нет
|
Доброго времени суток. Я новичёк в Java. Возникла такая проблема...   Код: | Код | /** * Форма Registration * @author <a href="mailto:[email protected]">Alexandr Grinko</a> */ public class Registration { /** * First name */ private String firstName; /** * Last name */ private String lastName; /** * Password */ private String password; /** * Confirm password */ private String confirmPassword; /** * E-Mail */ private String email; //setters, getters
|
| Код |
package ua.org.teos.web.form;
/** * Форма UserProfile */ public class UserProfile { /** * First name */ private String firstName; /** * Last name */ private String lastName; /** * Password */ private String password; /** * Confirm password */ private String confirmPassword; /** * E-Mail */ private String email; /** *Country */ private Integer country; private Integer day; private String month; private Integer year; private String sex; private String state; private String city;
|
Контроллеры: | Код | package ua.org.teos.web.controller;
import static ua.org.teos.web.TeosUrl.*; import static ua.org.teos.web.form.TeosCommand.*; import static ua.org.teos.web.view.TeosView.*;
import java.util.*;
import javax.servlet.ServletException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.validation.BindingResult; import org.springframework.web.servlet.ModelAndView; import ua.org.teos.common.db.entity.IUser; import ua.org.teos.db.DataFacade; import ua.org.teos.web.form.Registration; import ua.org.teos.web.cryptography.MD5; import ua.org.teos.web.validation.RegistrationValidation;
/** * Класс контроллер. Служит для регистрации пользователей */ @Controller @RequestMapping(REGISTRATION_URL) public class RegistrationController {
/** * Java bean. Используется для работы с базой данных. */ @Autowired private DataFacade dataFacade;
/** * Показывает форму регистрации */ @RequestMapping(method = RequestMethod.GET) public ModelAndView showRegistration() { Map<String, Object> model = new HashMap<String, Object>(); Registration registration = new Registration(); model.put(REGISTRATION_COMMAND, registration); return new ModelAndView(REGISTRATION_VIEW, model); }
/** * Используется для регистрации пользователя */ @RequestMapping(method = RequestMethod.POST) public ModelAndView processRegistration(Registration registration, BindingResult result) throws ServletException { Map<String, Object> model = new HashMap<String, Object>(); registration.setFirstName(registration.getFirstName().trim()); registration.setLastName(registration.getLastName().trim()); registration.setConfirmPassword(registration.getConfirmPassword().trim()); registration.setPassword(registration.getPassword().trim()); registration.setEmail(registration.getEmail().trim()); model.put(REGISTRATION_COMMAND, registration); RegistrationValidation registrationValidation = new RegistrationValidation(); registrationValidation.validate(registration, result); if (result.hasErrors()) { return new ModelAndView(REGISTRATION_VIEW, model); } if (dataFacade.readUser(registration.getEmail()) != null) { result.rejectValue("email", "validEmail.registration.email", "Этот E-mail занят. Выберите другой"); } if (result.hasErrors()) { return new ModelAndView(REGISTRATION_VIEW, model); } try { MD5 md5 = new MD5(); IUser user = dataFacade.getUserObject(); user.setFirstName(registration.getFirstName()); user.setLastName(registration.getLastName()); user.setUserPassword(md5.getHash(registration.getPassword())); user.setEMail(registration.getEmail()); dataFacade.createUser(user); } catch (InstantiationException e) { throw new ServletException(e); } catch (IllegalAccessException e) { throw new ServletException(e); } return new ModelAndView(REGISTRATION_SUCCESS_VIEW); } }
|
| Код | package ua.org.teos.web.controller;
import static ua.org.teos.web.TeosUrl.*; import static ua.org.teos.web.form.TeosCommand.*; import static ua.org.teos.web.view.TeosView.*;
import java.io.*; import java.text.*; import java.util.*;
import javax.servlet.ServletException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView;
import ua.org.teos.common.db.entity.IUser; import ua.org.teos.db.DataFacade; import ua.org.teos.web.cryptography.MD5; import ua.org.teos.web.form.UserProfile; import ua.org.teos.web.validation.UserProfileValidation;
/** * Класс контроллер. Служит для редактирования профиля пользователя * @author <a href="mailto:[email protected]">Alexandr Grinko</a> */ @Controller @RequestMapping(USER_PROFILE_URL) public class UserProfileController {
/** * Java bean. Используется для работы с базой данных. */ @Autowired private DataFacade dataFacade;
/** * Показывает форму редактирования профиля пользователя */ @RequestMapping(method = RequestMethod.GET) public ModelAndView showUserProfile() { Map<String, Object> model = new HashMap<String, Object>(); UserProfile userProfile = new UserProfile(); model.put(USER_PROFILE_COMMAND, userProfile); model.put("countries", dataFacade.getAllCountries()); return new ModelAndView(USER_PROFILE_VIEW, model); }
/** * Используется для редактирования профиля пользователя */ @RequestMapping(method = RequestMethod.POST) public ModelAndView editUserProfile(UserProfile userProfile, BindingResult result/*, @RequestParam("avatar") MultipartFile file*/) throws ServletException { userProfile.setFirstName(userProfile.getFirstName().trim()); userProfile.setLastName(userProfile.getLastName().trim()); userProfile.setPassword(userProfile.getPassword().trim()); userProfile.setEmail(userProfile.getEmail().trim()); userProfile.setConfirmPassword(userProfile.getConfirmPassword().trim()); userProfile.setCity(userProfile.getCity().trim()); userProfile.setState(userProfile.getState().trim()); Map<String, Object> model = new HashMap<String, Object>(); model.put(USER_PROFILE_COMMAND, userProfile); UserProfileValidation userProfileValidation = new UserProfileValidation(); userProfileValidation.validate(userProfile, result); if (result.hasErrors()) { return new ModelAndView(USER_PROFILE_VIEW, model); } try { /* //Создаём файл File avatar = new File("C:\\files\\" + file.getOriginalFilename()); //Кидаем в него нашу аватару. file.transferTo(avatar); */ String str_date = userProfile.getYear().toString() + "-" + userProfile.getMonth() + "-" + userProfile.getDay(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date date; date = (Date)formatter.parse(str_date); MD5 md5 = new MD5(); IUser user = dataFacade.getUserObject(); user.setFirstName(userProfile.getFirstName()); user.setLastName(userProfile.getLastName()); user.setUserPassword(md5.getHash(userProfile.getPassword())); user.setEMail(userProfile.getEmail()); user.setCity(userProfile.getCity()); user.setCountry(userProfile.getCountry()); user.setState(userProfile.getState()); user.setBirthday(date); user.setSex(Boolean.parseBoolean(userProfile.getSex())); dataFacade.createUser(user); } catch (ParseException e1) { e1.printStackTrace(); } catch (InstantiationException e) { throw new ServletException(e); } catch (IllegalAccessException e) { throw new ServletException(e); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } /*catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ return new ModelAndView(USER_PROFILE_VIEW, model); } }
|
Валидация: | Код | package ua.org.teos.web.validation;
import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils;
import java.util.regex.Matcher; import java.util.regex.Pattern;
import ua.org.teos.web.form.Registration;
public class RegistrationValidation { private Pattern pattern; private Matcher matcher; private static final String PASSWORD_PATTERN = "([\\w]+)"; public RegistrationValidation() { pattern = Pattern.compile(PASSWORD_PATTERN); } /** * Валидация формы регистрации */ private boolean validatePassword(final String password) { matcher = pattern.matcher(password); return matcher.matches(); } public void validate(Object target, Errors errors) { Registration registration = (Registration) target; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "NotEmpty.registration.userName", "First Name must not be Empty."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "NotEmpty.registration.lastName", "Last Name must not be Empty."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty.registration.password", "Password must not be Empty."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword", "NotEmpty.registration.confirmPassword", "Password must not be Empty."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "NotEmpty.registration.email", "E-Mail must not be Empty."); if (registration.getFirstName().length() > 200) { errors.rejectValue("firstName", "validFirstName.registration.firstName", "Имя должно быть меньше 50 символов"); } if (registration.getLastName().length() > 200) { errors.rejectValue("lastName", "validLastName.registration.firstName", "Фамилия должна быть меньше 50 символов"); } if (registration.getEmail().length() > 100) { errors.rejectValue("email", "validEmail.registration.email", "E-mail должен быть меньше 50 символов"); } if (registration.getPassword().length() < 6) { errors.rejectValue("password", "validPassword.registration.password", "Пароль должен быть больше 5 символов."); } else if (registration.getPassword().length() > 50) { errors.rejectValue("password", "validPassword.registration.password", "Пароль должен быть меньше 50 символов"); } else if (!validatePassword(registration.getPassword())) { errors.rejectValue("password", "validPassword.registration.password", "Пароль должен быть из букв латинского алфавита и цифр"); } else if (!(registration.getPassword()).equals(registration.getConfirmPassword())) { errors.rejectValue("password", "matchingPassword.registration.password", "Password и Confirm Password не совпадают"); }
} }
|
| Код | package ua.org.teos.web.validation;
import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils;
import java.util.regex.Matcher; import java.util.regex.Pattern;
import ua.org.teos.web.form.UserProfile;
public class UserProfileValidation { private Pattern pattern; private Matcher matcher; private static final String PASSWORD_PATTERN = "([\\w]+)"; public UserProfileValidation() { pattern = Pattern.compile(PASSWORD_PATTERN); } /** * Валидация формы профиля пользователя */ private boolean validatePassword(final String password) { matcher = pattern.matcher(password); return matcher.matches(); } public void validate(Object target, Errors errors) { UserProfile userProfile = (UserProfile) target; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty.userProfile.password", "Password must not be Empty."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "NotEmpty.userProfile.email", "E-Mail must not be Empty."); if (userProfile.getFirstName().length() > 200) { errors.rejectValue("firstName", "validFirstName.userProfile.firstName", "Имя должно быть меньше 200 символов"); } if (userProfile.getLastName().length() > 200) { errors.rejectValue("lastName", "validLastName.userProfile.firstName", "Фамилия должна быть меньше 200 символов"); } if (userProfile.getEmail().length() > 100) { errors.rejectValue("email", "validEmail.userProfile.email", "E-mail должен быть меньше 100 символов"); } if (userProfile.getState().length() > 200) { errors.rejectValue("state", "validState.userProfile.state", "Название штата должно быть меньше 200 символов"); } if (userProfile.getCity().length() > 200) { errors.rejectValue("city", "validCity.userProfile.city", "Название города должно быть быть меньше 200 символов"); } if (userProfile.getSex() != null) { if ((!userProfile.getSex().equals("true")) && (!userProfile.getSex().equals("false"))) { errors.rejectValue("sex", "validSex.userProfile.month","Вы не выбрали пол"); } } //Валидация даты //-------------------------------------- if (userProfile.getDay()<1) { errors.rejectValue("day", "validDay.userProfile.day", "Вы не выбрали день рождения"); } if ((userProfile.getYear()<1920) || (userProfile.getYear()>2002)) { errors.rejectValue("year", "validYear.userProfile.year", "Вы не выбрали год рождения"); } if ((Integer.parseInt(userProfile.getMonth())<1) || (Integer.parseInt(userProfile.getMonth())>12)) { errors.rejectValue("month", "validMonth.userProfile.month", "Вы не выбрали месяц"); } if (userProfile.getMonth().equals("2") && userProfile.getDay()>29) { errors.rejectValue("month", "validMonth.userProfile.month", "В феврале может быть не больше 29-и дней"); } if (userProfile.getMonth().equals("4") && userProfile.getDay()>30) { errors.rejectValue("month", "validMonth.userProfile.month", "В апреле только 30 дней"); } if (userProfile.getMonth().equals("6") && userProfile.getDay()>30) { errors.rejectValue("month", "validMonth.userProfile.month", "В июне только 30 дней"); } if (userProfile.getMonth().equals("9") && userProfile.getDay()>30) { errors.rejectValue("month", "validMonth.userProfile.month", "В сеньтябре только 30 дней"); } if (userProfile.getMonth().equals("11") && userProfile.getDay()>30) { errors.rejectValue("month", "validMonth.userProfile.month", "В ноябре только 30 дней"); } //------------------------------- if (userProfile.getPassword().length() < 6) { errors.rejectValue("password", "validPassword.userProfile.password", "Пароль должен быть больше 5 символов."); } else if (userProfile.getPassword().length() > 50) { errors.rejectValue("password", "validPassword.userProfile.password", "Пароль должен быть меньше 50 символов"); } else if (!validatePassword(userProfile.getPassword())) { errors.rejectValue("password", "validPassword.userProfile.password", "Пароль должен быть из букв латинского алфавита и цифр"); } else if (!(userProfile.getPassword()).equals(userProfile.getConfirmPassword())) { errors.rejectValue("password", "matchingPassword.userProfile.password", "Password и Confirm Password не совпадают"); }
} }
|
Jsp: registration.jsp | Код | <?xml version="1.0" encoding="UTF-8" ?> <%@ 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=UTF-8"%> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ page import="static ua.org.teos.web.TeosUrl.*" %> <%@ page import="static ua.org.teos.web.form.TeosCommand.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title><spring:message code="label.registration"/></title> </head> <body> <span style="float: right"> <a href="?lang=en">EN</a> | <a href="?lang=ru">RU</a> | <a href="?lang=uk">UA</a> </span> <form:form method="Post" action="<%=REGISTRATION_URL%>" commandName="<%=REGISTRATION_COMMAND%>"> <table> <tr><td style="color:red;"><form:errors path="firstName" /></td></tr> <tr><td><spring:message code="label.first.name"/>:</td><td><form:input path="firstName" /></td></tr>
<tr><td style="color:red;"><form:errors path="lastName" /></td></tr> <tr><td><spring:message code="label.last.name"/>:</td><td><form:input path="lastName" /></td></tr>
<tr><td style="color:red;"><form:errors path="password" /></td></tr> <tr><td><spring:message code="label.password"/>:</td><td><form:password path="password" /></td></tr>
<tr><td style="color:red;"><form:errors path="confirmPassword" /></td></tr> <tr><td><spring:message code="label.password.confirm"/>:</td><td><form:password path="confirmPassword" /></td></tr>
<tr><td style="color:red;"><form:errors path="email" /></td></tr> <tr><td><spring:message code="label.email"/>:</td><td><form:input path="email" /></td></tr>
<tr><td><input type="submit" value="<spring:message code="label.registration.submit"/>" /></td></tr> </table> </form:form> </body> </html>
|
user_profile.jsp | Код | <?xml version="1.0" encoding="UTF-8" ?> <%@ 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=UTF-8"%> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ page import="static ua.org.teos.web.TeosUrl.*" %> <%@ page import="static ua.org.teos.web.form.TeosCommand.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title><spring:message code="label.user.profile"/></title> </head> <body> <span style="float: right"> <a href="?lang=en">EN</a> | <a href="?lang=ru">RU</a> | <a href="?lang=uk">UA</a> </span> <form:form method="Post" action="<%=USER_PROFILE_URL%>" commandName="<%=USER_PROFILE_COMMAND%>" enctype="multipart/form-data"> <table> <tr><td style="color:red;"><form:errors path="firstName" /></td></tr> <tr><td><spring:message code="label.first.name"/>:</td><td><form:input path="firstName" /></td></tr>
<tr><td style="color:red;"><form:errors path="lastName" /></td></tr> <tr><td><spring:message code="label.last.name"/>:</td><td><form:input path="lastName" /></td></tr>
<tr><td style="color:red;"><form:errors path="password" /></td></tr> <tr><td><spring:message code="label.password"/>:</td><td><form:password path="password" /></td></tr>
<tr><td style="color:red;"><form:errors path="confirmPassword" /></td></tr> <tr><td><spring:message code="label.password.confirm"/>:</td><td><form:password path="confirmPassword" /></td></tr>
<tr><td style="color:red;"><form:errors path="email" /></td></tr> <tr><td><spring:message code="label.email"/>:</td><td><form:input path="email" /></td></tr>
<tr><td style="color:red;"><form:errors path="sex" /></td></tr> <tr> <td>Gender:</td> <td> <form:radiobutton path="sex" value="true" label="M" /> <form:radiobutton path="sex" value="false" label="F" /> </td> </tr>
<tr><td style="color:red;"><form:errors path="day" /><form:errors path="month" /><form:errors path="year" /></td></tr> <tr> <td>Date of birth.</td> <td> Day: <form:select path="day"> <c:forEach var="i" begin="1" end="31"> <form:option value="${i}"></form:option> </c:forEach> </form:select> Month: <form:select path="month"> <form:option value="1" label="January"></form:option> <form:option value="2" label="February"></form:option> <form:option value="3" label="March"></form:option> <form:option value="4" label="April"></form:option> <form:option value="5" label="May"></form:option> <form:option value="6" label="June"></form:option> <form:option value="7" label="July"></form:option> <form:option value="8" label="August"></form:option> <form:option value="9" label="September"></form:option> <form:option value="10" label="October"></form:option> <form:option value="11" label="November"></form:option> <form:option value="12" label="December"></form:option> </form:select> Year: <form:select path="year"> <c:forEach var="i" begin="1920" end="2002"> <form:option value="${i}"></form:option> </c:forEach> </form:select> </td> </tr>
<tr><td style="color:red;"><form:errors path="country" /></td></tr> <tr><td><spring:message code="label.country"/>:</td><td> <form:select path="country"> <form:option value="0" label="Select" /> <form:options items="${countries}" itemValue="id" itemLabel="name"/> </form:select> </td></tr>
<tr><td style="color:red;"><form:errors path="state" /></td></tr> <tr><td>State:</td><td><form:input path="state" /></td></tr>
<tr><td style="color:red;"><form:errors path="city" /></td></tr> <tr><td>City:</td><td><form:input path="city" /></td></tr>
<tr><td>Avatar:</td><td><input type="file" name="avatar" /></td></tr>
<tr><td><input type="submit" value="<spring:message code="label.save"/>" /></td></tr> </table> </form:form> </body> </html>
|
|