jsp之用戶管理系統5
?源碼下載:
這個是韓順平jsp中的用戶管理系統的代碼
LoginCl.java
//這是一個控制器,主要完成對用戶身份的驗證
//本身並不實際完成身份驗證的業務邏輯,而是去調model的業務邏輯完成對數據處理...
package com.hao.controller;
import com.hao.model.*;
public class LoginCl extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//得到用戶名和密碼
String username=request.getParameter("username");
//解決無法從資料庫中讀取中文的解決方法
username=new Tools().getNewStr(username);
String password=request.getParameter("password");
//使用模型UserBeanCl,完成對用戶身份的驗證
//創建UserBeanCl對象
UserBeanCl ubc=new UserBeanCl();
//調用方法
if (ubc.checkUser(username, password))
{
//登陸成功!!
//這種跳轉為轉向
//response.sendRedirect("Wel.jsp");
//在跳轉到Wel.jsp頁面前就要把要顯示的數據就要準備好!!!
ArrayList al =ubc.fenye(1);
int pageCount =ubc.getPageCount();
//將al pageCount放入request中...
request.setAttribute("al", al);
request.setAttribute("pageCount", pageCount);
request.setAttribute("pageNow", 1);
//因為sendRedirect跳轉的效率不高,在公司里常常用轉發的方法....
//這種轉發效率高,並且request中的對象還可以在下個頁面中使用
//將用戶名放入session以備後用
request.getSession().setAttribute("username", username);
request.getSession().setMaxInactiveInterval(300);
//在本案例中request對象指的是上面的兩句話result和pageCount
request.getRequestDispatcher("main.jsp").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
//處理用戶的分頁顯示
//也用於處理用戶的增刪改
package com.hao.controller;
public class UserClServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//創建一個UserBeanCl方法,供全局調用!!!
UserBeanCl ubc =new UserBeanCl();
//得到標誌位,判斷進行不同的操作..
String flag=request.getParameter("flag").toString();
//情況一:分頁管理
if(flag.equals("fenye"))
{
try
{
//得到pageNow
int pageNow =Integer.parseInt(request.getParameter("pageNow").toString());
//在跳轉到Wel.jsp頁面前就要把要顯示的數據就要準備好!!!
ArrayList al =ubc.fenye(pageNow);
int pageCount =ubc.getPageCount();
//將al pageCount放入request中...
//說明這裡寫成setAttribute那麼在下也就要用getAttribute來接受
//如果是參數就要用getParameter來接受,不能搞混咯!!!!
request.setAttribute("pageCount", pageCount+"");
request.setAttribute("al", al);
request.setAttribute("pageNow", pageNow);
//重新跳回Wel.jsp
request.getRequestDispatcher("Wel.jsp").forward(request, response);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
//System.out.println("這是UserClServlet的測試finally");
}
}
//情況二:刪除用戶
else if(flag.equals("delUser"))
{
String userId=request.getParameter("userId");
if (ubc.delUser(userId))
{
request.getRequestDispatcher("Succ.jsp").forward(request, response);
}
else
{
request.getRequestDispatcher("Fail.jsp").forward(request, response);
}
}
//情況三:添加用戶
else if(flag.equals("addUser"))
{
//得到用戶輸入的信息..
String username=request.getParameter("username");
String password=request.getParameter("password");
String email=request.getParameter("email");
String grade=request.getParameter("grade");
if (ubc.addUser( username, password , email , grade ))
{
request.getRequestDispatcher("Succ.jsp").forward(request, response);
}
else
{
request.getRequestDispatcher("Fail.jsp").forward(request, response);
}
}
//情況四:添加用戶
else if(flag.equals("updateUser"))
{
//得到用戶輸入的信息..
String userid =request.getParameter("userid");
String username=request.getParameter("username");
String password=request.getParameter("password");
String email=request.getParameter("email");
String grade=request.getParameter("grade");
if (ubc.updateUser( userid , username, password , email , grade))
{
request.getRequestDispatcher("Succ.jsp").forward(request, response);
}
else
{
request.getRequestDispatcher("Fail.jsp").forward(request, response);
}
}
}
}
ConDB.java
//當一段代碼被使用三次以上就應該把這樣的代碼封裝到一個函數裡面
package com.hao.model;
import java.sql.*;
public class ConDB {
private Connection ct=null;
public Connection getct()
{
Connection con=null;
try
{
//1載入驅動
String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url="jdbc:sqlserver://127.0.0.1:1433;databaseName=spdb";
Class.forName(driver);
con =DriverManager.getConnection (url,"sa","hao123");
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
return con ;
}
}
}
Tools.java
package com.hao.model;
public class Tools {
//提供一個方法,將亂碼轉換成gb2312...
public static String getNewStr(String input)
{
String result="";
try
{
result=new String (input.getBytes("iso-8859-1"),"gb2312");
}
catch(Exception ex)
{
ex.printStackTrace();
}
return result;
}
}
UserBean.java
//這是一個javaBean對應Users表數據.
//表中有幾個欄位,那麼這個java中就有多少個私有屬性
//他的一個實例代表一個USers表中的一條記錄.
package com.hao.model;
public class UserBean {
private int userId;
private String userName;
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;
}
private String passwd;
private String email;
private int grade;
public void setUserId(int userId) {
this.userId = userId;
}
public int getUserId() {
return userId;
}
}
UserBeanCl.java
//這是一個處理類,有些人喜歡把它叫做BO business object
//主要是封裝users表的各種操作[增加刪除修改查詢].
package com.hao.model;
import java.sql.*;
import java.util.*;
public class UserBeanCl {
private Connection ct =null;
private Statement sm =null;
private ResultSet rs =null;
private int pageSize=3;
private int rowCount=0;//從資料庫中得到
private int pageCount =0;//一共有多少頁 通過pageSize和rowCount獲得.
//修改用戶
public boolean updateUser(String userid ,String username,String password ,String email ,String grade)
{
boolean b=false;
try
{
ct=new ConDB().getct();
sm=ct.createStatement();
int a=sm.executeUpdate("update users set username="
+username+",passwd="+password+",email="+email+",grade="+grade+" where userId = "+userid);
if(a==1)
{
b=true;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return b;
}
//添加用戶
/**
* @author haofengli
* @return 如果為真,說明添加成功;否則,添加失敗
* @param username 用戶名
* @param password 密碼
*/
public boolean addUser(String username,String password ,String email ,String grade)
{
boolean b=false;
try
{
ct=new ConDB().getct();
sm=ct.createStatement();
int a=sm.executeUpdate("insert into users values ("
+username+","+password+","+email+","+grade+")");
if(a==1)
{
b=true;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return b;
}
//刪除用戶
public boolean delUser(String userId)
{
boolean b=false;
try
{
ct=new ConDB().getct();
sm=ct.createStatement();
int a=sm.executeUpdate("delete from users where userid = "+userId+"");
if(a==1)
{
b=true;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return b;
}
//得到總頁數
public int getPageCount()
{
try
{
//得到連接
ct =new ConDB().getct();
//3創建Statement
sm=ct.createStatement();
//4查詢
rs=sm.executeQuery("select count(*) from users ");
if(rs.next())
{
rowCount =rs.getInt(1);
//計算pageCount
pageCount=(rowCount+pageSize-1)/pageSize;
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
this.closed();
}
return pageCount ;
}
//分頁函數
public ArrayList fenye ( int pageNow)
{
ArrayList al =new ArrayList();
try
{
//得到連接
ct =new ConDB().getct();
//3創建Statement
sm=ct.createStatement();
//查詢出需要顯示的記錄.
rs=sm.executeQuery("select top "+pageSize
+" * from users where userid not in ( select top "+pageSize*(pageNow-1)+" userid from users )");
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放進al中
al.add(ub);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
this.closed();
return al;
}
}
//驗證用戶是否存在!
public boolean checkUser (String u,String p)
{
boolean b=false;
String sql ="select top 1 passwd from users where username ="+u+"";
try
{
//得到連接
ct=new ConDB().getct();
sm =ct.createStatement();
rs=sm.executeQuery(sql);
if(rs.next())
{
if(rs.getString(1).equals(p))
{
b=true;
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
this.closed();
}
return b;
}
//關閉資源
public void closed()
{
try
{
if(rs!=null){rs.close(); rs=null;}
if(sm!=null){sm.close(); sm=null;}
if(ct!=null){ct.close(); ct =null;}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
Adduser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
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 AddUser.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="#ced3fc"> <!-- 引入一張圖片 -->
<img src="images/myLogo.gif"></img>
<hr>
<center>
<h1 >添加用戶</h1>
<form action="UserClServlet?flag=addUser" method="post">
<table>
<tr bgcolor="silver"><td>用戶名:</td><td> <input type="text" name="username"/></td></tr>
<tr bgcolor="silver"><td>密碼:</td><td> <input type="text" name="password"/></td></tr>
<tr bgcolor="silver"><td>電子郵件:</td><td> <input type="text" name="email"/></td></tr>
<tr bgcolor="silver"><td>級別:</td><td> <input type="text" name="grade"/></td></tr>
</table>
<input type="Submit" name="button1" value="確定"/> <input type="reset" name="button2" value="重置">
</form>
</center>
<hr>
<!-- 圖片可以直接拖過來接可以了 -->
<img src="images/logoleft.gif"></img>
</body>
</html>
Fail.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
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 Fail.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="#ced3fc">
<!-- 引入一張圖片 -->
<img src="images/myLogo.gif"></img>
<center>
操作失敗!!<br><hr>
<a href="main.jsp">返回主界面</a>
</center>
<!--引入一張圖片 小烏龜的圖片 -->
<hr>
<!-- 圖片可以直接拖過來接可以了 -->
<img src="images/logoleft.gif"></img>
</body>
</html>
Login.java
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
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="#ced3fc">
<!-- 引入一張圖片 -->
<img src="images/myLogo.gif"></img>
<center>
用戶登錄<br><hr>
<!-- 注意了,雖然的servlet這裡的有一個/但是在這裡的action中不能加/ -->
<form action="LoginCl" method="post">
用戶名:<input type="text" name="username" size="16"/><br>
密 碼:<input type="password" name="password" size="16"/><br>
<input type ="submit" value="提交" />
<input type="reset" value ="重置"/>
</form>
</center>
<!--引入一張圖片 小烏龜的圖片 -->
<hr>
<!-- 圖片可以直接拖過來接可以了 -->
<img src="images/logoleft.gif"></img>
</body>
</html>
推薦閱讀:
TAG:JSP |