基于MVC结构

基于MVC结构的网站设计      

---------以一个简单的学生信息管理系统为例

1.首先从视图开始吧,即View;创建一个登录页面index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 'index.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
	<h2 align="center">欢迎登陆学生信息管理系统</h2><br>
   <form method="post" action="Comer">
   <center>
   <table width="300" border="1" align="center">
  	<tbody><tr>
	<td width="150" align="center">姓名:<br></td>
	<td><input type="text" name="adminName"></td></tr>
	<tr>
	<td align="center">密码:</td>
	<td><input type="password"  name="passWord"></td></tr>
	<tr>
	<td valign="top" colspan="2" align="center"><input type="submit" value="登录" name="ok"></td>
	</tr>
	</tbody>
   </table>
   <h3>${Mesg }</h3>
   </center>
   </form>
  </body>
</html>

 

2.创建学生信息显示页面list1.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ 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 'index.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">   
	 <style type="text/css">
       body,input,td{
       	font-size: 30px
       }
    	
    </style> 
  </head>
  
  <body style="font-size: 40px"><div align="center"><h3> 
    学生信息管理系统</h3>
    <a href="edit.jsp">添加学生信息</a>
    </div>

<table width="1000" border="1" height="52" align="center">
<tbody><tr>
<td width="100"> 学号</td>
<td width="150">姓名 <br></td>
<td width="70">性别 <br></td>
<td width="200">班级 <br></td>
<td width="300">家庭住址<br></td>
<td width="150">操作 <br></td>
<c:forEach items="${stuList}" var="stu">
<tr>
<td>${stu.id }</td>
<td>${stu.name }</td>
<td>${stu.sex }</td>
<td>${stu.className }</td>
<td>${stu.homeAdress }</td>
<td>
  <c:url value="Controller" var="url">
  	<c:param name="action">edit</c:param>
  	<c:param name="id">${stu.id }</c:param>
  </c:url>
  <a href="${url }">编辑 </a>
	|
	<c:url value="Controller" var="url">
  	<c:param name="action">delete</c:param>
  	<c:param name="id">${stu.id }</c:param>
  </c:url>
  <a href="${url }">删除</a> 
	</td>
</tr>
</c:forEach>
</tbody></table>
  </body>
</html>

 

3.创建一个学生信息添加\编辑页面edit.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ 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>
    
    <title>My JSP 'MyJsp.jsp' starting page</title>
    <style type="text/css">
       body,input,td,select{
       	font-size: 40px
       }
    	
    </style>


  </head>
  
  <body><h2 align="center"> 
    添加/编辑学生信息</h2><br>
    <form method="post" action="Controller?action=save&oldId=${stu.id}" name="add">
    <table width="800" border="1" align="center">
<tbody><tr>
<td width="150" align="center">学号:<br></td>
<td><input type="text" value="${stu.id}" name="id"></td></tr>
<tr>
<td align="center">姓名:</td>
<td><input type="text" value="${stu.name}" name="name"></td></tr>
<tr>
<td align="center">性别:<br></td>
<td>
	<select name="sex">
		<option value="男" ${stu.sex == "男"?"selected":"" }>男</option>
		<option value="女" ${stu.sex == "女"?"selected":"" }>女</option>
	</select>
</td>
</tr><tr>
<td valign="top" align="center">班级:<br></td>
<td valign="top"><input type="text" value="${stu.className}" name="className"></td></tr>
<td valign="top" align="center">家庭住址:<br></td>
<td valign="top"><input type="text" value="${stu.homeAdress}" name="homeAdress"></td></tr> 

<tr><td valign="top" colspan="2" align="center"><input type="submit" value="保存" name="ok"></td></tr>
</tbody></table>
</form>
  </body>
</html>

 

4.创建一个错误信息显示页面error.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 'error.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
 <style type="text/css">
       body,input,td{
       	font-size: 40px
       }
    	
    </style>
  </head>
  
  <body style="font-size: 40px">
    <h1 style="color:red;text-align: center">出错啦!!!</h1>
    <h3>${errMsg }</h3>
  </body>
</html>

 

5.视图部分创建完成,然后开始创建Model部分,主要是两个javabean,同属于包bean,用于进行数据的处理。第一个是Admin.java类,如下

package bean;

