用户注册和登录案例

用户注册和登录案例

1.功能分析

1、技术架构:三层架构(表现层MVC:M:model   V:View C:Controller)

2、要求:JSP中不能出现一行java脚本或java表达式。除了指令<%@%>,其余地方不能有<%%>

3、数据库:临时使用xml。解析使用Dom4j

4、必须知道要干什么?

用户注册和登录案例_第1张图片

5、开发步骤:

a、建立工程,搭建开发环境(拷贝jar包、建立配置文件)

dom4j.jar

jaxen.jar

commons-beanutils.jar

commons-logging.jar

standard.jar

jstl.jar

b、建立类所用的包

cn.itcast.domain:放JavaBean    弄出数据库

cn.itcast.dao:放Dao接口

cn.itcast.dao.impl:放Dao接口的实现

cn.itcast.servcie:业务接口

cn.itcast.service.impl:业务接口实现

cn.itcast.web.controller:Servlet控制器

//WEB-INF/pages:用户无法直接访问(只能靠转发)

 

把握两点:

1、domain中的javabean

2、业务接口

 

知识点:用户输入数据的验证

1、客户端验证:使用js代码。减轻服务器的负担

2、服务器端验证:使用java代码。安全

3、实际开发中:1+2

注册流程

用户注册和登录案例_第2张图片

2.代码编写

1.bean包

User.java:

package com.heima.bean;

import java.io.Serializable;
import java.util.Date;

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;
	}
}
UserFormBean.java:
package com.heima.web.formbean;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

//此bean专门用来封装页面的数据
public class UserFormBean {

	private String username;

	private String password;
	
	private String repassword;

	private String email;

	private String birthday;
	
	private Map errors = new HashMap() ;

	public Map getErrors() {
		return errors;
	}

	public String getUsername() {
		return username;
	}
	
	public String getPassword() {
		return password;
	}

	public String getRepassword() {
		return repassword;
	}

	public void setRepassword(String repassword) {
		this.repassword = repassword;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setUsername(String username) {
		this.username = username;
	}
	
	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 boolean validate(){
		//验证用户名
		if(username == "" || username == null){
			errors.put("username", "用户名不能为空") ;
		}else{
			if(username.length() > 8 || username.length() < 3){
				errors.put("username", "用户名长度必须在3~8位之间") ;
			}
		}
		
		//验证密码
		if(password == "" || password == null){
			errors.put("password", "密码不能为空") ;
		}else{
			if(password.length() > 8 || password.length() < 3){
				errors.put("password", "密码长度必须在3~8位之间") ;
			}
		}
		
		if(!repassword.equals(password)){
			errors.put("password", "两次密码输入不一致") ;
		}
		
		//验证邮箱
		if(email == "" || email == null){
			errors.put("email", "邮箱不能为空") ;
		}else{
			if(!email.matches("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$")) 
				errors.put("email", "邮箱格式不正确") ;
		}
		
		//验证生日
		if(birthday == "" || birthday == null){
			errors.put("birthday", "生日不能为空") ;
		}else{
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
//			try {
//				sdf.parse(birthday) ;
//			} catch (ParseException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			
			DateLocaleConverter dlc = new DateLocaleConverter() ;
			try {
				dlc.convert(birthday) ;
			} catch (Exception e) {
				errors.put("birthday", "日期格式错误") ;
			}
		}
		
		return errors.isEmpty() ;
	}
}

2.service层:业务逻辑层(数据服务层,为页面服务)

UserService:

package com.heima.service;

import com.heima.bean.User;
import com.heima.exception.UserExistsException;

public interface UserService {

	/**
	 * 根据用户名和密码登录
	 * @param username 用户名
	 * @param password 密码
	 * @return 登录成功返回此用户,否则返回null
	 */
	public User login(String username,String password ) ;
	
