javaweb下MVC模式即学即用

<img src="http://img.blog.csdn.net/20150327153134076?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZ3JlZW5saWdodF83NDExMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />
1.搭建开发环境
    1.1 导入项目所需的开发包
        dom4j-1.6.1.jar
        jaxen-1.1-beta-6.jar
        commons-beanutils-1.8.0.jar
        commons-logging.jar
        jstl.jar
        standard.jar
        
    1.2 创建程序的包名
        cn.itcast.domain
        cn.itcast.dao
        cn.itcast.dao.impl
        cn.itcast.service
        cn.itcast.service.impl
        cn.itcast.web.controller  
        cn.itcast.web.UI  (user interface)(放为用户提供用户界面的servlet)
        cn.itcast.utils
        junit.test
        
        在web-inf\jsp目录,保存jsp页面
        
    1.3 在类目录下面,创建用于保存用户数据的xml文件(users.xml)
    
    
2、开发实体user
    private String id;
    private String username;
    private String password;
    private String email;
    private Date birthday;
    
3、开发dao(Data Access Object) 
    3.1  开发UserDaoXmlImpl
            public void add(User user)
            public User find(String username)
            public User find(String username,String password)
            
    3.2  抽取接口:UserDao
    
    3.3  开发工具类: XmlUtils 
    3.4  开发测试类:Junit

    
4、开发service(service 对web层提供所有的业务服务)
     4.1  开发BusinessServiceImp
             public void registerUser(User user) throws UserExistException
             public User loginUser(String username,String password);
            
    3.2  抽取接口:BusinessService
    
    3.3  开发工具类: WebUtils 
    3.4  开发测试类:Junit

            
 5、开发web层
     5.1 开发注册
         5.1.1  写一个RegisterUIServlet为用户提供注册界面,它收到请求,跳到register.jsp
         5.1.2  写register.jsp
         5.1.3  register.jsp提交请求,交给RegisterServlet处理
         5.1.4  写RegisterServlet
                 1.设计用于校验表单数据RegisterFormbean 
                 2、写WebUtils工具类,封装请求数据到formbean中
                 3、如果校验失败跳回到register.jsp,并回显错误信息
                 4、如果校验通过,调用service向数据库中注册用户
                 
     5.2 开发登陆
         5.2.1      写一个LoginUIServlet为用户提供注册界面,它收到请求,跳到login.jsp    
         5.2.2      login.jsp提交给LoginServlet处理登陆请求
        
    6.3 开发注销
        6.2.1      写一个LogoutUIServlet为用户提供注册界面,它收到请求,跳到logout.jsp    
         6.2.2      logout.jsp提交给LogoutServlet处理登陆请求
        
<img src="http://img.blog.csdn.net/20150327153218677?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZ3JlZW5saWdodF83NDExMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />

	
package he.junhua.domain;

import java.util.Date;

//实体类User
public class User {

	private String id;
	private String username;
	private String password;
	private Date birthday;
	private String email;
	
	
	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 Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
}		

//UserDao接口的实现	
package he.junhua.dao.impl;

import java.text.SimpleDateFormat;

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

import he.junhua.dao.UserDao;
import he.junhua.domain.User;
import he.junhua.utils.XmlUtils;

public class UserDaoXmlImpl 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("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;
			}
			
			//new出一个user用以存放查找所得信息
			User user =	new User();
			String date =	e.attributeValue("birthday");
			if(date==null||date.equals("")){
				user.setBirthday(null);
			}else{
				//将String转换成Date
				SimpleDateFormat format =	new SimpleDateFormat("yyyy-MM-dd");
				user.setBirthday(format.parse(date));
			}
			
			user.setUsername(e.attributeValue("username"));
			user.setPassword(e.attributeValue("password"));
			user.setId(e.attributeValue("id"));
			user.setEmail(e.attributeValue("email"));
			
			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+"']");//XPath
			
			//判断用户名是否存在
			if(e==null){
				return false;
			}
			return true;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
		
//抽取接口,以便以后对程序修改时就可以根据需要直接实现该接口(即重写以上的UserDaoImpl)
package he.junhua.dao;

