javaweb搭建的增删改查项目

初学javaweb时搭建的一个小项目,对我来说算是有个里程碑的意义把。

本项目由servlet+jsp搭建而成,实现了单表crud功能,项目虽小,但也用了标准的三层架构

包结构如下:
javaweb搭建的增删改查项目_第1张图片
建库语句:CREATE TABLEstudent` (

id int(11) NOT NULL,
name varchar(255) NOT NULL,
age int(11) NOT NULL,
sex varchar(255) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO student VALUES (‘1’, ‘张三’, ‘10’, ‘男’);
INSERT INTO student VALUES (‘2’, ‘李四’, ‘11’, ‘男’);
INSERT INTO student VALUES (‘3’, ‘王五’, ‘12’, ‘女’);
INSERT INTO student VALUES (‘4’, ‘赵六’, ‘13’, ‘男’);
INSERT INTO student VALUES (‘5’, ‘。。。’, ‘13’, ‘未知’);`

1.实体类
Student.java

package com.cm.entity;

public class Student {
	
	private int id;
	private String name;
	private int age;
	private String sex;
	public Student() {
		super();
	}
	public Student(int id, String name, int age, String sex) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.sex = sex;
	}
	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;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	
	
}

PageO.java
(分页用到)

package com.cm.entity;

import java.util.List;

public class PageO {
	//当前页
	private int currentPage;
	//当前页码
	private int pageSize;
	//总数据条数
	private int totalCount;
	//总页数
	private int totalPage;
	private List students;
	public int getCurrentPage() {
		return currentPage;
	}
	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
		this.totalPage=this.totalCount%this.pageSize==0?this.totalCount/this.pageSize:this.totalCount/this.pageSize+1;
	}
	public int getTotalCount() {
		return totalCount;
	}
	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
	public int getTotalPage() {
		return totalPage;
	}
//	public void setTotalPage(int totalPage) {
//		this.totalPage = totalPage;
//	}
	public List getStudents() {
		return students;
	}
	public void setStudents(List students) {
		this.students = students;
	}
	public PageO(int currentPage, int pageSize, int totalCount, int totalPage, List students) {
		super();
		this.currentPage = currentPage;
		this.pageSize = pageSize;
		this.totalCount = totalCount;
		this.totalPage = totalPage;
		this.students = students;
	}
	public PageO() {
		super();
	}

}

2.jdbc工具类
Dbconn.java

package com.cm.util;

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



public class Dbconn {

	private static final String URL="jdbc:mysql://localhost:3306/smbms?useunicuee=true& characterEncoding=utf8";
	private static final String USERNAME="root";
	private static final String PASSWORD="123456";
	public static Connection connection=null;
	public static PreparedStatement pstm=null;
	public static ResultSet rs=null;
	public static boolean executeUpdate(String sql,Object[] pstms) {
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection=DriverManager.getConnection(URL,USERNAME,PASSWORD);
			pstm=connection.prepareStatement(sql);
			for (int i = 0; i < pstms.length; i++) {
				pstm.setObject(i+1, pstms[i]);
			}
			
			int count=pstm.executeUpdate();
			if(count>0){
				return true;
				}
			else{
				return false;
			}
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();	
			return false;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();	
			return false;
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
	}finally{
		try{
		if(rs!=null)rs.close();
		if(pstm!=null)pstm.close();
		if(connection!=null)connection.close();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}	
	
	}
	
	public static ResultSet qusery(String sql,Object[] pstms){
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection=DriverManager.getConnection(URL,USERNAME,PASSWORD);
			pstm=connection.prepareStatement(sql);
			if(pstms!=null){
			for (int i = 0; i < pstms.length; i++) {
				pstm.setObject(i+1, pstms[i]);
			}
			}
			rs=pstm.executeQuery();	
			return rs;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
	}
	
		
	}
	
	public static int getTotalCount(String sql) {
		int count=-1;
		
			try {
				rs = qusery(sql, null);
				if (rs.next()) {
				count=rs.getInt(1);
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				try{
					if(rs!=null)rs.close();
					if(pstm!=null)pstm.close();
					if(connection!=null)connection.close();
					}catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
					}
					
				}
			return count;	
			
		
	}
}

