javaee之jsp和Servlet的练习

时间:2021-11-03 20:08:38

一、现在先使用xml来充当数据库,显示了用户的crud功能:

实体类:

public class User {

private String id;
private String name;
private String password;
private String gender;
private String birth;
private String address;
private String email;



public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public User(String id, String name, String password, String gender,
String birth, String address,String email) {
super();
this.id = id;
this.name = name;
this.password = password;
this.gender = gender;
this.birth = birth;
this.address = address;
this.email = email;
}
public User() {
super();
}

}

逻辑层:

import java.util.List;

import xml_crud.entiry.User;

public interface UserDao {

/*
* 对用户的操作
*/
//查找用户
public List<User> findAll();

public User findById(String id);

public void editUser(User user);

public void delUser(String id);

public void addUser(User user);
}
import java.util.ArrayList;import java.util.List;import org.dom4j.Document;import org.dom4j.Element;import xml_crud.entiry.User;import xml_crud.util.XMLUtil;public class UserDaoImpl implements UserDao {public List<User> findAll() {try {Document doc = XMLUtil.read();Element root = doc.getRootElement();
<span style="white-space:pre"></span>//查找到所有的元素进行遍历List<User> users = new ArrayList<User>();List<Element> elements = root.elements();for(Element e : elements){String id = e.attributeValue("id");String name = e.elementText("name");String password = e.elementText("password");String gender = e.elementText("gender");String birth = e.elementText("birth");String email = e.elementText("email");String address = e.elementText("address");User user = new User(id, name, password, gender, birth, address,email);users.add(user);}return users;} catch (Exception e) {e.printStackTrace();throw new RuntimeException(",网络异常,请稍后再操作.");}}public User findById(String id) {try{Document doc = XMLUtil.read();Element element = (Element) doc.getRootElement().selectSingleNode("//user[@id='"+id+"']");User user = null;if(element != null){user = new User();String name = element.elementText("name");String password = element.elementText("password");String gender = element.elementText("gender");String birth = element.elementText("birth");String email = element.elementText("email");String address = element.elementText("address");user.setId(id);user.setAddress(address);user.setBirth(birth);user.setEmail(email);user.setGender(gender);user.setName(name);user.setPassword(password);}return user;}catch(Exception e){e.printStackTrace();throw new RuntimeException(",网络异常,请稍后再操作.");}}public void editUser(User user) {try{Document doc = XMLUtil.read();Element element = (Element) doc.getRootElement().selectSingleNode("//user[@id='"+user.getId()+"']");if(element != null){element.element("name").setText(user.getName());element.element("password").setText(user.getPassword());element.element("gender").setText(user.getGender());element.element("address").setText(user.getAddress());element.element("email").setText(user.getEmail());element.element("birth").setText(user.getBirth());}XMLUtil.writerxml(doc);}catch(Exception e){e.printStackTrace();throw new RuntimeException(",网络异常,请稍后再操作.");}}public void delUser(String id) {try{Document doc = XMLUtil.read();Element element = (Element) doc.getRootElement().selectSingleNode("//user[@id='"+id+"']");if(element != null){element.getParent().remove(element);}XMLUtil.writerxml(doc);}catch(Exception e){e.printStackTrace();throw new RuntimeException(",网络异常,请稍后再操作.");}}public void addUser(User user) {try{Document doc = XMLUtil.read();Element root = doc.getRootElement();Element e = root.addElement("user");e.addAttribute("id", user.getId());e.addElement("name").setText(user.getName());e.addElement("password").setText(user.getPassword());e.addElement("gender").setText(user.getGender());e.addElement("email").setText(user.getEmail());e.addElement("address").setText(user.getAddress());e.addElement("birth").setText(user.getBirth());XMLUtil.writerxml(doc);}catch(Exception e){e.printStackTrace();throw new RuntimeException(",网络异常,请稍后再操作.");}}}

视图层:

import java.io.IOException;

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

import xml_crud.dao.UserDao;
import xml_crud.dao.UserDaoImpl;
import xml_crud.entiry.User;

public class AddUserServlet extends HttpServlet {


private UserDao dao = new UserDaoImpl();

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

request.setCharacterEncoding("utf-8");
String id = request.getParameter("id");
String name = request.getParameter("name");
String password = request.getParameter("password");
String birth = request.getParameter("birth");
String address = request.getParameter("address");
String email = request.getParameter("email");
String gender = request.getParameter("gender");

User user = new User(id, name, password, gender, birth, address, email);

dao.addUser(user);

response.setContentType("text/html;charset=utf-8");
response.getWriter().write("添加成功,3秒后跳转");
response.setHeader("refresh", "3;url="+request.getContextPath()+"/QueryUserServlet");

}

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

doGet(request, response);
}

}

import java.io.IOException;

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

import xml_crud.dao.UserDao;
import xml_crud.dao.UserDaoImpl;

public class DelUserServlet extends HttpServlet {


private UserDao dao = new UserDaoImpl();

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

String id = request.getParameter("id");

dao.delUser(id);

response.setContentType("text/html;charset=utf-8");
response.getWriter().write("删除成功,3秒后跳转");
response.setHeader("refresh", "3;url="+request.getContextPath()+"/QueryUserServlet");

}


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

doGet(request, response);
}

}