import he.junhua.domain.User;

public interface UserDao {

	void add(User user);

	User find(String username, String password);

	//查找请求的用户是否存在
	boolean find(String username);

}		
		
//开发工具类XmlUtils,在这里引入了dom4j工具包
package he.junhua.utils;

import java.io.FileOutputStream;
import java.io.IOException;

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

public class XmlUtils {

	private static String filepath;
	static {
		filepath = XmlUtils.class.getClassLoader().getResource("users.xml")
				.getPath();
	}

	public static Document getDocument() throws DocumentException {
		SAXReader reader = new SAXReader();
		Document document = reader.read(filepath);
		return document;
	}
	
	public static void write2Xml(Document document) throws IOException{
        // Pretty print the document to System.out
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        XMLWriter writer = new XMLWriter(new FileOutputStream(filepath), format );
        writer.write( document );
        
        writer.close();
	}
}

//对上述代码的功能作一简单测试,如有错及时debug,否则继续前进
package junit.test;

import java.util.Date;

import he.junhua.dao.impl.UserDaoXmlImpl;
import he.junhua.domain.User;

import org.junit.Test;

public class UserDaoTest {

	@Test
	public void testAdd() throws Exception {
		User user =	new User();
		user.setUsername("bbb");
		user.setPassword("123");
		user.setEmail("[email protected]");
		user.setBirthday(new Date());
		user.setId("222");
		
		new UserDaoXmlImpl().add(user);
	}
	
	@Test
	public void testFind1(){
		boolean b =	new UserDaoXmlImpl().find("ccc");
		System.out.println(b);
	}
	
	@Test
	public void testFind2(){
		User user =	new User();
		user =	new UserDaoXmlImpl().find("ccc","vL4zZeasleosA0OiOVg03Q==");
		System.out.println(user);
	}
}

//开发service,对WEB层提供所有的业务服务
package he.junhua.service.impl;

import he.junhua.dao.UserDao;
import he.junhua.dao.impl.UserDaoXmlImpl;
import he.junhua.domain.User;
import he.junhua.exception.UserExistException;
import he.junhua.service.BusinessService;
import he.junhua.utils.WebUtils;

public class BusinessServiceImpl implements BusinessService {

	UserDao dao =	new UserDaoXmlImpl();	//实际中常使用工厂模式	 spring
	
	//对WEB层提供注册服务
	public void register(User user) throws UserExistException{
		if(dao.find(user.getUsername())){
			throw new UserExistException("用户已存在!!");
			//发现用户已存在,则给web层抛出一个异常,提醒web层处理该异常,并且给用户友好提示
		}else{
			user.setPassword(WebUtils.md5(user.getPassword()));
			dao.add(user);
		}
	}
	
	//对WEB层提供登录服务
	public User login(String username,String password){
		password =	WebUtils.md5(password);
		return dao.find(username, password);
	}
}

//同理,要抽取service接口
package he.junhua.service;

import he.junhua.domain.User;
import he.junhua.exception.UserExistException;

public interface BusinessService {

	//对WEB层提供注册服务
	void register(User user) throws UserExistException;

	//对WEB层提供登录服务
	User login(String username, String password);

}		

//对service层作一简单测试
package junit.test;

import he.junhua.domain.User;
import he.junhua.exception.UserExistException;
import he.junhua.service.BusinessService;
import he.junhua.service.impl.BusinessServiceImpl;

import java.util.Date;

import org.junit.Test;

public class ServiceTest {

	@Test
	public void testRigister(){
		
		User user =	new User();
		user.setUsername("aaa");
		user.setPassword("111");
		user.setEmail("[email protected]");
		user.setBirthday(new Date());
		user.setId("111");
		
		BusinessService bs =	new BusinessServiceImpl();
		try {
			bs.register(user);
			System.out.println("用户注册成功!");
		} catch (UserExistException e) {
			System.out.println("用户已经存在!");
		}
	}
	
	@Test
	public void testLogin(){
		BusinessService bs =	new BusinessServiceImpl();
		User user =	bs.login("bbb", "123");
		System.out.println(user);
	}
}


