使用mvc模式开发网站

看了韩顺平的j2ee的视频后,吧里面教的做了出来,感觉好极了,新手上路!!!

这个肯定不是原创,但是也不是转载,那我就姑且把它作为翻译吧,给其他看视频学习但是没有代码的同学一点福利吧

首先是login.jsp的登陆界面代码。

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
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 'login.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 bgcolor="pink"> 
  <center>
   	用户登录 <br>
   	<hr>
<!--   	<form action="loginCl.jsp" method="post">	 -->
	<form action="LoginClServlet" method="post">
   	用户名: <input type="text" name="username"><br>
   	 密  码: <input type="password" name="passwd"><br>
   	 <input type="submit" value="登录">
   	 <input type="reset" value="重置">
   	</form>
   </center>
  </body>
</html>

然后就是欢迎界面的代码,wel.jsp

<%@ page language="java" import="java.util.*,java.sql.*,com.xf.model.*" pageEncoding="gb2312"%>
<%
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 'wel.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>
    登录成功!!!恭喜发财!!!<%=request.getParameter("user") %><br>
    <a href="login.jsp">返回重新登录</a>
<hr>
<h1>用户信息列表</h1>
<%
/*
	//定义四个变量
	int pageNow=1;	//默认从第一页开始

	int pageSize=3;		//一共的页数
	int rowCount=0;			//这个从数据库查询
	int pageCount=0;	//通过rowCount和pageSize求得

	
	String s_pageNow=request.getParameter("pageNow");

	
	if(s_pageNow != null)
	{
		//从超链接处得到值
		pageNow=Integer.parseInt(s_pageNow);
	}


	//1.加载驱动
	Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
	//2.得到链接
	Connection ct=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=spdb1","sa","");
	//3.创建statement
	Statement sm=ct.createStatement();
	//4.到数据库中查询
	ResultSet rs=sm.executeQuery("select count(*) from users");
	//5.对查询结果进行判断

	//这里注意一定要next,不然GG思密达
	if(rs.next())
	{
		rowCount=rs.getInt(1);
	}
	
	//计算pageCount,算法很多
	if(rowCount%pageSize == 0)
	{
		pageCount=rowCount/pageSize;
	}
	else
	{
		pageCount=rowCount/pageSize+1;
	}
	
	//查出要显示出来的记录
	rs=sm.executeQuery("select top "+pageSize+" * from users where userId not in (select top "
	+pageSize*(pageNow-1)+" userId from users)");
	
*/

	//调用UserBeanCl的方法(创建一个UserBeanCl的实例然后调用他的方法),完成分页显示
//	UserBeanCl ubc=new UserBeanCl();
//	ArrayList a1=ubc.getUsersByPage(pageNow);
	//要显示的用户信息从request中取
	ArrayList a1=(ArrayList)request.getAttribute("result");
	
	
	//显示出来
	%>
	<table border="1">
	<tr><td>用户id</td><td>用户名字</td><td>密码</td><td>电子邮件</td><td>用户级别</td></tr>
	<%
		//while(rs.next())
		for(int i=0 ; i<a1.size() ; ++i)
		{
		//重arraylist中取出UserBean
		UserBean ub=(UserBean)a1.get(i);
			%>
			<tr><td><%=ub.getUserId() %></td><td><%=ub.getUsername() %></td><td><%=ub.getPasswd() %></td><td><%=ub.getEmail() %></td><td><%=ub.getGrade() %></td></tr>
			<%
		}	
	 %>
	</table>
	<%
	
	//首页
	out.println("<a href=UserClServlet?pageNow="+1+">[首页]</a>");
	
	//String s_pageNow=(String)request.getAttribute("pageNow");
	int pageNow=Integer.parseInt((String)request.getAttribute("pageNow"));
	//上一页
	if(pageNow != 1)
	{
		out.println("<a href=UserClServlet?pageNow="+(pageNow-1)+">[上一页]</a>");
	}
	
	//得到pageCount
//	int pageCount=ubc.getPageCount();
	String s_pageCount=(String)request.getAttribute("pageCount");
	int pageCount=Integer.parseInt(s_pageCount);
	
	//显示超链接
	for(int i=1 ; i<=pageCount ; ++i)
	{
		out.println("<a href=UserClServlet?pageNow="+i+">["+i+"]</a>");
	}
	
	//下一页
	if(pageNow != pageCount)
	{
		out.println("<a href=UserClServlet?pageNow="+(pageNow+1)+">[下一页]</a>");
	}
	
	//尾页
	out.println("<a href=UserClServlet?pageNow="+pageCount+">[尾页]</a>");
	
