类库
后台代码
JAVA BEAN
public class User implements Serializable {
private String userName;
private String password;
private String email;
private Date birthday;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
DAO
// 只负责CRUD
public interface UserDao {
void save(User user);
User findUser(String username);
User findUser(String username,String password);
}
public class UserDaoXml implements UserDao {
@Override
public void save(User user) {
try {
Document document = Dom4JUtil.getDocument();
Element root = document.getRootElement();
root.addElement("user")
.addAttribute("username", user.getUserName())
.addAttribute("password", user.getPassword())
.addAttribute("email", user.getEmail())
.addAttribute("birthday", user.getBirthday().toLocaleString());
Dom4JUtil.write2xml(document);
} catch (Exception e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
@Override
public User findUser(String username) {
try {
Document document = Dom4JUtil.getDocument();
Node node = document.selectSingleNode("//user[@username='"+username+"']");
if(node == null)
return null;
User user=new User();
user.setUserName(node.valueOf("@username"));
user.setPassword(node.valueOf("@password"));
user.setEmail(node.valueOf("@email"));
String sbirthday = node.valueOf("@birthday");
Date birthday = null;
if(sbirthday!=null&&sbirthday.equals("")) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
birthday = df.parse(sbirthday);
}
user.setBirthday(birthday);
return user;
} catch (Exception e) {
// TODO: handle exception
throw new RuntimeException(e);
}
}
@Override
public User findUser(String username, String password) {
try {
Document document = Dom4JUtil.getDocument();
Node node = document.selectSingleNode("//user[@username='"+username+"' and @password='"+password+"']");
if(node == null)
return null;
User user=new User();
user.setUserName(node.valueOf("@username"));
user.setPassword(node.valueOf("@password"));
user.setEmail(node.valueOf("@email"));
String sbirthday = node.valueOf("@birthday");
Date birthday = null;
if(sbirthday!=null&&sbirthday.equals("")) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
birthday = df.parse(sbirthday);
}
user.setBirthday(birthday);
return user;
} catch (Exception e) {
// TODO: handle exception
throw new RuntimeException(e);
}
}
}
service
public interface BusinessService {
void regist(User user) throws UserExistsException;
User login (String username,String password);
}
public class BusinessServiceImpl implements BusinessService {
private UserDao dao = new UserDaoXml();
@Override
public void regist(User user) throws UserExistsException {
if(user == null) {
throw new IllegalArgumentException();
}
User dbUser = dao.findUser(user.getUserName());
if(dbUser != null) {
throw new UserExistsException("The username \""+user.getUserName()+"\"已经存在了");
}
dao.save(user);
}
@Override
public User login(String username, String password) {
return dao.findUser(username,password);
}
}
Util
public class Dom4JUtil {
private static String dbfilePath;
static {
ClassLoader cl= Dom4JUtil.class.getClassLoader();
URL url = cl.getResource("User.xml");
dbfilePath = url.getPath();
}
public static Document getDocument() throws DocumentException {
SAXReader reader = new SAXReader();
return reader.read(dbfilePath);
}
public static void write2xml(Document document) throws Exception {
OutputStream out = new FileOutputStream(dbfilePath);
XMLWriter writer = new XMLWriter(out);
writer.write(document);
writer.close();
}
}
单元测试
public class BusinessServiceImplTest {
private static BusinessService s=null;
// 在初始化类时执行,只执行一次
@BeforeClass
public static void m1() {
s = new BusinessServiceImpl();
System.out.println("BeforeClass");
}
@AfterClass
public static void m2() {
s=null;
System.out.println("AfterClass");
}
// 在每个测试执行时执行
@Before
public void b1() {
System.out.println("Before");
}
@After
public void b2() {
System.out.println("After");
}
@Test
public void testRegist() throws UserExistsException{
User user = new User();
user.setUserName("zxn");
user.setPassword("123");
user.setEmail("zxn@123.com");
user.setBirthday(new Date());
s.regist(user);
}
@Test(expected = UserExistsException.class)
public void testRegist1() throws UserExistsException{
User user = new User();
user.setUserName("zxn");
user.setPassword("123");
user.setEmail("zxn@123.com");
user.setBirthday(new Date());
s.regist(user);
}
@Test
public void testLogin(){
User user = s.login("zxn", "123");
assertNotNull(user);
user = s.login("zxn", "1234");
assertNotNull(user);
}
}
前台页面
主页
引入jstl类库
<c:if test="${sessionScope.user == null }">
<a href="${pageContext.request.contextPath }/regist.jsp">注册</a>
<a href="${pageContext.request.contextPath }/login.jsp">登陆</a>
</c:if>
<c:if test="${ sessionScope.user!=null}">
欢迎您: ${sessionScope.user.userName }
<a href="${pageContext.request.contextPath }/LogoutServlet">注销</a>
</c:if>
登陆
<form action="${pageContext.request.contextPath }/servlet/LoginServlet" method="post" enctype="application/x-www-form-urlencoded">
<table border="1" width="438">
<tr>
<th>用户名:</th>
<td>
<input type="text" name="username" />
</td>
</tr>
<tr>
<th>密码:</th>
<td>
<input type="password" name="password" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="登陆"/>
</td>
</tr>
</table>
</form>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = s.login(username, password);
if(user == null) {
response.getWriter().write("错误的用户名或密码,2秒后转向登陆界面");
response.setHeader("Refresh", "2,URL="+request.getContextPath()+"/login.jsp");
return;
}
request.getSession().setAttribute("user", user);
response.getWriter().write("登陆成功,2秒后转向主页");
response.setHeader("Refresh", "2;URL="+request.getContextPath()+"/Index.jsp");
}
注销
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
request.getSession().removeAttribute("user");
response.getWriter().write("注销成功,2秒后转向登陆界面");
response.setHeader("Refresh", "2,URL="+request.getContextPath());
}
注册
<form action="${pageContext.request.contextPath}/servlet/RegistServlet" method="post" enctype="application/x-www-form-urlencoded">
<!--
约定优于编码:遵守好的约定,会使代码编写更加高效
目前约定:表单的字段名和JavaBean的属性名保持了一致
-->
<table border="1" width="738">
<tr>
<td>用户名:</td>
<td>
<input type="text" name="username" value="${formBean.username}"/>${formBean.errors.username}
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<input type="password" name="password" value=""/>${formBean.errors.password}
</td>
</tr>
<tr>
<td>确认密码:</td>
<td>
<input type="password" name="repassword"/>${formBean.errors.repassword}
</td>
</tr>
<tr>
<td>邮箱:</td>
<td>
<input type="text" name="email" value="${formBean.email}"/>${formBean.errors.email}
</td>
</tr>
<tr>
<td>生日yyyy-MM-dd:</td>
<td>
<input type="text" name="birthday" value="${formBean.birthday}" readonly="readonly" onClick="return showCalendar('birthday', 'y-mm-dd');"/>${formBean.errors.birthday}
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="注册"/>
</td>
</tr>
</table>
</form>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String encoding = "UTF-8";
request.setCharacterEncoding(encoding);
response.setContentType("text/html;charset="+encoding);
// 获取表单数据,封装到javaBean中
UserFormBean formBean = FileBeanUtil.fileBean(request, UserFormBean.class);
// 数据验证;服务器端验证
if(!formBean.validate()) {
request.setAttribute("formBean", formBean);
request.getRequestDispatcher("/regist.jsp").forward(request, response);
return;
}
// 填充模型
User user = new User();
ConvertUtils.register(new DateLocaleConverter(), Date.class);
try {
BeanUtils.copyProperties(user, formBean);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
try {
s.regist(user);
response.getWriter().write("保存成功!2秒后转向主页");
response.setHeader("Refresh", "2;URL="+request.getContextPath());
} catch (Exception e) {
formBean.getErrors().put("username", "用户名已经存在了");
request.setAttribute("formBean", formBean);
request.getRequestDispatcher("/regist.jsp").forward(request, response);
return;
}
}