JavaWeb学习笔记及案例(二)MVC设计模式

1.MVC三层架构

M:Model>>>模型层:封装数据Java Bean;
V:View>>>视图层:jsp专注显示;
C:Controller>>>控制层:Servlet接收页面请求,找模型层处理,然后响应数据出去;
**好处:**分层,逻辑清楚,便于维护,扩展方便;【适用大型项目】
**缺点:**小型项目,代码稍多;
三层架构与MVC的关系
在这里插入图片描述

2.实战案例:学生管理系统

整个项目工程布局图

在这里插入图片描述
环境搭建,准备工作
第一步:1.数据库建表,添加数据;

mysql> create table stu(
    -> id int primary key not null auto_increment,
    -> name varchar(20),
    -> gender varchar(2),
    -> phone varchar(12),
    -> birthday date,
    -> hobby varchar(50),
    -> info varchar(200)
    -> );
Query OK, 0 rows affected

需要导入必要的jar包
在这里插入图片描述
2.数据库连接c3p0配置文件【c3p0-config.xml】
一般只需修改默认配置即可

<c3p0-config>
	<!-- default-config 默认的配置,  -->
  <default-config>
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost/students</property>
    <property name="user">root</property>
    <property name="password">123456</property>
    
    <property name="initialPoolSize">10</property>
    <property name="maxIdleTime">30</property>
    <property name="maxPoolSize">100</property>
    <property name="minPoolSize">10</property>
    <property name="maxStatements">200</property>
  </default-config>
  
   <!-- This app is massive! -->
  <named-config name="oracle"> 
    <property name="acquireIncrement">50</property>
    <property name="initialPoolSize">100</property>
    <property name="minPoolSize">50</property>
    <property name="maxPoolSize">1000</property>

    <!-- intergalactoApp adopts a different approach to configuring statement caching -->
    <property name="maxStatements">0</property> 
    <property name="maxStatementsPerConnection">5</property>

    <!-- he's important, but there's only one of him -->
    <user-overrides user="master-of-the-universe"> 
      <property name="acquireIncrement">1</property>
      <property name="initialPoolSize">1</property>
      <property name="minPoolSize">1</property>
      <property name="maxPoolSize">5</property>
      <property name="maxStatementsPerConnection">50</property>
    </user-overrides>
  </named-config>
</c3p0-config>

3.封装JDBCUtil.java用来获取来连接,一般放在util包下