%>
  </body>
</html>

然后就是Servlet文件的控制器,LoginClServlet.java这个是处理从login.jsp来的账号密码

/**
 * 功能:这是一个控制器,完成对用户身份的验证,本身是不会去完成业务逻辑的
 * 		它主要是去调用model完成对数据的处理
 * 时间:2014年6月5日12:56:46
 * 作者:cutter_point
 */
package com.xf.controller;

import com.xf.model.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

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

public class LoginClServlet extends HttpServlet
{

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		//得到账号密码
		String u=request.getParameter("username");	//账号
		String p=request.getParameter("passwd");	//密码
		
		//调用模型对他进行验证
		UserBeanCl ubc=new UserBeanCl();
		
		if(ubc.checkUser(u, p))
		{
			System.out.println("这是使用的Servlet完成验证!!");
			//合法
			//跳转
			//response.sendRedirect("wel.jsp");
			//在进入wel.jsp之前把数据都准备好
			//首先显示的是默认的第一页
			ArrayList al=ubc.getUsersByPage(1);
			int pageCount=ubc.getPageCount();
			request.setAttribute("result", al);
			request.setAttribute("pageCount", pageCount+"");
			request.setAttribute("pageNow", "1");
			
			//但是上面方法效率不高,高效率的是
			request.getRequestDispatcher("wel.jsp?user="+u).forward(request, response);
			

		}
		else
		{
			//不合法
		//	response.sendRedirect("login.jsp");
			
			//理由同上
			request.getRequestDispatcher("login.jsp").forward(request, response);
			
		}
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		this.doGet(request, response);
	}

}

然后就是另外一个控制器了,就是登陆进去后,分页跳转的部分UserClServlet.java

/**
 * 功能:这个控制器将处理用户的分页显示,用户的删除修改查询,添加
 * 时间:2014年6月5日13:47:03
 * 作者:cutter_point
 */
package com.xf.controller;

import com.xf.model.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

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

