不用 jdbc 用xml来模拟数据,创建数据,保持数据。
用典型的mvc模式来进行开发
首先来进行创建目录结构
- bean 包用来储存实体类
- dao 包用来创建数据库 接口定义
- daoxmlimpl 包用来进行实现数据库定义的接口
- utils 工具类
- juint.test 包用于测试功能
- service 包用于放业务处理类 是数据库和界面数据的桥梁
- web 包 用来存放有关网页的操作
- web包 下面又分为 controller(处理网页有关的逻辑)
- ui 包放用户直接访问的 servlet
- frombean 包下面放根据浏览器生成的 bean文件
具体看下面的图
QQ截图20170618232040.png后面继续添加
1、创建一个xml文件 定义为 user.xml 后面的用户的添加,查询等都是围绕此进行的。
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user id="1" username="基本密码" password="111" email="jibenmima@163.com" birthday="1992-01-17"></user>
</users>
2、根据创建的xml进行创建bean实体,用于对xml数据的封装。
public class UserBean {
private String id;
private String username;
private String password;
private String email;
private Date birthday;
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;
}
}
3、根据需求。因为是个登录的demo,分析。
- 1.进行添加用户 addUser(UserBean user);
- 2.根据用户名字查询有没有此人UserBean findUser(String name);
- 3.根据用户的名字、密码来进行登录 UserBean findUser(String name,String passWord);
所以上面的是 Dao 接口中的定义了
public interface UserDao {
/**
* 添加用户
* @param user
*/
void addUser(UserBean user);
/**
* 根据 姓名 密码来查找
* @param name
* @param passWord
* @return
*/
UserBean findUser(String name,String passWord);
/**
* 根据用户来找找 是否有该用户
* @param name
* @return
*/
UserBean findUser(String name);
}
4、紧接着是Dao的实现了 里面用到了dom4jjar包,专门用来进行xml的操作
public class UserDaoXmlImpl implements UserDao{
@Override
public void addUser(UserBean user) {
//其实就是向xml中插入数据 所以会用到 dem4j
try {
Document document = XmlUtils.getDocument();
Element root=document.getRootElement();
Element user_node=root.addElement("user");
user_node.setAttributeValue("id", user.getId());
user_node.setAttributeValue("username", user.getUsername());
user_node.setAttributeValue("password", user.getPassword());
user_node.setAttributeValue("email", user.getEmail());
user_node.setAttributeValue("birthday", user.getBirthday().toLocaleString());
try {
XmlUtils.write2Xml(document);
} catch (IOException e) {
throw new RuntimeException(e);
}
} catch (DocumentException e) {
throw new RuntimeException(e);
}
}
@Override
public UserBean findUser(String name, String passWord) {
try {
Document document=XmlUtils.getDocument();
Element el=(Element) document.selectSingleNode("//user[@username='"+name+"' and @password='"+passWord+"']");
if (el!=null) {
UserBean user=new UserBean();
user.setUsername(el.attributeValue("username"));
user.setId(el.attributeValue("id"));
user.setEmail(el.attributeValue("email"));
user.setPassword(el.attributeValue("password"));
String birthday= el.attributeValue("birthday");
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
Date date = simpleDateFormat.parse(birthday);
user.setBirthday(date);
return user;
} else{
return null;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public UserBean findUser(String name) {
try {
Document document=XmlUtils.getDocument();
// Element el=(Element) document.selectSingleNode("//user[@username='"+name+"']");
Element el = (Element) document.selectSingleNode("//user[@username='"+name+"']");
if (el!=null) {
UserBean user=new UserBean();
user.setUsername(el.attributeValue("username"));
user.setId(el.attributeValue("id"));
user.setEmail(el.attributeValue("email"));
user.setPassword(el.attributeValue("password"));
String birthday= el.attributeValue("birthday");
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
Date date = simpleDateFormat.parse(birthday);
user.setBirthday(date);
return user;
} else{
return null;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
上面设计到xml的 存,查 用到了 xmlUtils
/**
* 操作 xml 的工具类 用到第三方 dem4j
* @author songjiabin
*
*/
public class XmlUtils {
private static final String filename="user.xml";
/**
* 得到 Document
* @return
* @throws DocumentException
*/
public static Document getDocument() throws DocumentException{
URL url= XmlUtils.class.getClassLoader().getResource(filename);
String xmlPath=url.getPath();
SAXReader reader=new SAXReader();
Document document =reader.read(new File(xmlPath));
return document;
}
/**
* 將xml文件写道 文件中去
* @param document
* @throws IOException
*/
public static void write2Xml(Document document) throws IOException{
URL url= XmlUtils.class.getClassLoader().getResource(filename);
String xmlPath=url.getPath();
OutputFormat format=OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(new FileOutputStream(xmlPath), format );
writer.write( document );
writer.close();
}
}
写完了 一个小模块 需要测试 用到了 junit
public class UserDaoTest2 {
@Test
public void userDaoAddTest(){
UserBean userBean=new UserBean();
userBean.setId("222");
userBean.setBirthday(new Date());
userBean.setEmail("基本信息@163.com");
userBean.setPassword("222");
userBean.setUsername("基本信息");
UserDaoXmlImpl userDaoXmlImpl =new UserDaoXmlImpl();
userDaoXmlImpl.addUser(userBean);
}
@Test
public void findByUserName(){
UserDaoXmlImpl userDaoXmlImpl =new UserDaoXmlImpl();
UserBean user=userDaoXmlImpl.findUser("基本信息");
if (user!=null) {
String name=user.getUsername();
System.out.println(name);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String birthday=sdf.format(user.getBirthday());
System.out.println(birthday);
}
}
@Test
public void findByUserNameAndPassWord(){
UserDaoXmlImpl userDaoXmlImpl =new UserDaoXmlImpl();
UserBean user=userDaoXmlImpl.findUser("基本信息","222");
if (user!=null) {
String name=user.getUsername();
System.out.println(name);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String birthday=sdf.format(user.getBirthday());
System.out.println(birthday);
}
}
}
插入后可以在编译后的class文件中进行查询,看看是否有没有插入成功。
查询可以直接打印到控制台
下面主要是进行对web层的开发了 和用户打交道的层 比较恶心了
首先写好 service层 用来和web层进行数据交互的层
/**
* 业务处理
* @author 基本密码
*
*/
public interface BusinessService {
/**
* 传来 账号 密码 进行登陆的操作
* @param username
* @param password
* @return
*/
UserBean loginUser(String username,String password);
/**
* 传来用户 进行注册的操作
* @param userBean
*/
void registerUser(UserBean userBean) throws UserExistException;
}
这个层定义了 业务的操作
public class BusinessServiceImpl implements BusinessService {
private UserDaoXmlImpl userDaoXmlImpl;
public BusinessServiceImpl() {
userDaoXmlImpl=new UserDaoXmlImpl();
}
@Override
public UserBean loginUser(String username, String password) {
//查看本地 xml是否有 此用戶 有->返回user 沒有->返回 null
UserBean bean= userDaoXmlImpl.findUser(username, password);
return bean;
}
@Override
public void registerUser(UserBean userBean) throws UserExistException {
if (userDaoXmlImpl.findUser(userBean.getUsername())!=null) {
//表示xml中已經有此名字了 不能注册了
// 这里我们抛异常一个
throw new UserExistException("注册的用户名已存在!!!");
}else
userDaoXmlImpl.addUser(userBean);
}
}
用于实现上面定义的接口 方便 view层进行调用
上面用到一个UserExistException异常 ,就是用来处理 当存在当前用户了告诉上面调用的一层
public class UserExistException extends Exception{
//异常的处理类
public UserExistException() {
super();
// TODO Auto-generated constructor stub
}
public UserExistException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public UserExistException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public UserExistException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
}
先写登录的界面 。
- 1、在web/UI 下新建 LoginUIServlet ,用于让用户来进行访问
//为用户输出登陆界面
public class LoginUIServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//要隐藏 jsp文件 让用户直接访问这个 servlet
// 进行跳转到 jsp文件中去
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
- 2、在WEB-INF下面建立jsp文件 并新建login.jsp 用于显示界面,并通过from表单 提交到 servlet处理
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>用户登陆</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/LoginServlet" method="post">
用戶名:<input type="text" name="username"><br/>
密碼:<input type="password" name="password"><br/>
<input type="submit" value="提交">
- 3、将用户登录的先写提交到web/controller./LoginServlet 中
/**
* login.jsp 传值过来给次Servlet处理
* @author 基本密码
*
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//这里的操作时将登陆的信息进行判断,保存
request.setCharacterEncoding("UTF-8");
response.setHeader("content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
String username=request.getParameter("username");
String password=request.getParameter("password");
BusinessServiceImpl businessServiceImpl=new BusinessServiceImpl();
UserBean userBean=businessServiceImpl.loginUser(username, password);
if (userBean==null) {
//如果是null 表示xml中没有赐个用户
//将message传入到 request域中
request.setAttribute("message", "对不起,用户名或密码有误!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}else{
//表示登陆成功
request.getSession().setAttribute("user", userBean);//将数据保存到 session中 表示已经登陆过了
//跳转到 message中 并告诉这个界面上 过5秒进行刷信
request.setAttribute("message", "恭喜:"+userBean.getUsername()+",登陆成功!本页将在5秒后跳到首页!!<meta http-equiv='refresh' content='5;url=/Login/index.jsp'");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
当登录成功后调到message.jsp中
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>消息处理哦</title>
</head>
<body>
${message }
</body>
</html>
到此 用户的登录完成。
下面是用户的注册
- 1、和登录同样的操作 新建 RegisterUIServlet
/**
* 注册界面 用来提供给用户打开 直接访问即可
*/
@WebServlet("/RegisterUIServlet")
public class RegisterUIServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//重定向到 jsp
request.getRequestDispatcher("WEB-INF/jsp/register.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
- 2、新建用于显示注册界面的 register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册界面</title>
</head>
<body style="text-align: center;">
<form action="${pageContext.request.contextPath}/RegisterServlet">
<table width="60%" border="1">
<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="重置密码">
<input type="submit" value="注册">
</td>
<td></td>
</tr>
</table>
</form>
</body>
</html>
- 3、新建用于处理注册界面信息的RegisterServlet
/**
* register.jsp 表单提交到这里的 对页面过来数据的处理
*/
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RegisterFormBean bean=WebUtils.request2Bean(request, RegisterFormBean.class);
//表单校验
if(bean.validate()==false){
//如果注册的时候哪里出现了不合法的注册信息,将信息交给 register.jsp进行显示
request.setAttribute("formbean", bean);
request.getRequestDispatcher("/WEB-INF/jsp/register.jsp").forward(request,response);
return;
}
//把表单的数据填充到javabean中 从而来知道 这个次个注册数据 是否能成功
UserBean user = new UserBean();
try {
//注册字符串到日期的转换器
ConvertUtils.register(new DateLocaleConverter(), Date.class);
BeanUtils.copyProperties(user, bean);//copy 数据到 user中去
user.setId(WebUtils.makeId());
BusinessService service = new BusinessServiceImpl();
service.registerUser(user);
request.setAttribute("message", "注册成功!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}catch (UserExistException e) {
bean.getErrors().put("username", "注册用户已存在!!");
request.setAttribute("formbean", bean);
request.getRequestDispatcher("/WEB-INF/jsp/register.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace(); //在后台记录异常
request.setAttribute("message", "对不起,注册失败!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
上面用到了处理注册界面数据的WebUtils
/**
* 工具类 用来进行 对注册界面数据的处理
*
*/
public class WebUtils {
/**
* 传入 请求参数 将请求的参数 封装到实体中
* @param request
* @param classz
* @return
*/
public static <T> T request2Bean(HttpServletRequest request,Class<T> classz){
try {
T bean=classz.newInstance();
Enumeration<String> e = request.getParameterNames();
while(e.hasMoreElements()){
String name=(String)e.nextElement();
String value=request.getParameter(name);
//beanUtils 框架就是将 一个实体的bean
BeanUtils.setProperty(bean, name, value);
}
return bean;
} catch (Exception e) {
throw new RuntimeException();
}
}
/**
* 生成用户注册的ID
* @return
*/
public static String makeId(){
//UUID 128 36位字符
return UUID.randomUUID().toString();
}
}
OK 注册完成。
下面是主界面 ,里面将 登录、注册、退出的链接都好了 次index.jsp直接暴露出来就可以,因为是让用户调用的
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!-- 引用时 standar.jar/META-INF c.tld中的 <uri>http://java.sun.com/jsp/jstl/core</uri> -->
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>主界面</title>
<script type="text/javascript">
function doLogout(){
window.location.href="${pageContext.request.contextPath}/LogoutServlet";
}
</script>
</head>
<body>
<h1> XX网站</h1>
<br/><br/>
<c:if test="${user==null}">
<a href="${pageContext.request.contextPath }/RegisterUIServlet" target="_blank">注册</a>
<a href="${pageContext.request.contextPath }/LoginUIServlet">登陆</a>
</c:if>
<c:if test="${user!=null}">
欢迎您:${user.username }
<input type="button" value="退出登陆" onclick="doLogout()">
</c:if>
</body>
</html>
当点击注销的时候,就是讲 保留的session杀掉
/**
* 退出登录的操作
*/
@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//将 session 去掉 表示现在没有登录的操作了
request.getSession().removeAttribute("user");
request.setAttribute("message", "注销成功!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
完事 ~~~
网友评论