javaee之jsp和Servlet的练习

一、现在先使用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>[email protected]</email>
    <address>广州天河</address>
  </user>
  <user id="2">
    <name>eric</name>
    <password>1234</password>
    <gender>女</gender>
    <birth>1987-05-04</birth>
    <email>[email protected]</email>
    <address>广州黄埔</address>
  </user>
  <user id="3">
    <name>狗娃</name>
    <password>1234</password>
    <gender>男</gender>
    <birth>1987-05-06</birth>
    <email>[email protected]</email>
    <address>广州越秀</address>
  </user>
  <user id="4">
    <name>铁蛋</name>
    <password>1234</password>
    <gender>女</gender>
    <birth>1987-01-01</birth>
    <email>[email protected]</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>
时间: 2024-10-12 06:00:32

javaee之jsp和Servlet的练习的相关文章

javaEE jsp与servlet之间通信

0.下载安装Opencv,当前版本为249. 1.下载Python,当前OPencv版本为249,不过其支持的最新版本的Python为2.7,所以可以下载276版本. 2.下载numpy,开始我使用了1.6,没有通过,错误如图.下载了最新的1.8.1版本. 3.将Opencv安装目录下opencv\build\python\2.7\x86中的cv2.pyd复制到python安装目录Lib\site-packages下. 4.找到opencv源文件内的draw.py运行. javaEE jsp与s

JSP和servlet之间的传值(总结的很全面)

转自:http://blog.csdn.net/ssy_shandong/article/details/9328985 1.从一个jsp页面跳转到另一个jsp页面时的参数传递 (1)使用request对象获取客户端提交的信息 login.jsp页面代码如下: [java] view plaincopy <%@ page language="java" import="java.util.*" pageEncoding="GB2312"%&

jsp和servlet 简单登录界面(不连接数据库)

1.首先说明一点,虽然很简单但是对于初学者 这个jsp和servlet的链接 我捣鼓了半天才算弄明白 jsp将请求提交到一个url,然后servlet获取也从这个url中获取请求的数据,两者的链接就在那个url jsp中的代码 文件名:login.jsp <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <

JSP JavaBean Servlet 的介绍(转)

在JSP中调用JAVA类和使用JavaBean有什么区别? http://blog.sina.com.cn/s/blog_71c1942e01013gsb.html 可以像使用一般的类一样使用JavaBean,Bean只是一种特殊的类.特殊在可以通过<jsp:useBean   />调用JavaBean而其他类,可以和一般java中一样使用.  Bean的参数中还可以指定范围, <jsp:useBean  scope="application"   />该Bea

Jsp与servlet之间页面跳转及参数传递实例(转)

原网址:http://blog.csdn.net/ssy_shandong/article/details/9328985 11. jsp与servlet之间页面跳转及参数传递实例 分类: Java Web2013-07-17 16:24 16461人阅读 评论(12) 收藏 举报 jsp servlet传递参数 目录(?)[-] 1从一个jsp页面跳转到另一个jsp页面时的参数传递 2jsp页面传递参数给servlet 3从servlet到jsp页面中传递参数 4从一个servlet到另一个s

JSP和Servlet[1]

Servlet与JSP简介 Servlet是用Java编写的服务器端程序.其主要功能在于交互式地浏览和修改数据,生成动态Web内容.狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,一般情况下,人们将Servlet理解为后者. JSP经编译后就变成了Servlet.(JSP的本质就是Servlet,JVM只能识别java的类,不能识别JSP的代码,Web容器将JSP的代码编译成JVM能够识别的java类)2.JSP更擅长表现于页面显

jsp和servlet的区别

servlet是服务器端的程序,动态生成html页面发到客户端,但是这样 程序里有许多out.println(),java和html语言混在一起很乱.所以 后来推出了jsp.其实jsp就是servlet,每一个jsp在第一次运行时被 转换成servlet文件,再编译成.class来运行. 有了jsp,因此在MVC模式中servlet不再负责生成html页面,转而担任 控制程序逻辑的作用,控制jsp和javabean之间的流转. Servlet与Jsp的区别 * Servlet中没有内置对象,原来

转 高性能、高弹性JSP和Servlet性能优化

高性能.高弹性JSP和Servlet性能优化 2009-01-05 10:00 执木 网络转载 字号:T | T 本文讲述了开发高性能.高弹性的JSP页面和Servlet的性能优化技术.其意思是建立尽可能快的并能适应数量增长的用户及其请求.在本文中,你将学习已经实践和得到证实的性能调整技术,它将大大地提高你的Servlet和Jsp页面的性能,进而提升J2EE的性能. AD:WOT2015 互联网运维与开发者大会 热销抢票 你的J2EE应用是不是运行的很慢?它们能不能承受住不断上升的访问量?本文讲

jsp与servlet的区别

Servlet与Jsp的区别 * Servlet中没有内置对象,原来Jsp中的内置对象都是必须通过HttpServletRequest对象,或由 HttpServletResponse对象生成. * 对于静态的HTML标签,Servlet都必须使用页面输出流诼行输出. 总之,Jsp是Servlet的一种简化,使用Jsp只需要完成程序员需要输出到客户端的内容,至于Jsp中的 Java脚本如何镶嵌到一个类中,由Jsp容器完成.而Servlet则是个完整的Java类,这个类的Service 方法用于生