public class UserClServlet extends HttpServlet
{

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{

		//得到用户希望显示的pageNow
		String s_pageNow=request.getParameter("pageNow");
		//使用UserBeanCl的方法调用得到pageNow
		try
		{
			int pageNow=Integer.parseInt(s_pageNow);
			//调用UserBeanCl
			UserBeanCl ubc=new UserBeanCl();
			//在进入wel.jsp之前把数据都准备好
			ArrayList al=ubc.getUsersByPage(pageNow);
			int pageCount=ubc.getPageCount();
			request.setAttribute("result", al);
			request.setAttribute("pageCount", pageCount+"");
			request.setAttribute("pageNow", pageNow+"");
		//	request.setAttribute("pageNow", pageNow); 不行必须在后面加引号,不然没法用,因为别人
			//默认吧pageNow看成string了,结果传过去了,以为是String类型,实际是int类型,结果就出错了
			
			System.out.println("分页是使用了UserClServlet!!");
			
			//从新跳转回wel.jsp里面去
			request.getRequestDispatcher("wel.jsp").forward(request, response);
		} 
		catch (Exception e)
		{
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{

		this.doGet(request, response);
	}

}

然后就是三个跟数据库连接的模型文件了,就是用来被上面几个调用的!!

分别是:UserBean.java,UserBeanCl.java,ConnDB.java

/**
 * 功能:这是一个javabean,对应users表,代表数据
 * 时间:2014年6月4日10:39:33
 * 作者:cutter_point 
 */

package com.xf.model;

public class UserBean
{
	private int userId;
	private String username;
	private String passwd;
	private String email;
	private int grade;
	public int getUserId()
	{
		return userId;
	}
	public void setUserId(int userId)
	{
		this.userId = userId;
	}
	public String getUsername()
	{
		return username;
	}
	public void setUsername(String username)
	{
		this.username = username;
	}
	public String getPasswd()
	{
		return passwd;
	}
	public void setPasswd(String passwd)
	{
		this.passwd = passwd;
	}
	public String getEmail()
	{
		return email;
	}
	public void setEmail(String email)
	{
		this.email = email;
	}
	public int getGrade()
	{
		return grade;
	}
	public void setGrade(int grade)
	{
		this.grade = grade;
	}
	
	
}

/**
 * 功能:这是一个处理类,也叫做bo,主要封装对users表的各种操作
 * 		每一个UserBean对象放到ArrayList里面去,更早关闭和数据库链接
 * 时间:2014年6月4日10:43:48
 * 作者:cutter_point
 */
package com.xf.model;

import java.sql.*;
import java.util.*;

public class UserBeanCl
{
	private Statement sm=null;
	private ResultSet rs=null;
	private Connection ct=null;
	private int pageSize=3;	//默认从第一页开始
	private int rowCount=0;			//这个从数据库查询
	private int pageCount=0;	//通过rowCount和pageSize求得
	
	public void close()
	{
		try
		{
			if(rs != null)
			{
				rs.close();
				rs=null;
			}
			if(sm != null)
			{
				sm.close();
				sm=null;
			}
			if(ct != null)
			{
				ct.close();
				ct=null;
			}
		} 
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	//得到pageCount,页数总计
	public int getPageCount()
	{
		try
		{
			//得到链接
			ct=new ConnDB().getConn();
			//声明,创建一个sm
			sm=ct.createStatement();
			
			//4.到数据库中查询
			ResultSet rs=sm.executeQuery("select count(*) from users");
			
			//这里注意一定要next,不然GG思密达
			if(rs.next())
			{
				rowCount=rs.getInt(1);
			}				
			
			//计算pageCount的结果
			if(rowCount%pageSize == 0)
			{
				pageCount=rowCount/pageSize;
			}
			else
			{
				pageCount=rowCount/pageSize+1;
			}
		} 
		catch (Exception e)
		{
			// TODO: handle exception
			e.printStackTrace();
		}
		finally
		{
			this.close();
		}
		return pageCount;
	}
	
	//得到用户需要显示地信息(分页)
	public ArrayList getUsersByPage(int pageNow)
	{
		ArrayList a1=new ArrayList();
		
		try
		{
			//得到链接
			ct=new ConnDB().getConn();
			//创建statement
			sm=ct.createStatement();
			
			//查询出需要显示地信息
			rs=sm.executeQuery("select top "+pageSize+" * from users where userId not in (select top "
					+pageSize*(pageNow-1)+" userId from users)");
			
			//吧得到的信息存放到ArrayList上面去
			while(rs.next())
			{
				UserBean ub=new UserBean();
				
				ub.setUserId(rs.getInt(1));
				ub.setUsername(rs.getString(2));
				ub.setPasswd(rs.getString(3));
				ub.setEmail(rs.getString(4));
				ub.setGrade(rs.getInt(5));
				
				//将ub放到arraylist里面去
				a1.add(ub);
			}
			
		} 
		catch (Exception e)
		{
			e.printStackTrace();
			// TODO: handle exception
		}
		finally
		{
			//关闭资源
			this.close();
		}
		
		return a1;
	}

	//检查账号密码是否正确
	public boolean checkUser(String u, String p)
	{
		boolean b=false;
		
		try
		{
			//到数据库中去验证
			ct=new ConnDB().getConn();
			//3、创建statement
			sm=ct.createStatement();
			//4、进行查询,把查询第一个结果放到rs中
			rs=sm.executeQuery("select passwd from users where username='"+u+"'");
			//根据结果来判断是否是要寻找的数据
			if(rs.next())
			{
				//用户名存在,验证密码
				if(rs.getString(1).equals(p))
				{
					b=true;
				}
			}
			
		} 
		catch (Exception e)
		{
			e.printStackTrace();
			// TODO: handle exception
		}
		finally
		{
			this.close();
		}
		
		return b;
	}
}

/**
 * 功能:得到数据库的链接
 * 时间:2014年6月4日10:47:57
 * 作者:cutter_point
 */
package com.xf.model;

import java.sql.*;

public class ConnDB
{
	private Connection ct=null;
	
	public Connection getConn()
	{
		try
		{
			//1、加载驱动
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			//2、得到链接
			ct=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=spdb1","sa","");
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return ct;
	}
}


PS:不断努力,默默学习!!!





使用mvc模式开发网站,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。