3.dao层
StudentDao.java

package com.cm.dao;

import java.util.List;
import com.cm.entity.Student;


public interface StudentDao {
	public Student quseryOne(int id);
	public boolean isExist(int id);
	public boolean add(Student student);
	public boolean delete(int id);
	public List qusery();
	public boolean updata(Student student);
	public int getTotalCount();
	public List queryByPage(int currentPage,int pageSize);
}

StudentDaoImpl.java

package com.cm.dao.Impl;

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

import com.cm.dao.StudentDao;
import com.cm.entity.Student;
import com.cm.util.Dbconn;

public class StudentDaoImpl implements StudentDao {

	public boolean isExist(int id) {
		return quseryOne(id) == null ? false : true;

	}

	public boolean add(Student student) {
		String sql = "insert into student values(?,?,?,?)";
		Object[] pstms = { student.getId(), student.getName(), student.getAge(), student.getSex() };
		return Dbconn.executeUpdate(sql, pstms);
	}

	public boolean delete(int id) {
		String sql = "delete from student where id=?";
		Object[] pstms = { id };
		return Dbconn.executeUpdate(sql, pstms);

	}

	public boolean updata(Student student) {
		String sql = "UPDATE student SET name=?,age=?,sex=? WHERE id=?";
		Object[] pstms = { student.getName(), student.getAge(), student.getSex(), student.getId() };
		return Dbconn.executeUpdate(sql, pstms);
	}