//开发web层
//开发注册模块
//RegisterUIServlet为用户提供注册界面
package he.junhua.web.UI;

import java.io.IOException;

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

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);
	}

}

//注册页面,由RegisterUIServlet跳转过来
<%@ 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 style="text-align: center;">
    <form action="${pageContext.request.contextPath }/servlet/RegisterServlet" method="post">
	    <div align="center" style="color:blue;background-color: fuchsia; " >
		    <table width="641" border="1" height="228">
		    	<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.password }">${formbean.errors.password }
		    		</td>
		    	</tr>
		    	
		    	<tr>
		    		<td>确认密码</td>
		    		<td>
		    			<input type="password" name="password2" value="${formbean.password2 }">${formbean.errors.password2 }
		    		</td>
		    	</tr>
		    	
		    	<tr>
		    		<td>邮箱</td>
		    		<td>
		    			<input type="text" name="email" value="${formbean.email }">${formbean.errors.email }
		    		</td>
		    	</tr>
		    	
		    	<tr>
		    		<td>生日</td>
		    		<td>
		    			<input type="text" name="birthday" value="${formbean.birthday }">${formbean.errors.birthday }
		    		</td>
		    	</tr>
		    	
		    	<tr>
		    		<td>
		    			<input type="reset" value="清空">
		    		</td>
		    		<td>
		    			<input type="submit" value="注册">
		    		</td>
		    	</tr>
		    </table>
	    </div>
    </form>
  </body>
</html>

//register.jsp提交请求,交给RegisterServlet处理
package he.junhua.web.controller;

import he.junhua.domain.User;
import he.junhua.exception.UserExistException;
import he.junhua.service.BusinessService;
import he.junhua.service.impl.BusinessServiceImpl;
import he.junhua.utils.WebUtils;
import he.junhua.web.formbean.RegisterFormBean;

import java.io.IOException;

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

public class RegisterServlet extends HttpServlet {

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

		//将表单数据封装到formbean中(功能模块化)
		RegisterFormBean formbean =	WebUtils.request2Bean(request, RegisterFormBean.class);
		
		//表单校检
		//如果不合法,则重新跳回注册界面并对提交失败的信息回显
		if(!formbean.isValidate()){
			formbean.setPassword(null);
			formbean.setPassword2(null);
			request.setAttribute("formbean", formbean);
			request.getRequestDispatcher("/WEB-INF/jsp/register.jsp").forward(request, response);
			return;
		}
		
		//如果校检通过,则调用service处理请求
		User user =	new User();
		WebUtils.copyBean(formbean, user);
		user.setId(WebUtils.generateID());
		
		BusinessService service =	new BusinessServiceImpl();
		try {
			service.register(user);	
			
			request.setAttribute("message", "用户注册成功!!");
			request.getRequestDispatcher("/message.jsp").forward(request, response);
		} catch (UserExistException e) {
			formbean.getErrors().put("username", "用户已存在!");
			request.setAttribute("formbean", formbean);
			request.getRequestDispatcher("/WEB-INF/jsp/register.jsp").forward(request, response);
		} catch (Exception e) {
			request.setAttribute("message", "注册失败!(服务器未知错误)");
			request.getRequestDispatcher("/message.jsp").forward(request, response);
		}
	}

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

}

//设计RegisterFormBean类,并提供合法性校检方法isValidate()
package he.junhua.web.formbean;

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

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

public class RegisterFormBean {
	
	private String username;
	private String password;
	private String password2;
	private String email;
	private String birthday;
	
	private Map<String, String> errors =	new HashMap();
	
