补充知识:
获得当前web应用的目录:
①在.java文件当中:request.getContextPath()相当 于/day09_user
②在.jsp文件当中:${pageContext.request.contextPath}相当于/day09_user
例17、用户注册与登录编程。
第一步、导包,WebRoot ->WEB-INF->lib
commons-beanutils-1.8.3.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
jaxen-1.1-beta-6.jar
jstl-1.2.jar
junit-4.8.2.jar
standard.jar
第二步、建包package。
cn.itcast.dao
cn.itcast.dao.impl
cn.itcast.domain
cn.itcast.exception
cn.itcast.service.impl
cn.itcast.utils
cn.itcast.web.controller
cn.itcast.web.form
cn.itcast.web.UI junit.test
第三步、users.xml
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user username="aaa" password="123" id="123455" email="[email protected]" birthday="1980-09-01" nickname="强子"/>
</users>
第四步、User.java
package cn.itcast.domain;
import java.util.Date;
public class User {
private String id;
private String username;
private String password;
private String email;
private Date birthday;
private String nickname;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
}
第五步、XmlUtils.java
package cn.itcast.utils;
import*;
public class XmlUtils {
private static String filepath;
static{
filepath=XmlUtils.class.getClassLoader().getResource("users.xml").getPath();
}
public static Document getDocument() throws Exception{
SAXReader reader=new SAXReader();
Document document=reader.read(new File(filepath));
return document;
}
public static void write2Xml(Document document) throws Exception{
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer=new XMLWriter(new FileOutputStream(filepath),format);
writer.write(document);
writer.close();
}
}
第六步: UserDaoImpl.java
package cn.itcast.dao.impl;
import *;
public class UserDaoImpl implements UserDao {
public void add(User user){
try{
Document document=XmlUtils.getDocument();
Element root=document.getRootElement();
Element user_tag=root.addElement("user");
user_tag.setAttributeValue("id", user.getId());
user_tag.setAttributeValue("username", user.getUsername());
user_tag.setAttributeValue("password", user.getPassword());
user_tag.setAttributeValue("email", user.getEmail());
user_tag.setAttributeValue("nickname", user.getNickname());
user_tag.setAttributeValue("birthday", user.getBirthday()==null?"":user.getBirthday().toLocaleString());
XmlUtils.write2Xml(document);
}catch(Exception e){
throw new RuntimeException(e);
}
}
public User find(String username,String password){
try{
Document document=XmlUtils.getDocument();
Element e=(Element)document.selectSingleNode("//user[@username='"+username+"' and @password='"+password+"']");
if(e==null){
return null;
}
User user=new User();
String data=e.attributeValue("birthday");
if(data==null||data.equals("")){
user.setBirthday(null);
}else{
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
user.setBirthday(df.parse(data));
}
user.setEmail(e.attributeValue("email"));
user.setId(e.attributeValue("id"));
user.setNickname(e.attributeValue("nickname"));
user.setPassword(password);
user.setUsername(username);
return user;
}catch(Exception e){
throw new RuntimeException(e);
}
}
//查找注册的用户是否在数据库中存在
public boolean find(String username){
try{
Document document=XmlUtils.getDocument();
Element e=(Element)document.selectSingleNode("//user[@username='"+username+"']");
if(e==null){
return false;
}else{
return true;}
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
第七步、UserDao.java
package cn.itcast.dao;
import cn.itcast.domain.User;
public interface UserDao {
void add(User user);
User find(String username, String password);
//查找注册的用户是否在数据库中存在
boolean find(String username);
}
第八步、UserExistException.java
package cn.itcast.exception;
public class UserExistException extends Exception{
public UserExistException() {
super();
}
public UserExistException(String message, Throwable cause) {
super(message, cause);
}
public UserExistException(String message) {
super(message);
}
public UserExistException(Throwable cause) {
super(cause);
}
}
第九步、BusinessServiceImpl.java
package cn.itcast.service.impl;
import *;
//对web层提供所有的业务服务
public class BusinessServiceImpl {
private UserDao dao=new UserDaoImpl();
//对web层提供注册服务
public void register(User user) throws UserExistException{
//先判断当前要注册的用户是否存在
boolean b = dao.find(user.getUsername());
if(b){
throw new UserExistException();//发现要注册的用户已经存在,则给web层抛出一个编译时异常,提醒web层处理这个异常,给用户一个友好提示
}else{
user.setPassword(ServiceUtils.md5(user.getPassword()));
dao.add(user);
}
}
//对web层提供登录服务
public User login(String username,String password){
password=ServiceUtils.md5(password);//解密
return dao.find(username, password);
}
}
第十步、ServiceUtils.java
package cn.itcast.utils;
import *;
public class ServiceUtils {
public static String md5(String message){
try {
MessageDigest md=MessageDigest.getInstance("md5");
byte[] md5=md.digest(message.getBytes());
BASE64Encoder encoder=new BASE64Encoder();
return encoder.encode(md5);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
第十一步、WebUtils.java
package cn.itcast.utils;
import *;
public class WebUtils {
public static <T> T request2Bean(HttpServletRequest request,Class<T> beanClass){
try {
//1、创建要封转数据的bean,用泛型,上层数据就没必要强转了
T bean=beanClass.newInstance();
//2、把request中数据整到bean中
Enumeration e=request.getParameterNames();
while(e.hasMoreElements()){
String name=(String)e.nextElement();
String value=request.getParameter(name);
BeanUtils.setProperty(bean, name, value);
}
return bean;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void copyBean(Object src,Object dest){
//注册日期转换器
ConvertUtils.register(new Converter(){
public Object convert(Class type, Object value) {
if(value==null){
return null;
}
String str=(String)value;
if(str.trim().equals("")){
return null;
}
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
try {
return df.parse(str);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}, Date.class);
try {
BeanUtils.copyProperties(dest, src);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//产生全世界唯一的ID
public static String generateID(){
return UUID.randomUUID().toString();
}
}
第十二步、RegisterForm.java
package cn.itcast.web.form;
import *;
public class RegisterForm {
private String username;
private String password;
private String password2;
private String email;
private String birthday;
private String nickname;
private Map errors=new HashMap();
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 getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public Map getErrors() {
return errors;
}
public void setErrors(Map errors) {
this.errors = errors;
}
//用户名不能为空,并且要3-8为字母
//密码不能为空,并且是3-8位数字
//确认密码不能为空,并且要和一次一致
//电子邮箱不能为空,并且要是一个格式合法的邮箱
//生日可以为空,不为空时必须要是一个日期
//昵称不可以为空,并且要是汉字
public boolean validate(){
boolean isOK=true;
if(this.username==null||this.username.trim().equals("")){
isOK=false;
errors.put("username", "用户名不能为空");
}else{
if(!this.username.matches("[a-zA-Z0-9]{3,8}")){
isOK=false;
errors.put("username", "用户名必须是3-8为字母或者数字");
}
}
if(this.password==null||this.password.trim().equals("")){
isOK=false;
errors.put("password", "密码不能为空");
}else{
if(!this.password.matches("\\d{3,8}")){
isOK=false;
errors.put("password", "密码必须是3-8为数字");
}
}
if(this.password2==null||this.password2.trim().equals("")){
isOK=false;
errors.put("password2", "确认密码不能为空");
}else{
if(!this.password.equals(this.password2)){
isOK=false;
errors.put("password2", "两次密码要一致");
}
}
if(this.email==null||this.email.trim().equals("")){
isOK=false;
errors.put("email", "邮箱不能为空");
}else{
if(!this.email.matches("\\w+@\\w+(\\.\\w+)+")){
isOK=false;
errors.put("email", "邮箱格式不对");
}
}
if(this.birthday!=null&& !this.birthday.trim().equals("")){
try{DateLocaleConverter dic=new DateLocaleConverter();//beanutils中的本地日期转换器
dic.convert(this.birthday,"yyyy-MM-dd");}
catch(Exception e){
isOK=false;
errors.put("birthday", "日期格式不对");
}
}
if(this.nickname==null&& this.birthday.trim().equals("")){
isOK=false;
errors.put("nickname", "昵称不能为空");
}else{
if(!this.nickname.matches("^([\u4e00-\u9fa5]+)$")){
isOK=false;
errors.put("nickname", "昵称必须是汉字!");
}
}
return isOK;
}
}
第十三步、RegisterUIServlet.java
package cn.itcast.web.UI;
import *
//为用提供注册界面
public class RegisterUIServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/register.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
附录:register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script language="javascript" src="${pageContext.request.contextPath}/js/Calendar.js"> </script>
<style> body{ margin:0px; padding:0px; overflow:hidden; font-size:12px; background:48CFEC; color:#FFF; text-align:left; } #neirong{ margin-top:30px; margin-left:30px; } #form{ margin-bottom:5px; } .wen{ width:180px; } #input div{ margin-bottom:5px; } #input2{ margin-top:10px; margin-left:80px; } #input2 input { width:50px; margin-right:20px;} </style>
<body>
<div>
<img src="${pageContext.request.contextPath}/images/head.gif"/>
</div>
<div>
<div id="neirong">
<h2>注册须知:</h2><br/>
<div id="shengming1">
<p>1、在本站注册的会员,必须遵守《互联网电子公告服务管理规定》,不得在本站发表诽谤他人,侵犯他人隐私,侵犯他人知识产权,传播病毒,政治言论,商业机密等信息。</p>
</div>
<div id="shengming2">
<p>2、在所有在本站发表的文章,本站都具有最终编辑权,并且保留用于印刷或想第三方发表的权利,如果您的资料不齐全,我们将有权不作任何通知使用您在本站发布的作品。
</p>
</div>
<div id="form">
<form name="form1" action="${pageContext.request.contextPath}/servlet/RegisterServlet" method="post">
<div id="input">
<div>登陆账号: <input class="wen" type="text" name="username" value="${form.username}"/>
<span>${form.errors.username}</span></div>
<div>重复密码: <input class="wen" type="password" name="password" value="${form.password}" /><span>${form.errors.password}</span></div>
<div>确认密码: <input class="wen" type="password" name="password2" value="${form.password2}"/><span>${form.errors.password2}</span></div>
<div>电子邮件: <input class="wen" type="text" name="email"value="${form.email}"/><span>${form.errors.email}</span></div>
<div>您的昵称: <input class="wen" type="text" name="nickname" value="${form.nickname}"/><span>${form.errors.nickname}</span></div>
<div>您的生日: <input class="wen" type="text" name="birthday" id="birthday" value="1990-12-1"/><span>${form.errors.birthday}</span>
<input name="" type="button" onclick="MyCalendar.SetDate(this,document.getElementById('birthday'))" value="选择" />
<div>图片认证: <input type="text" class="wen" name="image"/></div>
<div id="input2">
<input type="reset" value="重置"/>
<input type="submit" value="注册"/>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
第十四步、ServiceTest.java
package junit.test;
import *;
public class ServiceTest {
@Test
public void testRegister(){
User user=new User();
user.setBirthday(new Date());
user.setEmail("[email protected]");
user.setId("111111");
user.setNickname("小强");
user.setPassword("11");
user.setUsername("fandong");
BusinessServiceImpl service=new BusinessServiceImpl();
try {
service.register(user);
System.out.println("注册成功");
} catch (UserExistException e) {
// TODO Auto-generated catch block
System.out.println("用户已经存在");
}
}
@Test
public void testLogin(){
BusinessServiceImpl service=new BusinessServiceImpl();
User user=service.login("fandong","11");
System.out.println(user);
}
}
第十五步、UserDaoTest.java
package junit.test;
import *
public class UserDaoTest {
@Test
public void testAdd(){
User user=new User();
user.setBirthday(new Date());
user.setEmail("[email protected]");
user.setId("111111");
user.setNickname("小强");
user.setPassword("11");
user.setUsername("qiang");
UserDao dao=new UserDaoImpl();
dao.add(user);
}
@Test
public void testFind(){
UserDao dao=new UserDaoImpl();
dao.find("aaa", "123");
}
@Test
public void testFindByUsername(){
UserDao dao=new UserDaoImpl();
dao.find("aaa");
}
}
以下是登陆制作:
第一步、LoginUIServlet.java
package cn.itcast.web.UI;
import *;
//提供登录界面
public class LoginUIServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
第二步、login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登陆界面</title>
<meta http-equiv="content-type" content="text/heml;charset=UTF-8">
<style> body{ margin:0px; padding:0px; font-size:12px; background:#016AA9; overflow:hidden; text-align:center; } #container{ width:980px; } #login{ background-image:url(../images/login.gif); width:937px; height:333px; margin-top:115px; margin-left:15px; } #form{ margin-top:155px; margin-left:-50px; } #input div{ margin-bottom:5px; } #input div input{ width:120px; height:16px; background:#292929; border:0px; color:#6CD0FF; } #btn{ margin-left:18px; margin-top:10px; } #btn input{ border=0; color:white; width:49px; height:18px; margin-left:10px; background-image:url(../images/dl.gif); cursor:hand; } </style>
</head>
<body>
<div id="container">
<div id="login">
<div id="form">
<form action="${pageContext.request.contextPath}/servlet/LoginServlet" method="post">
<div id="input">
<div> 用户:<input type="text" name="username"/><br/></div>
<div> 密码:<input type="password" name="password"/><br/></div>
</div>
<div id="btn">
<input type="submit" value="登录"/>
<input type="button" value="注册" onclick="window.location.href='register.html'"/>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
package cn.itcast.web.controller;
import *;
//处理登录请求
//ctrl+shift+o可以选择继承包
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username=request.getParameter("username");
String password=request.getParameter("password");
BusinessServiceImpl service=new BusinessServiceImpl();
User user=service.login(username, password);
if(user!=null){
request.getSession().setAttribute("user", user);
//让用户登陆成功后跳转到首页
response.sendRedirect(request.getContextPath()+"/index.jsp");
return;
}
request.setAttribute("message", "用户名或者密码错误");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
第四步、LoginoutServlet.java
package cn.itcast.web.controller;
import *;
//处理用户注销请求
public class LoginoutServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession(false);
if(session!=null){
session.removeAttribute("user");
}
//注销成功,跳到全局消息页面显示注销成功消息,并控制消息显示页面过三秒后跳转到首页;
request.setAttribute("message", "注销成功,浏览器将在3秒后跳转!<meta http-equiv='refresh' content='3;url="+request.getContextPath()+"/index.jsp'/>");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
附录:
Index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>首页</title>
</head>
<body style="text-align:center">
<h2>xxxxx网站</h2><br/>
<c:if test="${user!=null}">
欢迎您 :${user.nickname }
<a href="${pageContext.request.contextPath}/servlet/LoginoutServlet">注销</a>
</c:if>
<c:if test="${user==null}">
<a href="${pageContext.request.contextPath}/servlet/RegisterUIServlet">注册</a>
<a href="${pageContext.request.contextPath}/servlet/LoginUIServlet">登录</a>
</c:if>
</body>
</html>
message.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>网站全局消息显示</title>
</head>
<body>
${message}
</body>
</html>
Readme.text
1、搭建开发环境
1.1导开发包
dom4j开发包
jstl开发包
beanUtils开发包
1.2创建组织程序的包
cn.itcast.domain
cn.itcast.dao
cn.itcast.dao.impl
cn.itcast.service
cn.itcast.service.impl
cn.itcast.web.controller(处理请求的servlet)
cn.itcast.web.UI (给用户提供用户界面)
cn.itcast.utils
junit.test
WEB-INF/jsp 保存网站所有的JSP
1.3创建代表数据库的xml文件
在类目录下创建一个代表数据库的users.xml文件