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

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

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

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

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

工程整体架构如下图:

简易jsp+servlet实现单表增删查改_第1张图片
















数据库新建一张名为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 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 getAllUsers() {
		List ulist = new ArrayList();
		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 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("");
		}
		if (dos.equals("del")) {
			String ids = request.getParameter("id");
			int id = Integer.parseInt(ids);
			ud.delUser(id);
			out.print("");
			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("");
			return;
		}
	}
}

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



	jdbc
  
    This is the description of my J2EE component
    This is the display name of my J2EE component
    ServletUsers
    com.zdf.servlet.ServletUsers
  

  
    ServletUsers
    /servletusers
  
	
		servletusers
	

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 + "/";
%>






My JSP 'index.jsp' starting page










	

主页

id 姓名 年龄 操作
${data.id } ${data.name } ${data.age } 修改 删除
新增


add.jsp

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



  
    
    
    My JSP 'add.jsp' starting page
    
	
	
	    
	
	
	

  
  
  
    

新增页面

姓名:
年龄:
 

edit.jsp

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



  
    
    
    My JSP 'add.jsp' starting page
    
	
	
	    
	
	
	

  
  
  
    

修改页面

姓名:
年龄:
 

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

http://localhost:8080/jdbc/

简易jsp+servlet实现单表增删查改_第2张图片

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





你可能感兴趣的:(java,web)