	public Student quseryOne(int id) {
		Student student = new Student();
		student = null;
		ResultSet rs = null;
		try {
			String sql = "select * from student where id=?";
			Object[] pstms = { id };
			rs = Dbconn.qusery(sql, pstms);
			if (rs.next()) {
				String name = rs.getString("name");
				int age = rs.getInt("age");
				String sex = rs.getString("sex");
				student = new Student(id, name, age, sex);
			}
			return student;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} finally {
			try{
				if(rs!=null)rs.close();
				if(Dbconn.pstm!=null)Dbconn.pstm.close();
				if(Dbconn.connection!=null)Dbconn.connection.close();
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				}

	}

	public List qusery(){
		List students=new ArrayList();
		ResultSet rs=null;
		
			String sql="select * from student";
			rs=Dbconn.qusery(sql, null);
			
				try {
					while(rs.next()) {
					Student student=new Student();
					student.setId( rs.getInt("id"));
					student.setName(rs.getString("name"));
					student.setAge(rs.getInt("age"));
					student.setSex(rs.getString("sex"));
					students.add(student);	
					}
					return students;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return null;
				}finally {
		try{
		if(rs!=null)rs.close();
		if(Dbconn.pstm!=null)Dbconn.pstm.close();
		if(Dbconn.connection!=null)Dbconn.connection.close();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		}
	}
	public int getTotalCount() {
		String sql="select count(1) from student";
		return Dbconn.getTotalCount(sql);
	}

	@Override
	public List queryByPage(int currentPage,int pageSize) {
		List students=new ArrayList();
		ResultSet rs=null;
		String sql="select * from student limit ? ,?";
		int i=(currentPage-1)*pageSize;
		Object[] pstms={i,pageSize};
			rs=Dbconn.qusery(sql, pstms);
			
				try {
					while(rs.next()) {
					Student student=new Student();
					student.setId( rs.getInt("id"));
					student.setName(rs.getString("name"));
					student.setAge(rs.getInt("age"));
					student.setSex(rs.getString("sex"));
					students.add(student);	
					}
					return students;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return null;
				}finally {
		try{
		if(rs!=null)rs.close();
		if(Dbconn.pstm!=null)Dbconn.pstm.close();
		if(Dbconn.connection!=null)Dbconn.connection.close();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		}
	}

}

4.service层
StudentService.java

package com.cm.service;


import java.util.List;
import com.cm.entity.Student;

public interface StudentService {
	public boolean add(Student student);
	public List qusery();
	public boolean delete(int id);
	public Student quseryOne(int id);
	public boolean updata(Student student);
	public List queryByPage(int currentPage,int pageSize);
	public int getTotalCount();

}

StudentServiceImpl.java

package com.cm.service.Impl;

import java.util.List;

import com.cm.dao.StudentDao;
import com.cm.dao.Impl.StudentDaoImpl;
import com.cm.entity.Student;
import com.cm.service.StudentService;


public class StudentServiceImpl implements StudentService {
	StudentDao studentDao=new StudentDaoImpl();
	public boolean add(Student student){
		if (!studentDao.isExist(student.getId())) {
			studentDao.add(student);
			return true;
		}else{
			System.out.println("此人已存在!");
			return false;
		}
		
	}
	public List qusery() {
		return studentDao.qusery();
	}
	public boolean delete(int id) {
		return studentDao.delete(id);
	}
	public Student quseryOne(int id) {
		return studentDao.quseryOne(id);
		}
	public boolean updata(Student student){
		return studentDao.updata(student);
	}
	public List queryByPage(int currentPage,int pageSize){
		return studentDao.queryByPage(currentPage, pageSize);
	}
	public int getTotalCount(){
		return studentDao.getTotalCount();
	}

}

5.视图层
servlet
AddStudentServlet.java

package com.cm.servlet;

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 com.cm.entity.Student;
import com.cm.service.StudentService;
import com.cm.service.Impl.StudentServiceImpl;



public class AddStudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	request.setCharacterEncoding("UTF-8");
	int id = Integer.parseInt(request.getParameter("id"));
	String name = request.getParameter("name");
	System.out.println(name);
	int age = Integer.parseInt(request.getParameter("age"));
	String sex=request.getParameter("sex");
	Student student=new Student(id,name,age,sex);
	StudentService studentService=new StudentServiceImpl();
	boolean result=studentService.add(student);
	response.setContentType("text/html;charset=UTF-8");
	response.setCharacterEncoding("utf-8");
	PrintWriter out = response.getWriter();
	if(result==true){
		out.print("增加成功");
	}else {
		out.print("增加失败");
	}
}
@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

DeleteStudentServlet.java

package com.cm.servlet;

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 com.cm.service.StudentService;
import com.cm.service.Impl.StudentServiceImpl;



public class DeleteStudentServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		StudentService studentService=new StudentServiceImpl();
		boolean result=studentService.delete(id);
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		if(result==true){
			out.print("删除成功");
		}else {
			out.print("删除失败");
		}
	}

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

		doGet(request, response);
	}

}

QueryStudentByPage.java

package com.cm.servlet;

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 com.cm.entity.PageO;
import com.cm.entity.Student;
import com.cm.service.StudentService;
import com.cm.service.Impl.StudentServiceImpl;


public class QueryStudentByPage extends HttpServlet {       
  
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	PageO pageo=new PageO();
	StudentService studentService=new StudentServiceImpl();
	int totalCount = studentService.getTotalCount();
	pageo.setTotalCount(totalCount);
	pageo.setPageSize(3);
	int currentPage;
	
	if (request.getParameter("currentPage")==null) {
		currentPage=1;
	}else {
		currentPage=Integer.parseInt(request.getParameter("currentPage"));
	}
	pageo.setCurrentPage(currentPage);
	List students=studentService.queryByPage(pageo.getCurrentPage(), pageo.getPageSize());
	pageo.setStudents(students);
	request.setAttribute("pageo", pageo);
	request.getRequestDispatcher("/paging.jsp").forward(request, response);
	}
	


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

}

ShowAllStudentServlet.java

package com.cm.servlet;

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 com.cm.entity.Student;
import com.cm.service.StudentService;
import com.cm.service.Impl.StudentServiceImpl;

