您现在的位置: 365建站网 > 365文章 > 实现MVC模式的CRUD实例(一般的教材上看不到)

实现MVC模式的CRUD实例(一般的教材上看不到)

文章来源:365jz.com     点击数:445    更新时间:2009-09-19 10:31   参与评论

实例包括如下文件:

M部分:Student.java,包含了数据库访问代码,能够表示学生信息,封装了对学生操作的基本方法。

C部分:StudentServlet.java,完成增删改查的控制。

V部分:studentlist.jsp和edituser.jsp,前者显示学生列表,以及添加、删除、修改的入口,后者用于添加和修改。

配置文件:web.xml

下面分别给出相关文件。

----------------------------------------Student.java-----------------------------------------------------------

 package javabean;

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

public class Student {
 
 private Connection con;
 
 private Statement stmt;
 
 private ResultSet rs;
 
 private String sid;
 private String sname;
 private String sage;
 
 /*
  * 获取所有学生信息
  */
 public List getAllStudents(){
  List list = new ArrayList();
  String sql = "select * from student";
  try{
   rs = executeQuery(sql);
   while(rs.next()){
    Student temp = new Student();
    temp.setSid(rs.getString(1));
    temp.setSname(rs.getString(2));
    temp.setSage(rs.getString(3));
    list.add(temp);
   }
  }catch(Exception e){
   System.out.println(e.toString());
  }finally{
   close();
  }
  return list;
 }
 
 /*
  * 添加学生
  */
 public void add(Student stu){
  String sql = "insert into student values('"+stu.getSid()+"','"+stu.getSname()+"',"+stu.getSage()+")";
  try{
   executeUpdate(sql);
  }catch(Exception e){
   System.out.println(e.toString());
  }finally{
   close();
  }
 }
 
 /*
  * 删除学生
  */
 public void delete(String sid){
  String sql = "delete from student where sid='"+sid+"'";
  try{
   executeUpdate(sql);
  }catch(Exception e){
   System.out.println(e.toString());
  }finally{
   close();
  }
 }
 
 /*
  * 修改学生
  */
 public void edit(Student stu){
  String sql = "update student set sname='"+stu.getSname()+"',sage="+stu.getSage()+" where sid='"+stu.getSid()+"'";
  try{
   int n = executeUpdate(sql);
   System.out.println("--------------"+n);
  }catch(Exception e){
   System.out.println(e.toString());
  }finally{
   close();
  }
 }
 
 /*
  * 根据学号查询学生
  */
 public Student findStudentById(String sid){
  String sql = "select * from student where sid='"+sid+"'";
  try{
   rs = executeQuery(sql);
   if(rs.next()){
    Student temp = new Student();
    temp.setSid(rs.getString(1));
    temp.setSname(rs.getString(2));
    temp.setSage(rs.getString(3));
    return temp;
   }
  }catch(Exception e){
   System.out.println(e.toString());
  }finally{
   close();
  }
  return null;
 }
 
 /*
  * 执行更新等操作
  */
 public int executeUpdate(String sql)throws SQLException,ClassNotFoundException{
  return getStatement().executeUpdate(sql);
 }
 
 /*
  * 关闭对象
  */
 public void close(){
  if(rs!=null)
   try{rs.close();}catch(Exception e){}
  if(stmt!=null)
   try{stmt.close();}catch(Exception e){}
  if(con!=null)
   try{con.close();}catch(Exception e){}
 }
 
 /*
  * 执行有结果集返回的查询
  */
 public ResultSet executeQuery(String sql) throws SQLException,ClassNotFoundException{
  return getStatement().executeQuery(sql);
 }
 
 /*
  * 获取语句对象
  */
 public Statement getStatement() throws SQLException,ClassNotFoundException{
  if(stmt==null){
   stmt = getConnection().createStatement();
  }
  return stmt;
 }
 
 /*
  * 获取连接
  */
 public Connection getConnection() throws SQLException,ClassNotFoundException{
  if(con==null){
   Class.forName("oracle.jdbc.driver.OracleDriver");
   con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.102.206:1521:orcl","training","123456");
  }
  return con;
 }

 public String getSid() {
  return sid;
 }

 public void setSid(String sid) {
  this.sid = sid;
 }

 public String getSname() {
  return sname;
 }

 public void setSname(String sname) {
  this.sname = sname;
 }

 public String getSage() {
  return sage;
 }