	/**
	 * 注册用户
	 * @param user 要注册的用户
	 * @throws UserExistsException 当用户名已经存在的时候,抛出一个用户已存在异常
	 */
	public void register(User user) throws UserExistsException ;
}

UesrServiceImpl.java:

package com.heima.service.impl;

import com.heima.bean.User;
import com.heima.dao.UserDao;
import com.heima.dao.impl.UserDaoImpl;
import com.heima.exception.UserExistsException;
import com.heima.service.UserService;

public class UserServiceImpl implements UserService {

	UserDao dao = new UserDaoImpl() ;
	
	public User login(String username, String password) {
		return dao.findUserByUserNameAndPassword(username, password);
	}

	public void register(User user) throws UserExistsException {
		//查找用户
		User u = dao.findUserByUserName(user.getUsername()) ;
		if(u == null)
			//说明用户没有注册过
			dao.add(user) ;
		else
			throw new UserExistsException() ;
	}
}


异常包:exception

UserExistsException.java:

package com.heima.exception;

public class UserExistsException extends Exception {

}

3.dao层:数据访问层(和数据库关联)

UserDao:

package com.heima.dao;

import com.heima.bean.User;

public interface UserDao {

	/**
	 * 根据用户名和密码查询用户
	 * @param username 用户名
	 * @param password 密码
	 * @return 查询到用户返回此用户,否则返回null
	 */
	public User findUserByUserNameAndPassword(String username,String password) ;
	
	/**
	 * 注册用户
	 * @param user 要注册的用户
	 */
	public void add(User user) ;
	
	/**
	 * 根据用户的名字查找用户
	 * @param name 用户的名字
	 * @return 查询到了返回此用户,否则返回null
	 */
	public User findUserByUserName(String name) ;
}
实现:

package com.heima.dao.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;

import com.heima.bean.User;
import com.heima.dao.UserDao;
import com.heima.utils.JaxpUtils;

public class UserDaoImpl implements UserDao {
//要操作xml文档,读取进来再写回去
	public User findUserByUserNameAndPassword(String username, String password) {
		//加载Dom树
		Document document = JaxpUtils.getDocument() ;
		//查询需要的node节点
		Node node = document.selectSingleNode("//user[@username='" + username+ "' and @password='" + password + "']") ;
		if(node != null){
			//找到了用户,封装数据
			User user = new User() ;
			user.setUsername(username) ;
			user.setPassword(password) ;
			user.setEmail(node.valueOf("@email")) ;
			String birthday = node.valueOf("@birthday") ;
			
			try {
				user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday)) ;
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return user;
		}
		
		return null;
	}

	public void add(User user) {
		//加载dom树
		Document document = JaxpUtils.getDocument() ;
		//拿到根节点
		Element root = document.getRootElement() ;
		//添加一个user节点
		root.addElement("user").addAttribute("username", user.getUsername())
				.addAttribute("password", user.getPassword())
				.addAttribute("email", user.getEmail())
				.addAttribute("birthday", new SimpleDateFormat("yyyy-MM-dd").format(user.getBirthday())) ;
		
		//将dom树保存到硬盘上
		JaxpUtils.write2xml(document) ;
		
	}

	public User findUserByUserName(String name) {
		//加载Dom树
				Document document = JaxpUtils.getDocument() ;
				//查询需要的node节点
				Node node = document.selectSingleNode("//user[@username='" + name +"']") ;
				if(node != null){
					//找到了用户,封装数据
					User user = new User() ;
					user.setUsername(name) ;
					user.setPassword("@password") ;
					user.setEmail(node.valueOf("@email")) ;
					String bithday = node.valueOf("@birthday") ;
					
					try {
						user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(bithday)) ;
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					return user;
				}
		return null;
	}

}


4.utils包

JaxpUtils.java:

package com.heima.utils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

//操作XML文件的方法
public class JaxpUtils {
	
	static String path ;
	
	static{
		path = JaxpUtils.class.getClassLoader().getResource("users.xml").getPath() ;
	}
	
