当前位置: 代码迷 >> HTML/CSS >> java-servlet、DOM、html综合施用示例
  详细解决方案

java-servlet、DOM、html综合施用示例

热度:181   发布时间:2012-11-25 11:44:31.0
java-servlet、DOM、html综合运用示例
题目:

学员管理:
  学员录入,与Student类中字段对应,点击保存数据,提交给UserSaveServlet进行处理,保存成功后,显示成功信息,并且提供一个用户列表<a>的超链接,
点击“用户列表”超链接,显示出所有的用户数据信息,并且可以对数据进行删除操作。

说明:没有用到jsp,还没学到那儿……

学生信息录入页面:
<!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>Insert title here</title>
</head>
<body>
	<form action="/StuRecServlet" method="post">
		姓名:<input type="text" name="name"/><br/>
		性别:<input type="radio" name="sex" value="true"/>男
			<input type="radio" name="sex" value="false"/>女<br/>
		年龄:<input type="text" name="age" /><br/>
		班级:<input type="text" name="className" /><br/>
		<input type="submit" value="提交信息" />
	</form>
</body>
</html>


Servlet项目配置信息:
<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5">	
	<servlet>
		<servlet-name>StuRecServlet</servlet-name>
		<servlet-class>cn.itcast.servlet.student.StuRecServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>StuRecServlet</servlet-name>
		<url-pattern>/StuRecServlet</url-pattern>
	</servlet-mapping>
	
	<servlet>
		<servlet-name>StuManServlet</servlet-name>
		<servlet-class>cn.itcast.servlet.student.StuManServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>StuManServlet</servlet-name>
		<url-pattern>/StuManServlet</url-pattern>
	</servlet-mapping>
	
	<servlet>
		<servlet-name>StuDelServlet</servlet-name>
		<servlet-class>cn.itcast.servlet.student.StuDelServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>StuDelServlet</servlet-name>
		<url-pattern>/StuDelServlet</url-pattern>
	</servlet-mapping>
</web-app>




学生domain和DAO:
package cn.itcast.servlet.domain;

public class Student {
	private String id;
	private String name;
	private boolean sex;
	private String age;
	private String className;
	
	
	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 boolean isSex() {
		return sex;
	}
	public void setSex(boolean sex) {
		this.sex = sex;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", sex=" + sex
				+ ", age=" + age + ", className=" + className + "]";
	}
}

package cn.itcast.servlet.dao;

import java.util.List;

public interface IStudentDAO {
	List<Student> getAllStudents();
	void addStudent(Student stu);
	void deleteStudent(String id);
//	void updateStudent(Student stu);
}

package cn.itcast.servlet.dao;

import java.io.File;

public class StudentDAOImpl implements IStudentDAO {
	private final static String XMLFile = "D:\\Java\\WorkSpace\\MyWebApps\\webdoc\\student.xml";

	/**
	 * 获取Document对象.
	 * 
	 * @return
	 */
	public Document getDoc() {
		DocumentBuilder builder = null;
		Document doc = null;
		try {
			builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			doc = builder.parse(new File(XMLFile));
		} catch (Exception e) {
			e.printStackTrace();
			doc = builder.newDocument();
		}
		return doc;
	}

	/**
	 * 获取xml文件所有的Student对象,存放到List中.
	 */
	@Override
	public List<Student> getAllStudents() {
		/*
		 * 注意:这里只能使用局部变量doc来操作,不能直接使用getDoc()的方式,否则抛出异常:
		 * WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it。
		 * 在dom操作中全局变量赋值后再取值的时候会不确定
		 */
		Document doc = getDoc();
		List<Student> list = new ArrayList<Student>();
		// 得到所有的student元素.
		NodeList nodeList = doc.getElementsByTagName("student");

		// 迭代
		for (int i = 0; i < nodeList.getLength(); i++) {
			Student stu = new Student();

			Element stuEl = (Element) nodeList.item(i);
			stu.setId(stuEl.getAttribute("id"));
			stu.setAge(stuEl.getElementsByTagName("age").item(0)
					.getTextContent());
			stu.setClassName(stuEl.getElementsByTagName("className").item(0)
					.getTextContent());
			stu.setName(stuEl.getElementsByTagName("name").item(0)
					.getTextContent());
			stu.setSex(Boolean.parseBoolean(stuEl.getElementsByTagName("sex")
					.item(0).getTextContent()));

			list.add(stu);
		}
		return list;
	}