import java.io.IOException;

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

import xml_crud.dao.UserDao;
import xml_crud.dao.UserDaoImpl;
import xml_crud.entiry.User;

public class EditServlet extends HttpServlet {



private UserDao dao = new UserDaoImpl();

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

request.setCharacterEncoding("utf-8");
String id = request.getParameter("id");
String name = request.getParameter("name");
String password = request.getParameter("password");
String birth = request.getParameter("birth");
String address = request.getParameter("address");
String email = request.getParameter("email");
String gender = request.getParameter("gender");

User us = dao.findById(id);
us.setAddress(address);
us.setBirth(birth);
us.setEmail(email);
us.setGender(gender);
us.setName(name);
us.setPassword(password);

dao.editUser(us);


response.setContentType("text/html;charset=utf-8");
response.getWriter().write("修改成功,3秒后跳转");
response.setHeader("refresh", "3;url="+request.getContextPath()+"/QueryUserServlet");

}


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

doGet(request, response);
}

}

import java.io.IOException;
import java.util.List;

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

import xml_crud.dao.UserDao;
import xml_crud.dao.UserDaoImpl;
import xml_crud.entiry.User;

public class QueryUserServlet extends HttpServlet {


private UserDao dao = new UserDaoImpl();

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

List<User> list = dao.findAll();

request.setAttribute("userlist", list);

request.getRequestDispatcher("/queryUser.jsp").forward(request, response);



}


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

doGet(request, response);
}

}

import java.io.IOException;

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

import xml_crud.dao.UserDao;
import xml_crud.dao.UserDaoImpl;
import xml_crud.entiry.User;

public class EditUserServlet extends HttpServlet {


private UserDao dao = new UserDaoImpl();

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

String id = request.getParameter("id");
User user = dao.findById(id);
request.setAttribute("user", user);

request.getRequestDispatcher("/editUser.jsp").forward(request, response);

}


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

doGet(request, response);
}

}

还有其他的是工具类和xml文件

import java.io.File;
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 XMLUtil {

/**
* 对“数据库”xml的读取操作
* @return
* @throws Exception
*/
public static Document read() throws Exception{
SAXReader reader = new SAXReader();
Document doc = reader.read("d:/java/webapps/Myitcast_day09/WEB-INF/classes/user.xml");
return doc;
}


/**
* 对“数据库”xml的写入操作
* @param doc
* @throws Exception
*/
public static void writerxml(Document doc) throws Exception{
XMLWriter writer = new XMLWriter(
new FileOutputStream(new File("d:/java/webapps/Myitcast_day09/WEB-INF/classes/user.xml")),
OutputFormat.createPrettyPrint()
);
writer.write(doc);
writer.close();
}
}

<?xml version="1.0" encoding="UTF-8"?>

