skyxuyan的专栏

从明天起 做一个编程的人 编程、测试、制作网页 从明天起 关心 J2EE 和 Android 我有一个电脑 面朝代码 春暖花开!!...

J2EE学习笔记——MVC模式的用户管理系统(一)



 

首先是登录界面:

<%@ 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> JSP </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>
   <form action="LoginCLServlet" >
  用户名:<input type="text" name="username">
   
     <br>
      密  码:<input type="text" name="password">
   
     <br>
     <input type="submit" value=确定>
   
     <br>
     </form>
  </body>
</html>


其中 <form action="LoginCLServlet" >    要跳转到   LoginCLServlet 

LoginCLServlet  代码:

package xuyan.control;

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

import xuyan.model.*;

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("password");
		  UserBeanCL  ub=new UserBeanCL();
		  
		if(  ub.checkUser(u, p))
		{
			ArrayList al=ub.getUserByPage(1);
			int pageCount=ub.getpageCount();
			
			request.setAttribute("result", al);
			request.setAttribute("pageCount", pageCount+"");
			
			
			
			request.getRequestDispatcher("Main.jsp").forward(request, response);
		}
		
		else
		{
			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);
	}

}


 

调用M     ,有三个Model    分别为  ConnDB.java       UsrBean.java     UserBeanCL.java

ConnDB.java:

//数据库连接
package xuyan.model;
import  java.sql.*;

public class ConnDB {
      private Connection ct=null;
      public  Connection getConn()
      {
    	  
    	  try {
    		  
    		  Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//加载驱动
    		  
    	      ct=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=StudentInfo","sa","1234");
    	       
    	         
    		  
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return ct;
      }
      
}


 

UserBean.java

 

//这是一个javabean  ,对应user表  ,代表数据

package xuyan.model;

public class UserBean {

	private int ID;
	public int getID() {
		return ID;
	}
	public void setID(int iD) {
		ID = iD;
	}
	public String getStudentname() {
		return studentname;
	}
	public void setStudentname(String studentname) {
		this.studentname = studentname;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getGrade() {
		return grade;
	}
	public void setGrade(String grade) {
		this.grade = grade;
	}
	private String studentname;
	private String gender;
	private String age;
	private String grade;
	
	
}


 

UserBeanCL.java

//这是一个处理类    ,bo  buyinessobject,  封装对user表的各种操作    增删改查


package xuyan.model;
import  java.util.*;
import  java.sql.*;

public class UserBeanCL {
	
	private Connection  con=null;
	
	private Statement   sm=null;
	private ResultSet   rs=null;
	
	int pageSize=3;
	int rowCount=0;
	int pageCount=0;
	
	//关闭资源
	