package Student.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JDBCUtil {
	
	static ComboPooledDataSource dataSource = null;
	static{
		dataSource = new ComboPooledDataSource();
	}
	
	public static DataSource getDataSource(){
		return dataSource;
	}
	
	/**
	 * 获取连接对象
	 * @return
	 * @throws SQLException 
	 */
	public static Connection getConn() throws SQLException{
		return dataSource.getConnection();
	}
	
	/**
	 * 释放资源
	 * @param conn
	 * @param st
	 * @param rs
	 */
	public static void release(Connection conn , Statement st , ResultSet rs){
		closeRs(rs);
		closeSt(st);
		closeConn(conn);
	}
	public static void release(Connection conn , Statement st){
		closeSt(st);
		closeConn(conn);
	}
	private static void closeRs(ResultSet rs){
		try {
			if(rs != null){
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			rs = null;
		}
	}
	
	private static void closeSt(Statement st){
		try {
			if(st != null){
				st.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			st = null;
		}
	}
	
	private static void closeConn(Connection conn){
		try {
			if(conn != null){
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			conn = null;
		}
	}
}

4.同样在util包下创建一个TextUtil,用来判断字符是否为空

/**
 * @author Leonard
 *	判断一个字符串是否为空
 */
public class TextUtils {
	public static boolean isEmpty(CharSequence s){
		return s==null || s.length()==0;
	}
}

接下开始写项目了。。。。。。。。。。。。。。。。。
写项目
项目完成预览图
在这里插入图片描述
进入第一个列表
在这里插入图片描述
分页显示页面
在这里插入图片描述
第一步:创建jsp页面及对应的Servlet
1.创建index.jsp显示页面

<body>
	//超链接的地址是Servlet控制层
    <h3><a href="StudentListServlet">显示所有学生列表</a></h3><br>
    <h3><a href="StudentListPageServlet?currentPage=1">分页显示所有学生列表</a></h3>
</body>

StudentListServlet.java

public class StudentListServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try {
			StudentService service = new StudentServiceImpl();
			List<Student> list = service.findAll();
			//把结果存域
			request.getSession().setAttribute("list", list);
			//重定向方式,把结果存到session域需要
			response.sendRedirect("list.jsp");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

StudentListPageServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//1.获取需要显示的页码数
			int currentPage = Integer.parseInt(request.getParameter("currentPage"));
			//2.根据指定页数获取该页数据回来;
			StudentService service = new StudentServiceImpl();
			PageBean pageBean = service.findStudentByPage(currentPage);
			request.setAttribute("pageBean", pageBean);
			//3.跳转页面
			request.getRequestDispatcher("list_page.jsp").forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

2.查询显示页面list.jsp

html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
      function doDelete(sid){
    	  var flag = confirm("是否删除?");
    	  if(flag){
    		  location.href="DeleteServlet?sid="+sid;
    	  }
      }
</script>
<title>学生列表页面</title>
</head>
<body>
	<form action="SearchStudentServlet" method="post">
	    <table border="1" cellspacing="0">
	        <tr>
	            <td colspan="8">
			                按姓名查询:<input type="text" name="sname">
			                &nbsp; &nbsp; &nbsp;
			                按性别查询:<select name="gender" >
	                     <option value="">--请选择--
	                     <option value="男">男
	                     <option value="女">女
	                     </select>
	                       &nbsp; 
	              <input type="submit" value="查询"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
	              <a href="add.jsp">添加</a>
	            </td>
	        </tr>
	        <tr>
	            <td>编号</td>
	            <td>姓名</td>
	            <td>性别</td>
	            <td>电话</td>
	            <!-- <td>生日</td> -->
	            <td>爱好</td>
	            <td>简介</td>
	            <td>操作</td>
	        </tr>
	        <c:forEach items="${list}" var="stu">
		        <tr>
		            <td>${stu.sid}</td>
		            <td>${stu.sname}</td>
		            <td>${stu.gender}</td>
		            <td>${stu.phone}</td>
		            <%-- <td>${stu.birthday}</td> --%>
		            <td>${stu.hobby}</td>
		            <td>${stu.info}</td>
		            <td><a href="EditServlet?sid=${stu.sid}">更新</a>  <a href="#" onclick="doDelete(${stu.sid})">删除</a></td>
		        </tr>
	        </c:forEach>
	    </table>
	</form>
</body>
</html>

SearchStudentServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try {
			//1.中文
			request.setCharacterEncoding("UTF-8");
			//2.获取前台数据
			String sname = request.getParameter("sname");
			String gender = request.getParameter("gender");
			
			//3.调用service
			StudentService service = new StudentServiceImpl();
			List<Student> list = service.SearchStudentList(sname, gender);
			System.out.println("list集合大小========"+list.size());
			for (Student student : list) {
				System.out.println(student);
			}
			
			request .setAttribute("list", list);
			
			request.getRequestDispatcher("list.jsp").forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

EditServlet.java

扫描二维码关注公众号,回复: 4138738 查看本文章
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			int sid = Integer.parseInt(request.getParameter("sid"));
			//查数据
			StudentService service = new StudentServiceImpl();
			Student student = service.findStudentById(sid);
			//存数据
			request.setAttribute("stu", student);
			//跳转
			request.getRequestDispatcher("edit.jsp").forward(request, response);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}

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

DeleteServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			int sid = Integer.parseInt(request.getParameter("sid"));
			
			StudentService service = new StudentServiceImpl();
			service.delete(sid);
			
			request.getRequestDispatcher("StudentListServlet").forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

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

3.添加数据页面add.jsp

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加学生页面</title>
</head>
<body>
	<form action="AddServlet" method="post">
		<table border="1" width="600">
		    <tr>
		        <td>姓名</td>
		        <td><input type="text" name="sname"></td>
		    </tr>
		    <tr>
		        <td>性别</td>
		        <td>
		            <input type="radio" name="gender" value="男" checked="checked">男
		            <input type="radio" name="gender" value="女">女
		        </td>
		    </tr>
		    <tr>
		        <td>电话</td>
		        <td><input type="text" name="phone"></td>
		    </tr>
		    <!-- <tr>
		        <td>生日</td>
		        <td><input type="text" name="birthday"></td>
		    </tr> -->
		    <tr>
		        <td>爱好</td>
		        <td>
		            <input type="checkbox" name="hobby" value="篮球">篮球
		            <input type="checkbox" name="hobby" value="跑步">跑步
		            <input type="checkbox" name="hobby" value="读书">读书
		            <input type="checkbox" name="hobby" value="编程">编程
		        </td>
		    </tr>
		    <tr>
		        <td>简介</td>
		        <td><textarea name="info" rows="3" cols="20"></textarea></td>
		    </tr>
		    <tr>
		        <td colspan="2" align="center"><input type="submit" value="添加"></td>
		    </tr>
	    </table>
	</form>
</body>
</html>

AddServlet.java

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try {
			request.setCharacterEncoding("UTF-8");
			String sname = request.getParameter("sname");
			String gender = request.getParameter("gender");
			String phone = request.getParameter("phone");
			/*String birthday = request.getParameter("birthday");*/
			/*String hobby = request.getParameter("hobby");*/
			String info = request.getParameter("info");
			
			String[] h = request.getParameterValues("hobby");
			String s = Arrays.toString(h);
			String hobby = s.substring(1, s.length()-1);
			
		/*	Date date = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);*/
			//添加到数据库
			Student student = new Student(sname, gender, phone,hobby, info);
			
			StudentService service = new StudentServiceImpl();
			service.insert(student);
			
			request.getRequestDispatcher("StudentListServlet").forward(request, response);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

4.编辑更新更改数据页面edit.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>更新学生页面</title>
</head>
<body>
	<form action="UpdateServlet" method="post">
	
		<table border="1" width="600">
		  <input type="hidden" name="sid" value="${stu.sid}" ><!-- 隐藏 -->
		    <tr>
		        <td>姓名</td>
		        <td><input type="text" name="sname" value="${stu.sname}"></td>
		    </tr>
		    <tr>
		        <td>性别</td>
		        <td>
		            <input type="radio" name="gender" value="男" checked="checked"
		              <c:if test="${stu.gender =='男'}">checked</c:if>
		            >男
		            <input type="radio" name="gender" value="女"
		              <c:if test="${stu.gender=='女'}">checked</c:if>
		            >女
		        </td>
		    </tr>
		    <tr>
		        <td>电话</td>
		        <td><input type="text" name="phone" value="${stu.phone}"></td>
		    </tr>
		    <!-- <tr>
		        <td>生日</td>
		        <td><input type="text" name="birthday"></td>
		    </tr> -->
		    <tr>
		        <td>爱好</td>
		        <td>
		            <input type="checkbox" name="hobby" value="篮球"
		              <c:if test="${fn:contains(stu.hobby,'篮球')}">checked</c:if>
		            >篮球
		            <input type="checkbox" name="hobby" value="跑步"
		              <c:if test="${fn:contains(stu.hobby,'跑步')}">checked</c:if>
		            >跑步
		            <input type="checkbox" name="hobby" value="读书"
		              <c:if test="${fn:contains(stu.hobby,'读书')}">checked</c:if>
		            >读书
		            <input type="checkbox" name="hobby" value="编程"
		              <c:if test="${fn:contains(stu.hobby,'编程')}">checked</c:if>
		            >编程
		        </td>
		    </tr>
		    <tr>
		        <td>简介</td>
		        <td><textarea name="info" rows="3" cols="20">${stu.info}</textarea></td>
		    </tr>
		    <tr>
		        <td colspan="2" align="center"><input type="submit" value="更新"></td>
		    </tr>
	    </table>
	</form>
</body>
</html>

UpdateServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		try {
			request.setCharacterEncoding("UTF-8");
			int sid = Integer.parseInt(request.getParameter("sid"));
			String sname = request.getParameter("sname");
			String gender = request.getParameter("gender");
			String phone = request.getParameter("phone");
			/*String birthday = request.getParameter("birthday");*/
			/*String hobby = request.getParameter("hobby");*/
			String info = request.getParameter("info");
			
			String[] h = request.getParameterValues("hobby");
			String s = Arrays.toString(h);
			String hobby = s.substring(1, s.length()-1);
			
		/*	Date date = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);*/
			//添加到数据库
			Student student = new Student(sid, sname, gender, phone,hobby, info);
			
			StudentService service = new StudentServiceImpl();
			service.update(student);
			
			request.getRequestDispatcher("StudentListServlet").forward(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

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

5.分页页面list_page.jsp

<script type="text/javascript">
      function doDelete(sid){
    	  var flag = confirm("是否删除?");
    	  if(flag){
    		  location.href="DeleteServlet?sid="+sid;
    	  }
      }
</script>
<title>学生列表页面</title>
</head>
<body>
	<form action="SearchStudentServlet" method="post">
	    <table border="1" cellspacing="0">
	        <tr>
	            <td colspan="8">
			                按姓名查询:<input type="text" name="sname">
			                &nbsp; &nbsp; &nbsp;
			                按性别查询:<select name="gender" >
	                     <option value="">--请选择--
	                     <option value="男">男
	                     <option value="女">女
	                     </select>
	                       &nbsp; 
	              <input type="submit" value="查询"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
	              <a href="add.jsp">添加</a>
	            </td>
	        </tr>
	        <tr>
	            <td>编号</td>
	            <td>姓名</td>
	            <td>性别</td>
	            <td>电话</td>
	            <!-- <td>生日</td> -->
	            <td>爱好</td>
	            <td>简介</td>
	            <td>操作</td>
	        </tr>
	        <c:forEach items="${pageBean.list}" var="stu">
		        <tr>
		            <td>${stu.sid}</td>
		            <td>${stu.sname}</td>
		            <td>${stu.gender}</td>
		            <td>${stu.phone}</td>
		            <%-- <td>${stu.birthday}</td> --%>
		            <td>${stu.hobby}</td>
		            <td>${stu.info}</td>
		            <td><a href="EditServlet?sid=${stu.sid}">更新</a>  <a href="#" onclick="doDelete(${stu.sid})">删除</a></td>
		        </tr>
	        </c:forEach>
	       <td colspan="8">
	                  第${pageBean.currentPage }/${pageBean.totalPage }页&nbsp;&nbsp;&nbsp;&nbsp;
			           每页显示${pageBean.pageSize }  条      &nbsp;&nbsp;
			           总记录数${pageBean.totalSize } 条       &nbsp;&nbsp;
			    <c:if test="${pageBean.currentPage != 1 }">
				    <a href="StudentListPageServlet?currentPage=1">首页</a>
				    <a href="StudentListPageServlet?currentPage=${pageBean.currentPage-1}">上一页</a>  &nbsp;&nbsp;
			    </c:if>
			    <c:if test="${pageBean.currentPage == 1 }">
			       <a href="StudentListPageServlet?currentPage=1">首页</a> 
			                                                                                                                                     上一页 
			    </c:if>
			    |
			    <c:forEach begin="1" end="${pageBean.totalPage }" var="i">
			         <c:if test="${ pageBean.currentPage == i}">
			             ${i }
			         </c:if>
			         <c:if test="${ pageBean.currentPage != i}">
			             <a href="StudentListPageServlet?currentPage=${ i}">${i }</a>
			          </c:if>      
			    </c:forEach>
			    |
			    <c:if test="${pageBean.currentPage == pageBean.totalPage }">
                                                                                                                                                                                                                       下一页 
                   <a href="StudentListPageServlet?currentPage=${pageBean.totalPage}">尾页</a> &nbsp;&nbsp;
                </c:if>
			    <c:if test="${pageBean.currentPage != pageBean.totalPage }">
				     <a href="StudentListPageServlet?currentPage=${pageBean.currentPage+1 }">下一页</a>
	                 <a href="StudentListPageServlet?currentPage=${pageBean.totalPage}">尾页</a>
			    </c:if>	     
	       </td>
	    </table>
	</form>
</body>
</html>

第二步:创建domain层
1.Student类

public class Student {
	private int sid;
	private String sname;
	private String gender;
	private String phone;
	/*private Date birthday;*/
	private String hobby;
	private String info;
	public int getSid() {
		return sid;
	}
	public void setSid(int sid) {
		this.sid = sid;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	/*public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}*/
	public String getHobby() {
		return hobby;
	}
	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	public String getInfo() {
		return info;
	}
	public void setInfo(String info) {
		this.info = info;
	}
	
	@Override
	public String toString() {
		return "Student [sid=" + sid + ", sname=" + sname + ", gender="
						+ gender + ", phone=" + phone + ",  hobby=" + hobby + ", info=" + info
						+ "]";
	}
	public Student(String sname, String gender, String phone, String hobby,
					String info) {
		super();
		this.sname = sname;
		this.gender = gender;
		this.phone = phone;
		this.hobby = hobby;
		this.info = info;
	}
	public Student(int sid, String sname, String gender, String phone,
					String hobby, String info) {
		super();
		this.sid = sid;
		this.sname = sname;
		this.gender = gender;
		this.phone = phone;
		this.hobby = hobby;
		this.info = info;
	}
	public Student() {
		super();
	}
}

2.创建pageBean

/**
 * @author Leonard
 * 
 * 用于封装分页的数据
 * 里面包含:1.该页学生集合数据
 * 2.总的记录数
 * 3.总的页数
 * 4.当前页
 * 5.每页显示的记录数
 *
 */
public class PageBean<T> {
	private int currentPage;//当前页
	private int totalPage;//总页数
	private int pageSize;//每页记录数
	private int totalSize;//总的记录数
	private List<T> list;//当前页的学生集合
	public int getCurrentPage() {
		return currentPage;
	}
	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}
	public int getTotalPage() {
		return totalPage;
	}
	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public int getTotalSize() {
		return totalSize;
	}
	public void setTotalSize(int totalSize) {
		this.totalSize = totalSize;
	}
	public List<T> getList() {
		return list;
	}
	public void setList(List<T> list) {
		this.list = list;
	}
}

第三步:创建DAO及Dao的实现
1.StudentDao.java

public interface StudentDao {
	int PAGE_SIZE = 5;//代表一页显示多少数据
	/**
	 * @param 查询当页的学生数据
	 * @return
	 * @throws SQLException
	 */
	List<Student> findStudentByPage(int currentPage) throws SQLException;
	
	/**
	 * 查询总的学生记录数
	 * @return
	 * @throws SQLException
	 */
	int findCount() throws SQLException;
	
	List<Student> findAll() throws SQLException;
	
	//根据ID查询单个学生
	Student findStudentById(int sid)  throws SQLException;
	
	//根据条件进行模糊查询
	List<Student> SearchStudentList(String sname,String gender) throws SQLException;
	
	void insert(Student student) throws SQLException;
	
	void delete(int sid) throws SQLException;
	
	void update(Student student) throws SQLException;
}

2.StudentDaoImpl.java

public class StudentDaoImpl implements StudentDao {

	@Override
	public List<Student> findAll() throws SQLException {
		QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
		List<Student> list = runner.query("select * from stu", 
						new BeanListHandler<Student>(Student.class));
		return list;
	}

	@Override
	public void insert(Student student) throws SQLException {
		QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
		runner.update("insert into stu values(null,?,?,?,?,?)", 
						student.getSname(),
						student.getGender(),
						student.getPhone(),
						/*student.getBirthday(),*/
						student.getHobby(),
						student.getInfo()
						);
	}

	@Override
	public void delete(int sid) throws SQLException {
		QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
		runner.update("delete from stu where sid=?", sid);
	}

	@Override
	public Student findStudentById(int sid) throws SQLException {
		QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
		return runner.query("select * from stu where sid=?", new BeanHandler<Student>(Student.class),sid);
	}

	@Override
	public void update(Student student) throws SQLException {
		QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
		runner.update("update stu set sname=?,gender=?,phone=?,hobby=?,info=? where sid = ?",
						student.getSname(),
						student.getGender(),
						student.getPhone(),
						/*student.getBirthday(),*/
						student.getHobby(),
						student.getInfo(),
						student.getSid()
						);
	}

	@Override
	public List<Student> SearchStudentList(String sname, String gender)
					throws SQLException {
		System.out.println("模糊查询====="+sname+"=========="+gender);
		QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
		//1=1:代表查询全部的
		String sql="select * from stu where 1=1 ";
		List<String> list = new ArrayList<String>();
		//判断是否输入了姓名查询,若有数据就拼到sql语句里
		if(!TextUtils.isEmpty(sname)){ 
			sql = sql + " and sname like ?";
			list.add("%"+sname+"%");
		}
		//是否输入了按性别查询,如果有,就拼接到sql里,且把输入的性别追加到集合里
		if(!TextUtils.isEmpty(gender)){
			sql = sql + " and gender = ?";
			list.add(gender);
		}
		
		List<Student> query = runner.query(sql, new BeanListHandler<Student>(Student.class),
						list.toArray()//集合转为数组
						);
		return query;
	}

	@Override
	public List<Student> findStudentByPage(int currentPage) throws SQLException {
		QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
		//第一个问号代表返回多少记录,第二个问号代表前面跳过多少记录;;;
		List<Student> list = runner.query("select * from stu limit ? offset ?", 
						new BeanListHandler<Student>(Student.class),
						PAGE_SIZE,(currentPage-1)*PAGE_SIZE
						);
		return list;
	}

	/* 
		查询总的记录数
	 */
	@Override
	public int findCount() throws SQLException {
		QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
		// ScalarHandler()用于处理 平均值,总的个数等
		Long query = (Long) runner.query("select count(*) from stu",
						new ScalarHandler()
						);
		//转为int型
		return query.intValue();
	}
}

第三步:创建service层及service的实现
1.StudentService.java

public interface StudentService {
	List<Student> findAll() throws SQLException;
	
	//根据ID查询单个学生
	Student findStudentById(int sid) throws SQLException;
	
	//根据条件进行模糊查询
	List<Student> SearchStudentList(String sname,String gender) throws SQLException;
	
	void insert(Student student) throws SQLException;
	
	void delete(int sid) throws SQLException;
	
	void update(Student student) throws SQLException;
	
	/**
	 * @param 查询当页数据
	 * @return
	 * @throws SQLException
	 */
	PageBean findStudentByPage(int currentPage) throws SQLException;
}

2.StudentServiceImpl.java

public class StudentServiceImpl implements StudentService {

	@Override
	public List<Student> findAll() throws SQLException {
		StudentDao dao = new StudentDaoImpl();
		return dao.findAll();
	}

	@Override
	public void insert(Student student) throws SQLException {
		StudentDao dao = new StudentDaoImpl();
		dao.insert(student);
		
	}

	@Override
	public void delete(int sid) throws SQLException {
		StudentDao dao = new StudentDaoImpl();
		dao.delete(sid);
		
	}

	@Override
	public Student findStudentById(int sid) throws SQLException {
		StudentDao dao = new StudentDaoImpl();
		return dao.findStudentById(sid);
		
	}

	@Override
	public void update(Student student) throws SQLException {
		StudentDao dao = new StudentDaoImpl();
		dao.update(student);
	}

	@Override
	public List<Student> SearchStudentList(String sname, String gender)
					throws SQLException {
		StudentDao dao = new StudentDaoImpl();
		return dao.SearchStudentList(sname, gender);
	}

	@Override
	public PageBean findStudentByPage(int currentPage) throws SQLException {
		//封装分页的该页数据
		PageBean<Student> pageBean = new PageBean<Student>();

		pageBean.setCurrentPage(currentPage);//1.设置当前页
		int pageSize = StudentDaoImpl.PAGE_SIZE;
		pageBean.setPageSize(pageSize);//2.设置每页显示多少数据
		
		StudentDao dao = new StudentDaoImpl();
		List<Student> list = dao.findStudentByPage(currentPage);
		pageBean.setList(list);//3.设置该页的学生数据
		
		int count = dao.findCount();
		pageBean.setTotalSize(count);//4.设置总的记录数
		
		pageBean.setTotalPage(count%pageSize==0? count/pageSize : (count/pageSize)+1);//5.设置总页数
		
		return pageBean;
	}
}

第四步:由Servlet调service层
参考第一步:jsp页面对应着Servlet

3.分页设计详解
1.创建StudentListPageServlet.java

public class StudentListPageServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.获取需要显示的页码数
		int currentPage = Integer.parseInt(request.getParameter("currentPage"));
		//2.根据指定页数获取该页数据回来;
		StudentService service = new StudentServiceImpl();
		PageBean pageBean = service.findStudentByPage(currentPage);
		request.setAttribute("pageBean", pageBean);
		//3.跳转页面
		request.getRequestDispatcher("list_page.jsp").forward(request, response);
	}

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

2.domain层创建用于封装分页的数据pageBean类

/**
 * @author Leonard
 * 用于封装分页的数据
 * 里面包含:1.该页学生集合数据
 * 2.总的记录数
 * 3.总的页数
 * 4.当前页
 * 5.每页显示的记录数
 */
public class PageBean<T> {
	private int currentPage;//当前页
	private int totalPage;//总页数
	private int pageSize;//每页记录数
	private int totalSize;//总的记录数
	private List<T> list;//当前页的学生集合
	public int getCurrentPage() {
		return currentPage;
	}
	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}
	public int getTotalPage() {
		return totalPage;
	}
	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public int getTotalSize() {
		return totalSize;
	}
	public void setTotalSize(int totalSize) {
		this.totalSize = totalSize;
	}
	public List<T> getList() {
		return list;
	}
	public void setList(List<T> list) {
		this.list = list;
	}
}

3.dao层定义一页显示多少数据,及查询当页学生数据显示

int PAGE_SIZE = 5;//代表一页显示多少数据
List<Student> findStudentByPage(int currentPage) throws SQLException;

	/**
	 * 查询总的学生记录数
	 * @return
	 * @throws SQLException
	 */
	int findCount() throws SQLException;

4.dao层的实现:
//第一个问号代表返回多少记录,第二个问号代表前面跳过多少记录

List<Student> list = runner.query("select * from stu limit ? offset ?", 
						new BeanListHandler<Student>(Student.class),
						PAGE_SIZE,(currentPage-1)*PAGE_SIZE
						);
/* 
		查询总的记录数
	 */
	@Override
	public int findCount() throws SQLException {
		QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
		// ScalarHandler()用于处理 平均值,总的个数等
		Long query = (Long) runner.query("select count(*) from stu",
						new ScalarHandler()
						);
		//转为int型
		return query.intValue();
	}

5.service层:查询当页数据:返回domain层的pageBean

	/**
	 * @param 查询当页数据
	 * @return
	 * @throws SQLException
	 */
	PageBean findStudentByPage(int currentPage) throws SQLException;

6.实现service层

public PageBean findStudentByPage(int currentPage) throws SQLException {
		//封装分页的该页数据
		PageBean<Student> pageBean = new PageBean<Student>();

		pageBean.setCurrentPage(currentPage);//1.设置当前页
		int pageSize = StudentDaoImpl.PAGE_SIZE;
		pageBean.setPageSize(pageSize);//2.设置每页显示多少数据
		
		StudentDao dao = new StudentDaoImpl();
		List<Student> list = dao.findStudentByPage(currentPage);
		pageBean.setList(list);//3.设置该页的学生数据
		
		int count = dao.findCount();
		pageBean.setTotalSize(count);//4.设置总的记录数
		
		pageBean.setTotalPage(count%pageSize==0? count/pageSize : (count/pageSize)+1);//5.设置总页数
		
		return pageBean;
	}

7.创建第一步StudentListPageServlet.java里跳转的list_page.jsp页面【分页显示页面】

<body>
	<form action="SearchStudentServlet" method="post">
	    <table border="1" cellspacing="0">
	        <tr>
	            <td colspan="8">
			                按姓名查询:<input type="text" name="sname">
			                &nbsp; &nbsp; &nbsp;
			                按性别查询:<select name="gender" >
	                     <option value="">--请选择--
	                     <option value="男">男
	                     <option value="女">女
	                     </select>
	                       &nbsp; 
	              <input type="submit" value="查询"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
	              <a href="add.jsp">添加</a>
	            </td>
	        </tr>
	        <tr>
	            <td>编号</td>
	            <td>姓名</td>
	            <td>性别</td>
	            <td>电话</td>
	            <!-- <td>生日</td> -->
	            <td>爱好</td>
	            <td>简介</td>
	            <td>操作</td>
	        </tr>
	        <c:forEach items="${pageBean.list}" var="stu">
		        <tr>
		            <td>${stu.sid}</td>
		            <td>${stu.sname}</td>
		            <td>${stu.gender}</td>
		            <td>${stu.phone}</td>
		            <%-- <td>${stu.birthday}</td> --%>
		            <td>${stu.hobby}</td>
		            <td>${stu.info}</td>
		            <td><a href="EditServlet?sid=${stu.sid}">更新</a>  <a href="#" onclick="doDelete(${stu.sid})">删除</a></td>
		        </tr>
	        </c:forEach>
	       <td colspan="8">
	                   第${pageBean.currentPage }/${pageBean.totalPage }页&nbsp;&nbsp;&nbsp;&nbsp;
			           每页显示${pageBean.pageSize }  条      &nbsp;&nbsp;
			           总记录数${pageBean.totalSize } 条       &nbsp;&nbsp;
			    <c:if test="${pageBean.currentPage != 1 }">
				    <a href="StudentListPageServlet?currentPage=1">首页</a>
				    <a href="StudentListPageServlet?currentPage=${pageBean.currentPage-1}">上一页</a>  &nbsp;&nbsp;
			    </c:if>
			    <c:if test="${pageBean.currentPage == 1 }">
			       <a href="StudentListPageServlet?currentPage=1">首页</a> 
			                                                                                                                                     上一页 
			    </c:if>
			    |
			    <c:forEach begin="1" end="${pageBean.totalPage }" var="i">
			         <c:if test="${ pageBean.currentPage == i}">
			             ${i }
			         </c:if>
			         <c:if test="${ pageBean.currentPage != i}">
			             <a href="StudentListPageServlet?currentPage=${ i}">${i }</a>
			          </c:if>      
			    </c:forEach>
			    |
			    <c:if test="${pageBean.currentPage == pageBean.totalPage }">
                                                                                                                                                                                                                       下一页 
                   <a href="StudentListPageServlet?currentPage=${pageBean.totalPage}">尾页</a> &nbsp;&nbsp;
                </c:if>
			    <c:if test="${pageBean.currentPage != pageBean.totalPage }">
				     <a href="StudentListPageServlet?currentPage=${pageBean.currentPage+1 }">下一页</a>
	                 <a href="StudentListPageServlet?currentPage=${pageBean.totalPage}">尾页</a>
			    </c:if>
			     
	       </td>
	    </table>
	</form>
</body>

========================================
============================================================~~***

删除线============:这里为前期分析步骤=====

***~~

第二步:1.创建Servlet【控制层】以及Dao层实现,StudentListServlet.java

/**
 * @author Leonard
 * 控制层:【C】
 * 负责查询所有学生的信息,然后呈现到jsp页面上
 *
 */
public class StudentListServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}
}

2.创建Dao【数据访问层】,StudentDao.java
【注:提前创建一个Domain,即Student类

	private int id;
	private String name;
	private String gender;
	private String phone;
	private Date birthday;
	private String hobby;
	private String info;

生成set,get方法,默认空参构造

/**
 * @author Leonard
 * 	数据访问层【M】
 *	针对学生表的数据库操作
 */
public interface StudentDao {
	/**
	 * 查询所有学生,List里面放Student
	 * @return
	 */
	List<Student> findAll();
}

3.实现2中的Dao;

/**
 * @author Leonard
 *	StudentDao的实现,查询所有学生
 */
public class StudentDaoImpl implements StudentDao {

	@Override
	public List<Student> findAll() throws Exception {
		QueryRunner runner = new QueryRunner(JDBCUtil02.getDataSource());
		List<Student> list = runner.query("select * from stu", new BeanListHandler<Student>(Student.class));
		return list;
	}
}

第三步:Service层
好处:因为Dao层只针对单一的逻辑,数据操作层面;Service层是业务层面,一个业务包含多个单一的逻辑;
例如:分页
知道一页学生的集合-----Dao
1.创建业务逻辑层
StudentService.java

/**
 * @author Leonard
 *	学生业务处理规则
 */
public interface StudentService {
	List<Student> findAll() throws Exception;
}

2.实现:StudentServiceImpl.java

/**
 * @author Leonard
 *	学生的业务实现
 */
public class StudentServiceImpl implements StudentService {
	/*
	 *  Service里调Dao
	 */
	@Override
	public List<Student> findAll() throws Exception {
		StudentDao dao = new StudentDaoImpl();
		//返回查询的所有
		return dao.findAll();
	}
}

第四步:对第二步中的Servlet的代码,即StudentListServlet.java,进行完善

/**
 * @author Leonard
 * 控制层:【C】
 * 负责查询所有学生的信息,然后呈现到jsp页面上
 *
 */
public class StudentListServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//1.查询所有的学生
			StudentService service = new StudentServiceImpl();
			List<Student> list = service.findAll();
			//2.把Service层查到的数据存储到作用域中
			request.setAttribute("list", list);
			
			//3.跳转页面
			request.getRequestDispatcher("list.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

第五步:第四步中的跳转页面list.jsp

<body>
    <table border="1" cellspacing="0" align="center">
        <tr align="center">
            <td>编号</td>
            <td>姓名</td>
            <td>性别</td>
            <td>电话</td>
            <td>生日</td>
            <td>爱好</td>
            <td>简介</td>
            <td>操作</td>
        </tr>
        <c:forEach items="${list}" var="stu">
	        <tr>
	            <td>${stu.id}</td>
	            <td>${stu.name}</td>
	            <td>${stu.gender}</td>
	            <td>${stu.phone}</td>
	            <td>${stu.birthday}</td>
	            <td>${stu.hobby}</td>
	            <td>${stu.info}</td>
	            <td><a href="#">更新</a> <a href="#">删除</a></td>
	        </tr>
        </c:forEach>
    </table>
</body>

以上便实现了学生列表的查询操作
实现增加学生信息操作
第六步:在list.jsp新增添加按钮,实现向增加学生信息add.jsp页面跳转

<tr>
     <td colspan='8'><a href="add.jsp">添加</a></td>
</tr>

add.jsp页面

<body>
    <form action="addServlet" method="post">
	    <table border="1" cellspacing="0">
	        <tr>
	            <td>姓名</td>
	            <td><input type="text" name="name"/></td>
	        </tr>
	        <tr>
	            <td>性别</td>
	            <td>
	                <input type="radio" name="gender" value="男" checked="checked">男
	                <input type="radio" name="gender" value="女">女
	            </td>
	        </tr>
	         <tr>
	            <td>电话</td>
	            <td><input type="text" name="phone"/></td>
	        </tr>
	         <tr>
	            <td>生日</td>
	            <td><input type="text" name="birthday"/></td>
	        </tr>
	         <tr>
	            <td>爱好</td>
	            <td>
		            <input type="checkbox" name="hobby" value="游泳">游泳
		            <input type="checkbox" name="hobby" value="看书">看书
		            <input type="checkbox" name="hobby" value="写字">写字
		            <input type="checkbox" name="hobby" value="篮球">篮球
	            </td>
	        </tr>
	         <tr>
	            <td>简介</td>
	            <td><textarea rows="3" cols="20"  name="info"></textarea></td>
	        </tr>
	         <tr>
	            <td colspan="2"><button>添加</button></td>
	        </tr>
	    </table>
    </form>
</body>

第七步:添加学生的实现
创建Servlet,处理添加学生请求addServlet.java

/**
 * @author Leonard
 *	用于处理学生的添加请求
 */
public class addServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.处理中文问题
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;utf-8");
		//2.获取前台add.jsp提交的数据
		String name = request.getParameter("name");
		String gender = request.getParameter("gender");
		String phone = request.getParameter("phone");
		String birthday = request.getParameter("birthday");
		String hobby = request.getParameter("hobby");
		String info = request.getParameter("info");
		
		//3.获取的数据添加到数据库
		
		//4.跳转到列表页
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

第八步:Dao层与Dao层的实现
StudentDao.java

/**
	 * 添加学生
	 * @param student 需要添加到数据库
	 * @throws Exception
	 */
	void insert(Student student) throws Exception;

StudentDaoImpl.java

@Override
	public void insert(Student student) throws Exception {
		QueryRunner runner = new QueryRunner(JDBCUtil02.getDataSource());
		runner.update("insert into stu values(null,?,?,?,?,?,?)",
						student.getName(),
						student.getGender(),
						student.getPhone(),
						student.getBirthday(),
						student.getHobby(),
						student.getInfo());
	}

第九步:Service层与Service层的实现
Service层接口StudentService.java

void insert(Student student) throws Exception;//增加

Service层的实现StudentServiceImpl.java

@Override
	public void insert(Student student) throws Exception {
		StudentDao dao = new StudentDaoImpl();
		dao.insert(student);//直接调用Dao的insert方法
	}

第十步:Student类需要有参构造

/**
 * @author Leonard
 *	封装的学生对象Bean
 */
public class Student {
	private int id;
	private String name;
	private String gender;
	private String phone;
	private Date birthday;
	private String hobby;
	private String info;
	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 String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getHobby() {
		return hobby;
	}
	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	public String getInfo() {
		return info;
	}
	public void setInfo(String info) {
		this.info = info;
	}
	//不需要id
	public Student(String name, String gender, String phone, Date birthday,
					String hobby, String info) {
		super();
		this.name = name;
		this.gender = gender;
		this.phone = phone;
		this.birthday = birthday;
		this.hobby = hobby;
		this.info = info;
	}
	public Student() {
		super();
	}
}

第十一步:完善第七步的addServlet.java

在这里插入代码片

猜你喜欢

转载自blog.csdn.net/stack_xman/article/details/83895129
今日推荐