public class Admin {
	private String adminid;
	private String adminName;
	private String passWord;
	public String getAdminid(){
		return adminid;
	}
	public void setAdminid(String adminid) {
		this.adminid = adminid;
	}
	public String getAdminName() {
		return adminName;
	}
	public void setAdminName(String adminName) {
		this.adminName = adminName;
	}
	public String getPassWord() {
		return passWord;
	}
	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}
}

 

6.第二的javabean为Student.java,代码如下:

package bean;

public class Student {
	private String id;
	private String name;
	private String sex;
	private String className;
	private String homeAdress;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public String getHomeAdress(){
		return homeAdress;
	}
	public void setHomeAdress(String homeAdress){
		this.homeAdress=homeAdress;
	}
}

 

7至此,Model部分已经完成,现在进行Control部分的编制,这部分可分为两块,第一块是进行页面跳转处理的,第二块主要是进行数据库操作的,

首先是一个Comer.java类,包名为Controller,用于进行登录时的验证和跳转,代码如下:

package Controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

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

import process.DBUtil;

public class Comer extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	
	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");
		request.setCharacterEncoding("UTF-8");
		String name=request.getParameter("adminName");
		String passwd=request.getParameter("passWord");
		DBUtil db = new DBUtil();
		//System.out.println("hello");
		try {
			if(db.isAdmin(name, passwd))
				response.sendRedirect("Controller");
			else
			{
				
				response.sendRedirect("index.jsp");
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void init() throws ServletException {
		// Put your code here
	}
}

 

8.接下来是一个Controller.java类,包名同样为Controller,主要用于在学生信息处理模块部分控制页面跳转,代码如下:

package Controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

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

import bean.Student;

import process.DBUtil;

public class Controller extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public Controller() {
		super();
	}
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
	}
	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("UTF-8");
			String forword = "list1.jsp";
			String action = request.getParameter("action");
			DBUtil db = new DBUtil();			
			try {				
				if(action == null || "list1".equalsIgnoreCase(action) || "".equals(action)){
					ArrayList<Student> stuList = db.getAll();
					request.setAttribute("stuList", stuList);
				}
				else if("edit".equalsIgnoreCase(action)){
					String id = request.getParameter("id");
					Student stu = db.getOneById(id);
					request.setAttribute("stu", stu);
					forword = "edit.jsp";
				}
				else if("save".equalsIgnoreCase(action)){
					
					String id = request.getParameter("id");
					String name = request.getParameter("name");
					String sex = request.getParameter("sex");
					String className = request.getParameter("className");
					String oldId = request.getParameter("oldId");
					Student stu = new Student();
					stu.setClassName(className);
					stu.setId(id);
					stu.setName(name);
					stu.setSex(sex);
					db.save(oldId, stu);
					response.sendRedirect("Controller");
					return;
				}
				else if("delete".equalsIgnoreCase(action)){
					String id = request.getParameter("id");
					db.delete(id);
					response.sendRedirect("Controller");
					return;
				}
				else{
					request.setAttribute("errMsg", "请求操作不存在....");
					forword = "error.jsp";
				}
			} catch (ClassNotFoundException e) {
				request.setAttribute("errMsg", e.getMessage());
				forword = "error.jsp";
				e.printStackTrace();
			} catch (SQLException e) {
				request.setAttribute("errMsg", e.getMessage());
				forword = "error.jsp";
				e.printStackTrace();
			}
			request.getRequestDispatcher(forword).forward(request, response);
	}
	public void init() throws ServletException {
	}
}

 

9.Control部分中页面跳转部分完成后开始进行操作数据库部分代码的编制,DBUtil.java为类名,包名为process,代码如下:

package process;

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

import bean.*;


public class DBUtil {
	private static String ALLSQL = "select * from student";
	private static String ONESQL = "select * from student where id = '?'";
	private static String ADDSQL = "insert into student (homeAdress,name,sex,className,id) values(?,?,?,?,?)";
	private static String UPDATESQL = "update student set homeAdress=?,name=?,sex=?,className=?,id=? where id=?";
	private static String DELETESQL = "delete from student where id='?'";
	
	private static String FINDSQL = "select * from admin where adminName= '?'";
	