 public void setSage(String sage) {
  this.sage = sage;
 }
 
 public static void main(String[] args){
  Student student = new Student();
 }
}

----------------------------------------StudentServlet.java----------------- --------------------------------

package servlet;

import java.io.IOException;
import java.util.List;

import javabean.Student;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StudentServlet extends HttpServlet {

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

  doPost(request,response);
 }


 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setCharacterEncoding("gb2312");
  String sid = request.getParameter("sid");
  String sname = request.getParameter("sname");
  String sage = request.getParameter("sage");
  String action =  request.getParameter("action");
  
  // 调用业务方法
  Student student = new Student();
  if(action.equals("list")){ // 显示列表
   List list = student.getAllStudents();
   request.setAttribute("studentlist",list);
  }else if(action.equals("add")){ //添加
   Student info = new Student();
   info.setSid(sid);
   info.setSname(sname);
   info.setSage(sage);
   student.add(info);
  }else if(action.equals("edit")){ // 修改
   Student info = new Student();
   info.setSid(sid);
   info.setSname(sname);
   info.setSage(sage);
   student.edit(info);
  }else if(action.equals("findedit")){ // 修改之前的查询
   Student info = student.findStudentById(sid);
   request.setAttribute("student",info);
  }else if(action.equals("delete")){ // 删除学生
   student.delete(sid);
  }else if(action.equals("findadd")){
   
  }
  
  String forward;
  if(action.equals("findedit")){
   request.setAttribute("type","edit"); // 在界面上用于判断是添加界面还是修改界面
   forward = "edituser.jsp";
  }else if(action.equals("findadd")){
   request.setAttribute("type","add"); // 在界面上用于判断是添加界面还是修改界面
   forward = "edituser.jsp";
  }else if(action.equals("list")){
   forward = "studentlist.jsp";
  }else{
   forward = "student?action=list";
  }
  
  RequestDispatcher rd = request.getRequestDispatcher(forward);
  rd.forward(request,response);
 }

}

----------------------------------------studentlist.jsp---------------------------------------------------------

<%@ page contentType="text/html;charset=gb2312"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
  <head>
     <title>所有学生信息</title>
  </head>
  <body>
     <h1>学生列表</h1>
     <table>
        <tr>
           <td>学号</td><td>姓名</td><td>年龄</td>
        </tr>
        <c:forEach var="student" items="${studentlist}">
            <tr>
               <td>${student.sid}</td>
               <td>${student.sname}</td>
               <td>${student.sage}</td>
               <td><a href="student?action=delete&sid=${student.sid}">删除</a></td>
               <td><a href="student?action=findedit&sid=${student.sid}">修改</a></td>
            </tr>
        </c:forEach>
     </table>
     <a href="student?action=findadd">添加学生</a>
  </body>
</html>

----------------------------------------edituser.jsp -----------------------------------------------------------

 <%@ page language="java" pageEncoding="gb2312" contentType="text/html;charset=gb2312"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%
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 'edituser.jsp' starting page</title>
  </head>
 
  <body>
    <h2> <c:if test="${type==\"add\"}"> 添加学生</c:if> <c:if test="${type==\"edit\"}">  修改学生</c:if> </h2>
    <form action="student?action=${type}" method="post">
    <table>
       <tr>
          <td>学号</td>

             <td>

               <c:if test="${ empty student }"> <input type="text" name="sid"></c:if>

               <c:if test="${! empty student }"> <input type="hidden" name="sid" value="${student.sid}">${student.sid} </c:if>  

            </td>
       </tr>
       <tr>
          <td>姓名</td><td><input type="text" name="sname" <c:if test="${! empty student }"> value="${student.sname}" </c:if> ></td>
       </tr>
       <tr>
          <td>年龄</td><td><input type="text" name="sage" <c:if test="${! empty student }"> value="${student.sage}" </c:if>></td>
       </tr>
       <tr>
          <td><input type="submit" value="确定"></td><td><input type="reset" value="重置"></td>
       </tr>
    </table>
    </form>
  </body>
</html>

----------------------------------------web.xml-----------------------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <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>StudentServlet</servlet-name>
    <servlet-class>servlet.StudentServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>StudentServlet</servlet-name>
    <url-pattern>/student</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


该实例需要添加的内容:
1、增加验证部分。
2、增加异常处理部分。
3、增加日志部分。
4、增加国际化部分。
5、增加分页功能。
6、增加灵活的查询功能。

如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (445人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号