	public Map<String, String> getErrors() {
		return errors;
	}
	public void setErrors(Map<String, String> errors) {
		this.errors = errors;
	}
	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;
	}
	
	

	/*
	private String username;  用户名不能为空,并且要是3-8的字符 abcdABcd
	private String password;  密码不能为空,并且要是3-8的数字
	private String password2; 两次密码要一致
	private String email;     可以为空,不为空要是一个合法的邮箱
	private String birthday;  可以为空,不为空时,要是一个合法的日期
	正则表达式可以通过在javaAPI中搜索pattern得到
	 * 
	 */
	
	public boolean isValidate(){
		boolean isOk =	true;
		
		if(this.username==null||this.username.trim().equals("")){
			isOk =	false;
			errors.put("username", "用户名不能为空!");
		}else{
			if(!this.username.matches("[a-zA-Z]{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){
			if(!this.password2.equals(this.password)){
				isOk =	false;
				errors.put("password2", "两次密码必须一致!");
			}
		}
		
		if(this.email!=null){
			if(!this.email.matches("\\w+@\\w+(\\.\\w+)+")){
				isOk =	false;
				errors.put("email", "不是一个合法的邮箱!");
			}
		}
		
		if(this.birthday!=null){
			try {
				//检验生日格式是否合法常用的方法
				DateLocaleConverter converter = new DateLocaleConverter();
				converter.convert(this.birthday);
			} catch (Exception e) {
				isOk =	false;
				errors.put("birthday", "不是合法的生日!");
			}
		}
		return isOk;
	}
}

//设计工具类WebUtil
package he.junhua.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Enumeration;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

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

import sun.misc.BASE64Encoder;

public class WebUtils {

	//对password加密
	public static String md5(String data){
		
		try {
			MessageDigest md =	MessageDigest.getInstance("md5");
			byte[] md5 =	md.digest(data.getBytes());
			
			return new BASE64Encoder().encode(md5);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}
	
	//将request携带来的参数写入formbean
	public static <T>T request2Bean(HttpServletRequest request,Class<T> clazz){
		try {
			T bean =	clazz.newInstance();
			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();
		}
	}
	
	//用于两个bean对象间的bean复制
	public static void copyBean(Object src,Object dest){
		
		ConvertUtils.register(new DateLocaleConverter(), Date.class);
		
		try {
			BeanUtils.copyProperties(dest, src);
		} catch (Exception e) {
			throw new RuntimeException();
		} 
	}
	
	//为user产生唯一的ID
	public static String generateID(){
		return UUID.randomUUID().toString();
	}
}


//同理,开发登录模块
package he.junhua.web.UI;

import java.io.IOException;

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

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);
	}

}

//登录页面
<%@ 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>
  	<div align="center" style="background-color: yellow;">
	    <form action="${pageContext.request.contextPath }/servlet/LoginServlet" method="post">
	    	用户名:<input name="username" type="text"/><br/>
	    	密码:	<input name="password" type="password"/><br/>
	    	<input value="登录" type="submit">
	    </form>
    </div>
  </body>
</html>

//交给LoginServlet处理
package he.junhua.web.controller;

import he.junhua.domain.User;
import he.junhua.service.BusinessService;
import he.junhua.service.impl.BusinessServiceImpl;

import java.io.IOException;

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

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");
		
		BusinessService service =	new BusinessServiceImpl();
		User user =	service.login(username, password);
		if(user==null){
			request.setAttribute("message", "用户名或密码错误!");
			request.getRequestDispatcher("/message.jsp").forward(request, response);
			return;
		}
		
		request.getSession().setAttribute("user", user);
		request.setAttribute("message", "欢迎您,"+user.getUsername()+"!<br/>3秒后将自动跳转到首页...<meta http-equiv='refresh' content='3;url=/day7/index.jsp'>");
		request.getRequestDispatcher("/message.jsp").forward(request, response);
		//response.sendRedirect("/message.jsp");
	}

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

}

//注销模块
package he.junhua.web.controller;

import java.io.IOException;

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

public class LogoutServlet extends HttpServlet {

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

		HttpSession session =	request.getSession(false);
		if(session!=null){
			//注销实际上就是将存在session域中的user清除掉
			session.removeAttribute("user");
		}
		
		request.setAttribute("message", "用户注销成功,5秒钟后将自动跳转到首页!<meta http-equiv='refresh' content='5;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);
	}
}

//最后对细节方面进行优化
技术分享技术分享技术分享技术分享技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。