	public void closeConn(){
		
		try {
			if(rs!=null)
			{
				rs.close();
				rs=null;
			}
			if(sm!=null)
			{
				sm.close();
				sm=null;
			}
			if(con!=null)
			{
				con.close();
				con=null;
				
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	
	
	//删除用户
	
	public boolean DeleteUsers( String userID){
		
		boolean flag=false;
		
		
		try {
			
			
           con=new ConnDB().getConn();
			
			sm=con.createStatement();

	       int  a=sm.executeUpdate("delete from student where ID='"+userID+"'");
	      
	      if(a==1)
	      {
	    	  flag=true;
	      }
	      
	     
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		finally
		{
			closeConn();
		}
		return flag;
	}
	
	
	//添加用户
	
	
	public  boolean AddUser(String username,String sex,String age,String grade)
	{
       boolean flag=false;
		
		
		try {
			
			
           con=new ConnDB().getConn();
			
			sm=con.createStatement();

	       int  a=sm.executeUpdate("insert into student (studentname,gender,age,grade) values('"+username+"','"+sex+"','"+age+"','"+grade+"')");
	      
	      if(a==1)
	      {
	    	  flag=true;
	      }
	      
	     
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		finally
		{
			closeConn();
		}
		return flag;
		
	}
	
	//返回总页数
	
	public int  getpageCount()
	{
		
		try {
			
			con=new ConnDB().getConn();
			
			sm=con.createStatement();
	         
	          
	        
	         rs=sm.executeQuery("select  count(*) from student");//查询共有多少记录
	    	     
	        
	        if(rs.next())  //此处说明有记录
	    		
	    		{
	    			rowCount=rs.getInt(1);
	    			
	    			if(rowCount%pageSize==0)
	    			{
	    					pageCount=rowCount/pageSize;
	    			}
	    			
	    			else  
	    			{
	    					pageCount=rowCount/pageSize+1;  //int类型  会转化为整数
	    			}
	    			
	    			
	    	}
			
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		finally
		{
			closeConn();
		}
		
		return pageCount;
		
	}
	
	
	//显示用户信息(分页)
	public ArrayList getUserByPage(int pageNow)
	{
		
		ArrayList al=new ArrayList();
		
		
		try {
			
			con=new ConnDB().getConn();
			
			sm=con.createStatement();
			 
	        rs=sm.executeQuery("select top "+pageSize+"*  from student  where ID not in(select top "+pageSize*(pageNow-1)+" ID from student)");
	    	
	        
	        //开始封装   将  rs 封装到 Arraylist里
	        
	        while(rs.next())
	        {
	        	UserBean ub=new UserBean();
	        	ub.setID(rs.getInt(1));
	        	ub.setStudentname(rs.getString(2));
	        	ub.setGender(rs.getString(3));
	        	ub.setAge(rs.getString(4));
	        	ub.setGrade(rs.getString(5));
	        	//将UB放入到 arraylist
	        	al.add(ub);
	        }
	        
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		finally
		{
			closeConn();
		}
		return al;
		
		
	}
	
	
	//验证用户书否存在
	public boolean checkUser(String u,String p)
	{
		boolean b=false;
		try {
			   
		
		    	con=new ConnDB().getConn();
		         
		         sm=con.createStatement();
		        rs=  sm.executeQuery("select userpswd from userinfo where username='"+u+"'  ");
		         
		         if(rs.next())
		         {
		                 if(rs.getString(1).equals(p))
		                 {
		                 
		                
		                 b=true;
		                 
		                 }
		                 
		                
		         }
		        

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		finally
		{
			//关闭资源
			closeConn();
			
		}
		return b;
	}

}


 

用户名  和密码正确后跳转到   Welcome.jsp  页面

 

 

<%@ page language="java" import="java.util.*,java.sql.*,xuyan.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 'Welcome.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>
   <% 
   
       int pageNow=1; 
       String s_pageNow=request.getParameter("s_pageNow");
       if(s_pageNow!=null)
       {
          pageNow=Integer.parseInt(s_pageNow);
       }
       
      // UserBeanCL ubc=new UserBeanCL();
       
       
       //ArrayList al=ubc.getUserByPage(pageNow);
       
       ArrayList al=(ArrayList)request.getAttribute("result");
   
  %>
  
      <table  border="1">
      <tr><th>ID</th><th>NAME</th><th>SEX</th><th>AGE</th><th>GRADE</th><th>删除</th><th>插入</th></tr>
      <%
      
      for(int i=0;i<al.size();i++){
      //从al中取出userbean
        UserBean ub=(UserBean)al.get(i);
       %>
      <tr>
      <td>
      <%=ub.getID() %>
     
      </td>
       <td>
      <%=ub.getStudentname() %>
      
      </td>
       <td>
      <%=ub.getGender() %>
      
      </td>
       <td>
      <%=ub.getAge() %>
      
      </td>
       <td>
      <%=ub.getGrade() %>
      
      </td>
      
       <td>
     <a href=UserCLServlet?flag=deleteuser&userid=<%=ub.getID() %>>删除记录</a>
      
      </td>
      
       <td>
     <a href=InsertNews.jsp>插入</a>
      
      </td>
      <%
      
      }
       %>
      
      
      </tr>
      
      
      
      
      </table>
      
      
      <%
      
         String s_pagecount=(String)request.getAttribute("pageCount");
         int pageCount=Integer.parseInt(s_pagecount);
      
      
       %>
  
   <br/>
  共用记录条数:<%=pageCount %>
  <br/>
  
  当前页数为      :<%=pageNow %>
  
  
   <br/>
 
 <%  for(int i=1;i<=pageCount;i++)
     
     out.println("<a href=UserCLServlet?flag=fenye&s_pageNow="+i+">"+i+"</a>");
     
     
    
     
       if((pageNow-1)!=0)
       {
       
     out.println("<a href=UserCLServlet?flag=fenye&s_pageNow="+(pageNow-1)+">上一页</a>");
     
     }
     
     if((pageNow+1)<=pageCount)
     {
      out.println("<a href=UserCLServlet?flag=fenye&s_pageNow="+(pageNow+1)+"> 下一页</a>");
     
     }
     
     
      %>
 
 
  
  
 
  
  
  </body>
</html>

 

UserCLServlet   这个servlet 负责处理登陆后数据显示     增删改查

 

UserCLServlet.java

 

package xuyan.control;

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

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 {
		
		String getflag=request.getParameter("flag");
		
		
		if(getflag.equals("fenye"))
	{

		try {
			int pageNow=Integer.parseInt(request.getParameter("s_pageNow"));
			
			 UserBeanCL  ub=new UserBeanCL();
			  
			  ArrayList al=ub.getUserByPage(pageNow);
			  int pageCount=ub.getpageCount();
			  
			  request.setAttribute("result", al);
			 request.setAttribute("pageCount", pageCount+"");
			
			request.getRequestDispatcher("Welcome.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}	
		 //
		//
		else if(getflag.equals("deleteuser"))
		{
			
			String id=request.getParameter("userid");
			
			
			UserBeanCL  ub=new UserBeanCL();
			
			if(ub.DeleteUsers(id))
			
			{
				request.getRequestDispatcher("Success.jsp").forward(request, response);
				
			}
			
			else
			{
				request.getRequestDispatcher("New.jsp").forward(request, response);
				
			}
		}
		
		else if(getflag.equals("adduser"))
		{
              String username=request.getParameter("username");
              String sex=request.getParameter("sex");
              String age=request.getParameter("age");
              String grade=request.getParameter("grade");
  			
			
			UserBeanCL  ub=new UserBeanCL();
			
			if(ub.AddUser(username, sex, age, grade))
			
			{
				request.getRequestDispatcher("Success.jsp").forward(request, response);
				
			}
			
			else
			{
				request.getRequestDispatcher("New.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);
	}

}


系统界面:

 


package xuyan.control;

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

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 {
		
		String getflag=request.getParameter("flag");
		
		
		if(getflag.equals("fenye"))
	{

		try {
			int pageNow=Integer.parseInt(request.getParameter("s_pageNow"));
			
			 UserBeanCL  ub=new UserBeanCL();
			  
			  ArrayList al=ub.getUserByPage(pageNow);
			  int pageCount=ub.getpageCount();
			  
			  request.setAttribute("result", al);
			 request.setAttribute("pageCount", pageCount+"");
			
			request.getRequestDispatcher("Welcome.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}	
		 //
		//
		else if(getflag.equals("deleteuser"))
		{
			
			String id=request.getParameter("userid");
			
			
			UserBeanCL  ub=new UserBeanCL();
			
			if(ub.DeleteUsers(id))
			
			{
				request.getRequestDispatcher("Success.jsp").forward(request, response);
				
			}
			
			else
			{
				request.getRequestDispatcher("New.jsp").forward(request, response);
				
			}
		}
		
		else if(getflag.equals("adduser"))
		{
              String username=request.getParameter("username");
              String sex=request.getParameter("sex");
              String age=request.getParameter("age");
              String grade=request.getParameter("grade");
  			
			
			UserBeanCL  ub=new UserBeanCL();
			
			if(ub.AddUser(username, sex, age, grade))
			
			{
				request.getRequestDispatcher("Success.jsp").forward(request, response);
				
			}
			
			else
			{
				request.getRequestDispatcher("New.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);
	}

}


UserCLServletUserCLServlet

 

 

阅读更多
个人分类: J2EE
上一篇J2EE学习笔记——Servlet操作数据库(编辑数据)
下一篇J2EE学习笔记——HashMap和 Iterator迭代器的使用
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