	private Connection con;
	private Statement stat;
	private PreparedStatement pstat;
	/**
	 * 获取数据库连接
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	private void getConnect() throws ClassNotFoundException, SQLException{
		Class.forName("com.mysql.jdbc.Driver");
		con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8","root",""); 
	}	
	
	/**
	 * 执行查询
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	private ResultSet exeQry(String sql) throws SQLException{
		stat = con.createStatement();
		ResultSet rs = stat.executeQuery(sql);
		return rs;
	}
	/**
	 * 关闭数据库连接等
	 * @param res
	 * @throws SQLException
	 */
	private void closeCon(ResultSet res) throws SQLException{
		if(res != null){
			res.close();
		}		
		if(stat != null){
			stat.close();
		}
		if(con != null){
			con.close();
		}
	}	
	/**
	 * 得到所有学生信息列表
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public ArrayList<Student> getAll() throws ClassNotFoundException, SQLException{
		ArrayList<Student> stuList = new ArrayList<Student>();
		if(con == null){
			getConnect();
		}
		ResultSet rs = exeQry(ALLSQL);
		while(rs.next()){
			Student stu = new Student();
			stu.setId(rs.getString("id"));
			stu.setName(rs.getString("name"));
			stu.setClassName(rs.getString("className"));
			stu.setSex(rs.getString("sex"));
			stu.setHomeAdress(rs.getString("homeAdress"));
			stuList.add(stu);
		}
		closeCon(rs);
		return stuList;
	}	
	public boolean isAdmin(String name,String password) throws ClassNotFoundException, SQLException
	{
		//Admin user = null;
		if(con == null){
			getConnect();
		}
		System.out.println(name);
		String sql=FINDSQL.replace("?", name);
		ResultSet rs=exeQry(sql);
		while(rs.next()){
			if(rs.getString("password").equals(password))
				return true;
		}
		return false;
	}
	/**
	 * 根据学号获得学生信息
	 * @param id
	 * @return 指定学生信息
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public Student getOneById(String id) throws ClassNotFoundException, SQLException{
		Student stu = null;
		if(con == null){
			getConnect();
		}
		String sql = ONESQL.replace("?", id);
		ResultSet rs = exeQry(sql);
		if(rs.next()){
			stu = new Student();
			stu.setId(rs.getString("id"));
			stu.setName(rs.getString("name"));
			stu.setClassName(rs.getString("className"));
			stu.setSex(rs.getString("sex"));
			stu.setHomeAdress(rs.getString("homeAdress"));
		}
		closeCon(rs);
		return stu;
	}
	
	/**
	 * 保存信息
	 * @param add 是否为新增
	 * @param stu 学生信息
	 * @throws SQLException
	 * @throws ClassNotFoundException 
	 */
	public void save(String oldId,Student stu) throws SQLException, ClassNotFoundException{
		if(con == null){
			getConnect();
		}
		if(oldId == ""){
			pstat = con.prepareStatement(ADDSQL);
		}
		else{
			pstat = con.prepareStatement(UPDATESQL);
			pstat.setString(6, oldId);
		}
		pstat.setString(1, stu.getHomeAdress());
		pstat.setString(2, stu.getName());
		pstat.setString(3, stu.getSex());
		pstat.setString(4, stu.getClassName());
		pstat.setString(5, stu.getId());
		pstat.executeUpdate();
	}
	
	public void delete(String id) throws ClassNotFoundException, SQLException{
		if(con == null){
			getConnect();
		}
		String sql = DELETESQL.replace("?", id);
		stat = con.createStatement();
		stat.executeUpdate(sql);
	}
}

 

 代码的编制部分已经完成了,下面要完成的工作是在数据库中建立两张表:admin和student,其中admin表中的字段为:adminid、adminName、passWord,student表中的字段为:id、name、sex、className、homeAdress。

接下来的工作是将连接数据库的驱动复制到WebRoot->web-inf->lib下,最终的目录结构如下:

在浏览器中输入http://localhost:8080/Student/index.jsp进入登录界面;

最后效果如下:

登陆界面:

学生信息显示界面:

学生信息编辑\添加页面:

至此,通过建立这个简单的学生信息管理系统大体上对于MVC结构有了一定的认识,这个例子不太完善的地方个人认为有二,其一是登录页面

中如果登录失败没有提示,其二是应该运用过滤器将其中的学生信息显示和编辑两个页面保护起来以防止非法访问,有不清楚的地方原谅我的

语言表达能力吧,这尼玛是第二遍发帖,第一遍手抖了,结果没保存丢失了,实在恼火,结果郁闷的又重新敲了一遍,伤不起啊。

 

 

posted @ 2013-06-02 14:43  再见,少年  Views(737)  Comments(0Edit  收藏  举报