	/**
	 * 向xml中增加一个Student.
	 */
	@Override
	public void addStudent(Student stu) {
		Document doc = getDoc();
		Element stuEl = doc.createElement("student");
		stuEl.setAttribute("id", stu.getId());

		Element nameEl = doc.createElement("name");
		nameEl.setTextContent(stu.getName());
		stuEl.appendChild(nameEl);

		Element sexEl = doc.createElement("sex");
		sexEl.setTextContent(stu.isSex() + "");
		stuEl.appendChild(sexEl);

		Element ageEl = doc.createElement("age");
		ageEl.setTextContent(stu.getAge());
		stuEl.appendChild(ageEl);

		Element classEl = doc.createElement("className");
		classEl.setTextContent(stu.getClassName());
		stuEl.appendChild(classEl);

		// 通过根节点增加子节点(student元素)
		doc.getDocumentElement().appendChild(stuEl);

		// 将数据从内存保存到文件中
		try {
			Transformer tf = TransformerFactory.newInstance().newTransformer();
			Source source = new DOMSource(doc);
			Result result = new StreamResult(new File(XMLFile));
			tf.transform(source, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 从Xml文件中删除一个节点.
	 */
	@Override
	public void deleteStudent(String id) {
		Document doc = getDoc();
		NodeList nodeList = doc.getElementsByTagName("student");
		for (int i = 0; i < nodeList.getLength(); i++) {
			Element el = (Element) nodeList.item(i);
			if (id.equals(el.getAttribute("id"))) {
				el.getParentNode().removeChild(el);
				break;
			}
		}

		// 将数据从内存保存到文件中
		try {
			Transformer tf = TransformerFactory.newInstance().newTransformer();
			Source source = new DOMSource(doc);
			Result result = new StreamResult(new File(XMLFile));
			tf.transform(source, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


学生录入Servlet:
package cn.itcast.servlet.student;

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

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

import cn.itcast.servlet.dao.StudentDAOImpl;
import cn.itcast.servlet.domain.Student;

//学生信息录入StuRecServlet
public class StuRecServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		//设置编码,否则录入后读取信息会造成乱码.
		req.setCharacterEncoding("UTF-8");
		
		String id = UUID.randomUUID().toString();
		String name = req.getParameter("name");
		boolean sex = Boolean.parseBoolean(req.getParameter("sex"));
		String age = req.getParameter("age");
		String className = req.getParameter("className");
		
		StudentDAOImpl stuDao = new StudentDAOImpl();
		Student stu = new Student();
		stu.setName(name);
		stu.setSex(sex);
		stu.setAge(age);
		stu.setClassName(className);
		stu.setId(id);
		
		stuDao.addStudent(stu);
		
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		out.println("<h1>录入成功!</h1>");
		//关联学生管理StuManServlet.
		out.println("<a href='/StuManServlet'>查看学生信息列表</a>");
		out.flush();
	}

}


学生管理Servlet:
package cn.itcast.servlet.student;

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

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

import cn.itcast.servlet.dao.StudentDAOImpl;
import cn.itcast.servlet.domain.Student;

//学生信息管理StuManServlet
public class StuManServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		req.setCharacterEncoding("UTF-8");
		StudentDAOImpl stuDao = new StudentDAOImpl();
		List<Student> stuList = stuDao.getAllStudents();

		resp.setContentType("text/html;charset=utf-8");

		PrintWriter out = resp.getWriter();
		// 写表头信息,设置边框和宽度
		out.println("<form action='/StuManServlet' method='POST'>");
		out.println("<table border=1 bordercolor='blue' width='70%'><tr><th>ID</th><th>姓名</th><th>性别</th><th>年龄"
				+ "</th><th>班级</th><th>操作</th></tr>");

		//迭代处理
		for (Student stu : stuList) {
			String id = stu.getId();
			String name = stu.getName();
			String sex = stu.isSex() + "";
			String age = stu.getAge();
			String className = stu.getClassName();

			out.println("<tr>");
			out.println("<td>" + id + "</td>");
			out.println("<td align='center'>" + name + "</td>");
			out.println("<td align='center'>" + sex + "</td>");
			out.println("<td align='center'>" + age + "</td>");
			out.println("<td align='center'>" + className + "</td>");
			// 关联StuDelSetvlet删除的时候需要传递给StuDelServlet当前的ID,根据ID删除.
			out.println("<td align='center'><a href='/StuDelServlet?id=" + id
					+ "'>删除</a></td>");
			out.println("</tr>");
			out.flush();
		}
		out.println("</table></form>");
		out.flush();
	}
}


学生删除Servlet:
package cn.itcast.servlet.student;

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 cn.itcast.servlet.dao.StudentDAOImpl;

//学生信息删除StuDelServlet
public class StuDelServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		req.setCharacterEncoding("UTF-8");
		StudentDAOImpl stuDao = new StudentDAOImpl();
		
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		
		String id = req.getParameter("id");
		if(id!=null && !"".equals(id)){
			stuDao.deleteStudent(id);
			out.println("<h1>删除成功!</h1>");
			//关联学生管理servlet
			out.println("<br/><a href='/StuManServlet'>查看学生信息列表</a>");
			out.flush();
		}
	}
	
}
  相关解决方案