简易jsp+servlet实现单表增删查改

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/maple082/article/details/52904123

入职一个月了,感觉并没有当初学习时突飞猛进的感觉,公司并没有用到我所学习的ssh框架,在我学了各种springMVC+mybatis框架后仍旧是一头雾水,反正写代码的时候只是把前台页面添加数据,并在springmvc的controller层类中添加相应的方法。想来实在是无所事事,不如学习一下数据结构和算法,并补一补毕向东老师的javase基础视频。

 今天就来自己复习一下当初所学的原生web搭建:jsp+servlet。只要这个没有忘,框架什么的都是浮云(喂,这是在骗自己吗)。

好了,废话这么多,我们言归正传。首先本项目(这能算项目吗= =)使用到的软件环境有:MyEclipse2014,Tomcat7,数据库:mysql。还有什么待补充。

补充:本项目需要mysql连接jdbc的jar包,以及jstl的jar包,这里暂不提供下载,请自行百度

工程整体架构如下图:

项目架构
















数据库新建一张名为users的表,此表是参考了此mybatis学习贴

http://www.cnblogs.com/xdp-gacl/p/4261895.html


 CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT);
 INSERT INTO users(NAME, age) VALUES('蕾姆', 17);
 INSERT INTO users(NAME, age) VALUES('艾米莉亚', 17);
数据库准备工作完成,开始搭建web项目。


首先,在MyEclipse新建一个web项目。

然后,依次编写BaseDao(用途是jdbc连接数据库),Users(实体类),UsersDao(接口),UsersDaoImpl(实现类),以及Servlet类:ServletUsers

然后是前端页面:index.jsp用于展示数据列表。然后还有add.jsp是新增页面,edit.jsp是修改页面。

BaseDao代码:

