小案例——用MVC实现查询学生功能

目的:熟悉MVC架构,复习JDBC、连接池和dao

思路:MVC+jdbc(连接池)实现学生查询。

M:JavaBeans

V:JSP(用JSTL)

C:servlet

贴出部分代码

JavaBeans部分:StudentDao的实现类

StudentDaoImpl.java

package dao;

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

import util.DBUtil;

import entity.Student;

public class StudentDaoImpl implements StudentDao {

	@Override
	public List getAll() {
		List list = new ArrayList();
		
		Integer snum = null;
		String sname = null;
		Integer sgrade = null;
		Student stu = null;
	
		Connection con = null;
		try {			
			con = DBUtil.getConnection();
			
			String sql = "select * from student";
			
			PreparedStatement ps = con.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			
			while(rs.next()) {
				stu = new Student();
				snum = rs.getInt("snum");
				sname = rs.getString("sname");
				sgrade = rs.getInt("sgrade");
				stu.setSnum(snum);
				stu.setSname(sname);
				stu.setSgrade(sgrade);
				
				list.add(stu);
			}
		} catch (SQLException e) {
			throw new RuntimeException("查询学生失败");
		} finally {
			DBUtil.close(con);
		}
	System.out.println("查询成功");
		
		return list;
	}

}

JSP部分:

find_student.jsp

<%@page pageEncoding="utf-8"
	import="java.util.*,entity.*"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


	
		
		查询学生列表
	
	
		
			 	
学生学号 学生姓名 学生成绩
${student.snum } ${student.sname } ${student.sgrade }
servlet部分:

MainServlet.java

package web;

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 dao.CostDao;
import dao.CostDaoImpl;
import entity.Cost;

public class MainServlet extends HttpServlet {

	@Override
	protected void service(
			HttpServletRequest req, 
			HttpServletResponse res)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
	System.out.println(req.getRequestURI());
		if("/netctoss/findCost.do".equals(req.getRequestURI())) {
			CostDao dao = new CostDaoImpl();
			List list = dao.findAll();
			for(Cost c : list) {
				System.out.println(c.getName());
			}
				//设置属性并转发
			req.setAttribute("costs", list);
			System.out.println("转发成功");
			req.getRequestDispatcher("WEB-INF/cost/find.jsp").forward(req, res);
		}
	}

}



你可能感兴趣的:(java,小项目,jsp,mvc)