public class ShowAllStudentServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		StudentService studentService=new StudentServiceImpl();
		List students=studentService.qusery();
		request.setAttribute("students", students);
		request.getRequestDispatcher("/list.jsp").forward(request, response);
	
	}

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



}

ShowOneStudentSevlet.java

package com.cm.servlet;

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 com.cm.entity.Student;
import com.cm.service.StudentService;
import com.cm.service.Impl.StudentServiceImpl;

public class ShowOneStudentSevlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		StudentService studentService=new StudentServiceImpl();
		Student student=new Student();
		student = studentService.quseryOne(id);
		request.setAttribute("student",student);
		request.getRequestDispatcher("/showone.jsp").forward(request, response);
	}

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

	doGet(request, response);
	}

}

UpdataStudentServlet.java

package com.cm.servlet;

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 com.cm.entity.Student;
import com.cm.service.StudentService;
import com.cm.service.Impl.StudentServiceImpl;


public class UpdataStudentServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		int id = Integer.parseInt(request.getParameter("id"));
		String name = request.getParameter("name");
		int age = Integer.parseInt(request.getParameter("age"));
		String sex=request.getParameter("sex");
		Student student=new Student(id,name,age,sex);
		StudentService studentService=new StudentServiceImpl();
		boolean result=studentService.updata(student);
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		if(result==true){
			out.print("修改成功");
		}else {
			out.print("修改失败");
		}
		
	}

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

		doGet(request, response);
	}

}

jsp
add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%
    request.setCharacterEncoding("UTF-8");
	%>




Insert title here

  
    
学号
姓名
年龄
性别

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="com.cm.entity.Student,com.cm.servlet.ShowAllStudentServlet,java.util.*"%>




Insert title here


   新增
   
<% List students=(List)request.getAttribute("students"); for(int i=0;i <% }%>
学号姓名年龄性别
<%=student.getName()%> <%=student.getAge()%> <%=student.getSex() %>

paging.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="com.cm.entity.Student,com.cm.servlet.ShowAllStudentServlet,java.util.*"%>




Insert title here


   新增
   
<% List students=(List)request.getAttribute("students"); for(int i=0;i <% }%>
学号姓名年龄性别
<%=student.getName()%> <%=student.getAge()%> <%=student.getSex() %>

showone.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%request.setCharacterEncoding("UTF-8");%>
<%@page import="com.cm.entity.Student"%>




Insert title here



   
<% Student student=(Student)request.getAttribute("student"); %>
学号姓名年龄性别操作
删除

最后还有一个web.xml文件



  
    QueryStudentByPage
  
  
    AddStudentServlet
    com.cm.servlet.AddStudentServlet
  
  
    ShouAllStudent
    com.cm.servlet.ShouAllStudent
  
  
    DeleteStudentServlet
    com.cm.servlet.DeleteStudentServlet
  
  
    ShowOneStudentSevlet
    com.cm.servlet.ShowOneStudentSevlet
  
  
    UpdataStudentServlet
    com.cm.servlet.UpdataStudentServlet
  
  
    QueryStudentByPage
    com.cm.servlet.QueryStudentByPage
  
  
    AddStudentServlet
    /AddStudentServlet
  
  
    ShouAllStudent
    /ShouAllStudent
  
  
    DeleteStudentServlet
    /DeleteStudentServlet
  
  
    ShowOneStudentSevlet
    /ShowOneStudentSevlet
  
  
    UpdataStudentServlet
    /UpdataStudentServlet
   
    QueryStudentByPage
    /QueryStudentByPage
  

运行效果如下:
javaweb搭建的增删改查项目_第2张图片
点击id按键进入操作页:
javaweb搭建的增删改查项目_第3张图片
这是初学时做的第一个比较成功的小项目,代码量较大,但实现的功能却不多,还有很多地方也都没有完善,现在也不太愿意去继续完善它了,但毕竟是个能跑的项目,算是留作一个纪念吧。

你可能感兴趣的:(个人小项目,javaweb)