package com.zdf.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDao {
	public static final String DRIVER = "com.mysql.jdbc.Driver";
	public static final String URL = "jdbc:mysql://localhost:3306/mybatis";
	public static final String USER = "root";
	public static final String PASSWORD = "";

	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;

	public void getConnection() {
		try {
			Class.forName(DRIVER);
			conn = DriverManager.getConnection(URL, USER, PASSWORD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public int executeUpdate(String sql, Object... obj) {
		int num = 0;
		getConnection();
		try {
			pstmt = conn.prepareStatement(sql);
			for (int i = 0; i < obj.length; i++) {
				pstmt.setObject(i + 1, obj[i]);
			}
			num = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeAll();
		}
		return num;
	}

	public ResultSet executeQuery(String sql, Object... obj) {
		getConnection();
		try {
			pstmt = conn.prepareStatement(sql);
			for (int i = 0; i < obj.length; i++) {
				pstmt.setObject(i + 1, obj[i]);
			}
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	public void closeAll() {
		try {
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			pstmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

UsersDao代码:

package com.zdf.dao;

import java.util.List;

import com.zdf.entity.Users;

public interface UsersDao {
	public int addUser(Users u);
	public int delUser(int id);
	public int updateUser(Users u);
	public Users findUserById(int id);
	public List<Users> getAllUsers();
}

UsersDaoImpl代码:

package com.zdf.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.zdf.dao.BaseDao;
import com.zdf.dao.UsersDao;
import com.zdf.entity.Users;

public class UsersDaoImpl extends BaseDao implements UsersDao {

	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;

	@Override
	public int addUser(Users u) {
		int num = 0;
		String sql = "insert into users(name,age) values(?,?)";
		try {
			num = executeUpdate(sql, u.getName(), u.getAge());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return num;
	}

	@Override
	public int delUser(int id) {
		int num = 0;
		String sql = "delete from users where id=?";
		try {
			num = executeUpdate(sql, id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return num;
	}

	@Override
	public int updateUser(Users u) {
		int num = 0;
		String sql = "update users set name=?,age=? where id=?";
		try {
			num = executeUpdate(sql, u.getName(), u.getAge(), u.getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return num;
	}

	@Override
	public Users findUserById(int id) {
		Users u = null;
		String sql = "select * from users where id=?";
		rs = executeQuery(sql, id);
		try {
			if (rs.next()) {
				u = new Users(rs.getInt(1), rs.getString(2), rs.getInt(3));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return u;
	}

	@Override
	public List<Users> getAllUsers() {
		List<Users> ulist = new ArrayList<Users>();
		String sql = "select * from users";
		rs = executeQuery(sql);
		try {
			while (rs.next()) {
				Users u = new Users(rs.getInt(1), rs.getString(2), rs.getInt(3));
				ulist.add(u);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return ulist;
	}

}

Users代码:

package com.zdf.entity;

/**
 * users表所对应的实体类
 */
public class Users {

	// 实体类的属性和表的字段名称一一对应
	private int id;
	private String name;
	private int age;

	public Users(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public Users() {
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
}

ServletUsers代码:

package com.zdf.servlet;

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 javax.servlet.http.HttpSession;

import com.zdf.dao.UsersDao;
import com.zdf.dao.impl.UsersDaoImpl;
import com.zdf.entity.Users;

public class ServletUsers extends HttpServlet {


	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

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

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

		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();

		UsersDao ud = new UsersDaoImpl();

		String dos = request.getParameter("do");
		if (dos == null || dos.equals("")) {
			dos = "index";
		}
		// 主页
		if (dos.equals("index")) {
			List<Users> ulist = ud.getAllUsers();
			session.setAttribute("ulist", ulist);
			response.sendRedirect("index.jsp");
			return;
		}
		if (dos.equals("add")) {
			String name = request.getParameter("name");
			String ages = request.getParameter("age");
			int age = Integer.parseInt(ages);
			Users u = new Users(0, name, age);
			ud.addUser(u);
			out.print("<script>alert('新增成功!');window.location='servletusers?do=index';</script>");
		}
		if (dos.equals("del")) {
			String ids = request.getParameter("id");
			int id = Integer.parseInt(ids);
			ud.delUser(id);
			out.print("<script>alert('删除成功!');window.location='servletusers?do=index';</script>");
			return;
		}
		if (dos.equals("editbefore")) {
			String ids = request.getParameter("id");
			int id = Integer.parseInt(ids);
			Users u=ud.findUserById(id);
			session.setAttribute("edituser", u);
			response.sendRedirect("edit.jsp");
			return;
		}
		if (dos.equals("edit")) {
			String ids=request.getParameter("id");
			int id=Integer.parseInt(ids);
			String name = request.getParameter("name");
			String ages = request.getParameter("age");
			int age = Integer.parseInt(ages);
			Users u = new Users(id, name, age);
			ud.updateUser(u);
			out.print("<script>alert('修改成功!');window.location='servletusers?do=index';</script>");
			return;
		}
	}
}

web.xml配置(其实并没有写什么东西,注意welcome-file起始页面跳转就可以了,如果你是一路复制过来的,那么这个也要原样复制,因为它包含了servlet类的配置)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>jdbc</display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ServletUsers</servlet-name>
    <servlet-class>com.zdf.servlet.ServletUsers</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>ServletUsers</servlet-name>
    <url-pattern>/servletusers</url-pattern>
  </servlet-mapping>
	<welcome-file-list>
		<welcome-file>servletusers</welcome-file>
	</welcome-file-list>
</web-app>

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.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">
	-->
<style type="text/css">
table {
	width: 600px;
	height: 300px;
}
td{ text-align:center;}
</style>
</head>

<body>
	<h1>主页</h1>
	<table border="1px">
		<tr>
			<th>id</th>
			<th>姓名</th>
			<th>年龄</th>
			<th>操作</th>
		</tr>
		<c:forEach items="${ulist }" var="data">
			<tr>
				<td>${data.id }</td>
				<td>${data.name }</td>
				<td>${data.age }</td>
				<td><a href="servletusers?do=editbefore&id=${data.id }">修改</a> <a
					href="servletusers?do=del&id=${data.id }" οnclick="javascript:return confirm('确认删除吗?');">删除</a></td>
			</tr>
		</c:forEach>
	</table>
	
<a href="add.jsp">新增</a>
</body>
</html>


add.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'add.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>
  
  <body>
    <h1>新增页面</h1>
    <form action="servletusers?do=add" method="post">
    姓名:<input name="name"><br>
    年龄:<input name="age" ><br>
    <input type="submit" value="新增" > <input type="reset">
    </form>
  </body>
</html>

edit.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'add.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>
  
  <body>
    <h1>修改页面</h1>
    <form action="servletusers?do=edit" method="post">
    <input type="hidden" name="id" value="${edituser.id }">
    姓名:<input name="name" value="${edituser.name }"><br>
    年龄:<input name="age" value="${edituser.age }" ><br>
    <input type="submit" value="修改" > <input type="reset">
    </form>
  </body>
</html>

ok,现在打开浏览器,输入

http://localhost:8080/jdbc/


项目就搭建好啦,接下来就测试一下增删改功能是否正确执行了吧!





展开阅读全文

没有更多推荐了,返回首页