	public static Document getDocument(){
		//创建一个dom4j解析器
		try {
			SAXReader reader = new SAXReader() ;
			Document document = reader.read(path) ;
			return document ;
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null ;
	}
	
	public static void write2xml(Document document){
		try {
			XMLWriter writer = new XMLWriter(new FileOutputStream(path), OutputFormat.createPrettyPrint()) ;
			writer.write(document) ;
			writer.close() ;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}

WebUtils.java:

package com.heima.utils;

import java.lang.reflect.InvocationTargetException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;

//专门为页面服务: 封装了页面的信息
public class WebUtils {

	
	/**
	 * @param clazz 往那个对象里面封装,把类型传递进来
	 * @param request 从request对象中取出数据
	 * @return
	 */
	public static  T fillFormBean(Class clazz,HttpServletRequest request){
		T t = null ;
		try {
			t = clazz.newInstance() ;
			BeanUtils.populate(t, request.getParameterMap()) ;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t ;
	}
}

控制器:

RegisterServlet.java:

package com.heima.web.serlvet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

import com.heima.bean.User;
import com.heima.exception.UserExistsException;
import com.heima.service.UserService;
import com.heima.service.impl.UserServiceImpl;
import com.heima.utils.WebUtils;
import com.heima.web.formbean.UserFormBean;
//完成注册的功能
public class RegisterServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		//第一步,先封装数据到userbean中   把页面的数据封装到UserFormBean中
		UserFormBean ufb = WebUtils.fillFormBean(UserFormBean.class, request) ;
		
		//第二步,验证数据
		if(ufb.validate()){
			//说明验证通过
			//第三步,将formbean中的数据拷贝到user对象
			User user = new User() ;
			//由于formbean中的生日是String类型,userbaen中的生日是Date类型,beanUtils类不能自动转换,因此必须注册一个日期类型转换器
			try {
				ConvertUtils.register(new DateLocaleConverter(), Date.class) ;
				BeanUtils.copyProperties(user, ufb) ;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			//第四步,注册用户
			//调用业务逻辑层完成注册
			UserService us = new UserServiceImpl() ;
			try {
				us.register(user) ;
				//注册成功
				//返回登陆页面
				response.getWriter().write("恭喜你,注册成功,2秒后转向登陆页面") ;
				response.setHeader("Refresh", "2;url=" + request.getContextPath() + "/login.jsp") ;
				//response.sendRedirect(request.getContextPath() + "/login.jsp") ;
				
			} catch (UserExistsException e) {
				//说明用户已经注册过了
				ufb.getErrors().put("username", "此用户名已经被注册过了,请换一个") ;
				//将ufb存入request对象
				request.setAttribute("user", ufb) ;
				request.getRequestDispatcher("/register.jsp").forward(request, response) ;
			}
			
		}else{
			//验证不通过
			//完成数据的回显操作,把ufb对象存放到request
			request.setAttribute("user", ufb) ;
			request.getRequestDispatcher("/register.jsp").forward(request, response) ;
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

LoginServlet.java:

package com.heima.web.serlvet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.heima.bean.User;
import com.heima.service.UserService;
import com.heima.service.impl.UserServiceImpl;

public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		//获取页面的数据
		String name = request.getParameter("username") ;
		String pass = request.getParameter("password") ;
		
		//验证数据(略)
		
		//调用service层完成业务逻辑
		UserService us = new UserServiceImpl() ;
		User user = us.login(name, pass) ;
		if(user != null){
			//合法用户
			request.getSession().setAttribute("loginuser", user) ;
			request.getRequestDispatcher("/main.jsp").forward(request, response) ;
		}else{
			//非法用户
			request.getSession().setAttribute("error", "用户名或者密码错误") ;
			response.sendRedirect(request.getContextPath() + "/login.jsp") ;
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

视图层:

index.jsp:


       注册
       登陆
  

register.jsp:

	
  
  
  
       

注册用户


姓名: ${user.errors.username }
密码: ${user.errors.password }
确认密码:
邮箱: ${user.errors.email }
生日: ${user.errors.birthday }
login.jsp:

 
      

登陆页面


${error }
姓名:
密码:
main.jsp:

      ${loginuser.username },欢迎你
  


你可能感兴趣的:(项目)