<userList>
<user id="1">
<name>eric</name>
<password>1234</password>
<gender>男</gender>
<birth>1980-09-08</birth>
<email>eric@qq.com</email>
<address>广州天河</address>
</user>
<user id="2">
<name>eric</name>
<password>1234</password>
<gender>女</gender>
<birth>1987-05-04</birth>
<email>eric@qq.com</email>
<address>广州黄埔</address>
</user>
<user id="3">
<name>狗娃</name>
<password>1234</password>
<gender>男</gender>
<birth>1987-05-06</birth>
<email>gouwa@qq.com</email>
<address>广州越秀</address>
</user>
<user id="4">
<name>铁蛋</name>
<password>1234</password>
<gender>女</gender>
<birth>1987-01-01</birth>
<email>tiedan@qq.com</email>
<address>广州海珠</address>
</user>
</userList>

通过上面的简单逻辑就能实现用户的crud功能,

还有就是显示的jsp和修改、添加的jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'adduser.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<form action="<%=request.getContextPath() %>/AddUserServlet" method="post">
<table>
<tr>
<td>编号</td>
<td><input type="text" name="id" /></td>
</tr>
<tr>
<td>密码</td>
<td><input type="text" name="password" /></td>
</tr>
<tr>
<td>姓名</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name="gender" value="男" />男  
<input type="radio" name="gender" value="女" />女</td>
</tr>
<tr>
<td>生日</td>
<td><input type="text" name="birth" /></td>
</tr>
<tr>
<td>邮箱</td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td>地址</td>
<td>
<select name="address">
<option value="广州天河">广州天河</option>
<option value="广州越秀">广州越秀</option>
<option value="广州黄埔">广州黄埔</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit" value="添加" /></td>
<td><input type="reset" value="重写" /></td>
</tr>
</table>
</form>
<body>

</body>
</html>

<%@ 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="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>
<form action="<%=request.getContextPath() %>/EditServlet" method="post">
<%--使用隐藏域 --%>
<input type="hidden" name="id" value="${user.id}"/>
<table border="1" width="300px">
<tr>
<td>姓名</td>
<td><input type="text" name="name" value="${user.name}"/></td>
</tr>
<tr>
<td>密码</td>
<td><input type="text" name="password" value="${user.password}"/></td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name="gender" value="男" ${user.gender=="男"?"checked='checked'":""} />男
<input type="radio" name="gender" value="女" ${user.gender=="女"?"checked='checked'":""} />女
</td>
</tr>
<tr>
<td>address</td>
<td>
<select name="address">
<option value="广州天河" ${user.address=="广州天河"?"selected='selected'":""} >广州天河</option>
<option value="广州黄埔" ${user.address=="广州黄埔"?"selected='selected'":""}>广州黄埔</option>
<option value="广州海珠" ${user.address=="广州海珠"?"selected='selected'":""}>广州海珠</option>
<option value="广州越秀" ${user.address=="广州越秀"?"selected='selected'":""}>广州越秀</option>
</select>
</td>
</tr>
<tr>
<td>生日</td>
<td><input type="text" name="birth" value="${user.birth }"/></td>
</tr>
<tr>
<td>邮箱</td>
<td><input type="text" name="email" value="${user.email }"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="修改"/>
<input type="button" value="返回" onclick="toBack()"/>
</td>
</tr>
</table>
</form>
<script type="text/javascript">
//返回
function toBack(){
window.history.back();
}
</script>
<body>

</body>
</html>

<%@page import="xml_crud.entiry.User"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>用户的信息</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
<h3 align="center">用户所有信息</h3>
<table border="1" width="700px" align="center">
<tr>
<th>编号</th>
<th>姓名</th>
<th>密码</th>
<th>性别</th>
<th>邮箱</th>
<th>生日</th>
<th>地址</th>
<th>操作</th>
</tr>


<c:forEach items="${requestScope.userlist}" var="u">
<tr>
<td>${u.id }</td>
<td>${u.name }</td>
<td>${u.password }</td>
<td>${u.gender }</td>
<td>${u.email }</td>
<td>${u.birth }</td>
<td>${u.address }</td>
<td><a href="<%=request.getContextPath() %>/EditUserServlet?id=${u.id}">修改</a>  <a href="<%=request.getContextPath() %>/DelUserServlet?id=${u.id}">删除</a></td>
</tr>
</c:forEach>


<tr>
<td colspan="8" align="center">
<a href="<%=request.getContextPath() %>/adduser.jsp" style="text-decoration: none;"><input type="button" value="添加" /></a>
</td>
</tr>
</table>
</body>
</html>