1、項目開發通用化javascript
一、將className,url,user、password經常使用又不變值,定義爲常量,編寫到一個類(Constants)中php
package mybean.util;
html
public class Constants {
public static String DriverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static String url="jdbc:sqlserver://localhost:1433; Database=ebuy";
public static String uid="sa";
public static String pwd="123456";java
//數據庫名,用戶名,密碼,url有所不一樣
}算法
二、建立JDBCTool類,編寫鏈接數據庫、關閉鏈接,實現複用性sql
package mybean.util;
import java.sql.*;
public class JDBCTool {
public static Connection getConnection()
{
Connection conn=null;
try {
Class.forName(Constants.DriverName);
conn=DriverManager.getConnection(Constants.url,Constants.uid,Constants.pwd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
}數據庫
拓展:經過編寫一個通用的方法,在不修改源程序的狀況下,能夠獲取任何數據庫的鏈接dom
解決方案:將相關值放入配置文件中,經過修改配置方法實現和具體的數據解耦jsp
(1)在src文件夾下新建文件(file),jdbc.propertieside
className=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://10.40.43.202:1433;Database=ebuy
user=shopping
password=shopping
(2)mybean.util包下新建JDBCTool類
package mybean.util;
import java.util.*;
import mybean.*;
import java.sql.*;
import java.io.*;;
public class JDBCTool {
/*
* 編寫 一個通用的方法,在不修改源程序的狀況下,能夠獲取任何數據庫的鏈接
*/
public Connection getConnection() throws Exception{
Connection conn=null;
String className=null;
String url=null;
String user=null;
String password=null;
//讀取類路徑下的jdbc.properties文件輸入流
InputStream in=getClass().getClassLoader().getResourceAsStream("jdbc.properties");
//建立properties對象
Properties properties=new Properties();
//加載in對象輸入流
properties.load(in);
/加載字符串
className=properties.getProperty("className");
url=properties.getProperty("url");
user=properties.getProperty("user");
password=properties.getProperty("password");
Properties info=new Properties();
info.put("user", user);
info.put("password",password);
//方法 1
// Driver driver=(Driver)Class.forName(className).newInstance();
// conn=driver.connect(url, info);
//方法2
Class.forName(className);//加載數據驅動
conn=DriverManager.getConnection(url,user,password);
return conn;
}
}
2、分頁設計
分頁考慮一下幾個問題
(1)每頁顯示多少條記錄pageNum
(2)當前頁是哪頁currentPage
(3)總共有多少條記錄countNumber
(4)總共有多少頁countPage,其中countPage=ceil(countNumber/double(pageNum))
分頁須要知道的有:
(1)共有幾頁countPage,當前頁currentPage,共有多少條記錄countNumber,每頁顯示幾條記錄pageNum
(2)須要得到當前頁數據庫中數據GoodsDAO.list(PageInfo)
一、設計分頁Bean--PageInfo.java
package mybean.util;
public class PageInfo {
private int currentPage =1;//當前頁 //2
private int pageNum = 4;//每頁數據數 //1
private int countNumber = 0; //共記錄數 3
private int countPage=1;
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(String currentPage) {
int page=1;
if(null != currentPage)
{
page=Integer.parseInt(currentPage);
}
this.currentPage = page;
}
public int getCountNumber() {
return countNumber;
}
public void setCountNumber(int countNumber) {
this.countNumber = countNumber;
}
public void setCountPage()
{
this.countPage = (int)java.lang.Math.ceil(this.getCountNumber()/(this.getPageNum()+0.0));
}
public int getCountPage()
{
return countPage;
}
}
二、數據庫讀取相應頁的數據GoodsDAO.list(複製原list代碼,適當更改)
public LinkedList<Goods> list(PageInfo pageInfo)
{
LinkedList<Goods> ls=new LinkedList<Goods>();
Connection conn=null;
PreparedStatement stmt=null;
ResultSet rs=null;
String url="jdbc:sqlserver://localhost:1433;Database=ebuy";
String user="shopping";
String password="shopping";
String sql="select top (1*?) * from goods where gid not in (select top (1*?) gid from goods)";
String className="com.microsoft.sqlserver.jdbc.SQLServerDriver";
try {
Class.forName(className);
conn=DriverManager.getConnection(url, user, password);
//首先知道數據庫中有多少條記錄
String sql1="select count(*) from goods";
stmt=conn.prepareStatement(sql1);
rs=stmt.executeQuery();
if(rs.next()){
pageInfo.setCountNumber(rs.getInt(1));
}
rs.close();
stmt.close();
//獲取制定條數據記錄
stmt=conn.prepareStatement(sql);
stmt.setInt(1,pageInfo.getPageNum());
stmt.setInt(2, pageInfo.getPageNum()*(pageInfo.getCurrentPage()-1));
rs=stmt.executeQuery();
while(rs.next()){
Goods g=new Goods();
g.setGid(rs.getInt("gid"));
g.setName(rs.getString("name"));
g.setPrice(rs.getFloat("price"));
g.setNum(rs.getInt("num"));
ls.add(g);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(rs!=null)
{rs.close();}
if(stmt!=null)
{stmt.close();}
if(conn!=null)
{conn.close();}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ls;
}
三、good_view頁添加部分代碼實現,顯示指定頁數據
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="mybean.*,mybean.util.*" %>
<%
// 顯示指定頁的數據
String currentPage = request.getParameter("currentPage");
PageInfo pageInfo=(PageInfo)request.getAttribute("pageInfo");
if(pageInfo==null)
{
pageInfo=new PageInfo();
request.setAttribute("pageInfo",pageInfo);
}
pageInfo.setCurrentPage(currentPage); //設置當前頁
%>
<div style="width:500px;">
<p>商品信息顯示</p>
<div style="padding-left:350px;"><a href="good_add.jsp">添加</a></div>
<table width="400" border="1">
<tr>
<td>商品ID</td>
<td>商品名稱</td>
<td>商品價格</td>
<td>商品數量</td>
<td>刪除</td>
<td>修改</td>
<td>詳細</td>
</tr>
<%
GoodsDAO dao=new GoodsDAO();
LinkedList<Goods>gs=dao.list(pageInfo);
for(Goods g:gs)
{
//out.println(g.getName());
%>
<tr>
<td><%=g.getGid()%></td>
<td><%=g.getName()%></td>
<td><%=g.getPrice()%></td>
<td><%=g.getNum()%></td>
<td><a href="good_delete.jsp?gid=<%=g.getGid()%>">刪除</a></td>
<td><a href="good_update.jsp?gid=<%=g.getGid()%>">修改</a></td>
<td>詳細</td>
</tr>
<%}
pageInfo.setCountPage(); //設置總頁數
%>
</table>
<jsp:include page="page.jsp"/>
<form id="form1" name="form1" action="good_view.jsp" method="post" target="_self">
<input type="hidden" name="currentPage" id="currentPage" value="<%=pageInfo.getCurrentPage()%>">
</form></div>
四、page.jsp實現上一頁下一頁組件
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="mybean.*"%>
<%@page import="mybean.util.*"%>
<script type="text/javascript">
function pageChange(currentPage){
document.getElementById('currentPage').value = currentPage;
document.form1.submit();
}
</script>
<%
PageInfo pageInfo=(PageInfo)request.getAttribute("pageInfo");
if(pageInfo!=null)
{
int countPage=pageInfo.getCountPage();
int upPage=1;
int downPage=countPage;
if(pageInfo.getCurrentPage()!=1)
{
upPage=pageInfo.getCurrentPage()-1;
}
if(pageInfo.getCurrentPage()!=countPage){
downPage=pageInfo.getCurrentPage()+1;
}
%>
<ul style="list-style:none">
<li style="border:1px solid #ccc;width:50px;float:left;margin:5px;" href="#"></a>首頁</li>
<li style="border:1px solid #ccc;width:50px;float:left;margin:5px;" onclick="pageChange(<%=upPage%>);">上一頁</li>
<%
for(int i=1;i<=pageInfo.getCountPage();i++)
{
%>
<li style="border:1px solid #ccc;width:20px;float:left;margin:5px;margin-left:2px;margin-right:2px;" onclick="pageChange(<%=i%>);"><%=i%></li>
<%
}
%>
<li style="border:1px solid #ccc;width:50px;float:left;margin:5px;" onclick="pageChange(<%=downPage%>);">下一頁</li>
<li style="border:1px solid #ccc;width:50px;float:left;margin:5px;" onclick="pageChange(<%=pageInfo.getCountPage()%>);">尾頁</li>
</ul>
<%} %>
五、實現用戶信息分頁顯示
(1)編寫UserDAO.list(pageInfo)
public LinkedList<User> list(PageInfo page){
//page.countRec,page.countPage;
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
String sql1="select count(*) from users";
String sql2="select top (1*?)* from users where uid not in" +
"(select top (1*?)uid from users)";
LinkedList<User>us=new LinkedList<User>();
try{
Class.forName(Const.DRIVER);
conn=DriverManager.getConnection(Const.URL, Const.USER, Const.PASSWORD);
ps=conn.prepareStatement(sql1);
rs=ps.executeQuery();
if(rs.next()){
page.setCountNumber(rs.getInt(1));
}
rs.close();
ps.close();
ps=conn.prepareStatement(sql2);
ps.setInt(1,page.getPageNum());
ps.setInt(2,(page.getCurrentPage()-1)*page.getPageNum() );//2頁,不顯示前十條(2-1)*10
rs=ps.executeQuery();
while(rs.next()){
User u=new User();
u.setUid(rs.getInt("uid"));
u.setName(rs.getString("name"));
u.setEmail(rs.getString("email"));
us.add(u);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(rs!=null)
{rs.close();}
if(ps!=null)
{ps.close();}
if(conn!=null)
{conn.close();}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return us;
}
(2)user_view.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="mybean.*,mybean.util.*" %>
<div style="width:500px;">
<p>用戶信息</p>
<div style="padding-right:150px;float:right;"><a href="good_add.jsp">添加</a></div>
<table width="400" border="1">
<tr>
<td>用戶ID</td>
<td>用戶名稱</td>
<td>用戶郵箱</td>
<td>刪除</td>
<td>修改</td>
<td>詳細</td>
</tr>
<%
PageInfo pageInfo=(PageInfo)request.getAttribute("pageInfo");
if(pageInfo==null){
pageInfo=new PageInfo();
pageInfo.setPageNum(6); //1
request.setAttribute("pageInfo", pageInfo);
}
String currentPage=request.getParameter("currentPage");
pageInfo.setCurrentPage(currentPage); //2
UserDAO dao=new UserDAO();
LinkedList<User> us=dao.list(pageInfo); //pageInfo 3和4屬性
for(User u:us)
{
//out.println(g.getName());
%>
<tr>
<td><%=u.getUid()%></td>
<td><%=u.getName()%></td>
<td><%=u.getEmail()%></td>
<td><a href="../user/UserSevlet?type=delete&uid=<%=u.getUid()%>">刪除</a></td>
<td><a href="#?uid=<%=u.getUid()%>">修改</a></td>
<td>詳細</td>
</tr>
<%}
//pageInfo.setCountPage();
%>
</table>
<jsp:include page="page.jsp"/>
<form id="form1" name="form1" action="user_view.jsp" method="post" target="_self">
<input type="hidden" name="currentPage" id="currentPage" value="<%=pageInfo.getCurrentPage()%>">
</form>
</div>
效果以下:
3、Md5加密技術使用
一、能夠經過上網等方式查找MD5加密代碼
package mybean.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
public static String MD5Encrypt(String strIn)
{
MessageDigest md = null;
String strOut = null;
try
{
md = MessageDigest.getInstance("MD5"); //能夠選中其餘的算法如SHA
byte[] digest = md.digest(strIn.getBytes());
//返回的是byet[],要轉化爲String存儲比較方便
strOut = bytetoString(digest);
}
catch (NoSuchAlgorithmException nsae)
{
nsae.printStackTrace();
}
return strOut;
}
public static String bytetoString(byte[] digest)
{
String str = "";
String tempStr = "";
for (int i = 1; i < digest.length; i++)
{
tempStr = (Integer.toHexString(digest[i] & 0xff));
if (tempStr.length() == 1)
{
str = str + "0" + tempStr;
}
else
{
str = str + tempStr;
}
}
return str.toLowerCase();
}
}
二、編寫主函數進行測試(經過網頁查找MD5工具測試與本身編寫程序結果是否相同)
public static void main(String args[]){
String password="wxj";
String pwd = MD5.MD5Encrypt(password);
System.out.println(pwd);
}
三、任務實施:實現用戶註冊信息加密
(1)用戶註冊頁面設計 /user/register.jsp
<%@ page language="java" import="java.util.*,mybean.User" pageEncoding="UTF-8"%>
<script type="text/javascript">
function check()
{
if(form1.name.value=="")
{
alert("請輸入用戶名!!");
form1.name.focus();
return false;
}
if(form1.password.value=="")
{
alert("請輸入密碼!!");
form1.password.focus();
return false;
}
//var val=document.getElementById("email");
var val=form1.email.value;
if(val.indexOf('@')<1)
{
alert("郵箱格式不對");
form1.email.focus();
return false;
}
return true;
}
</script>
<form action="<%=request.getContextPath()%>/user/UserServlet?type=reg" method="post" submit="return check();">
<table width="400" border="1">
<tr>
<td>用戶名</td>
<td><input type="text" name="name" value="" /></td>
</tr>
<tr>
<td>密碼</td>
<td><input type="password" name="password" value="" /></td>
</tr>
<tr>
<td>性別</td>
<td><input name="sex" type="radio" value="男" checked="ok" />
男
<input name="sex" type="radio" value="女" />
女</td>
</tr>
<tr>
<td>郵箱</td>
<td><input type="text" name="email" value="" /></td>
</tr>
<tr>
<td>電話</td>
<td><input type="text" name="tel" value="" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="button" id="button" value="提交" />
</td>
</tr>
</table>
</form>
</body>
</html>
(2)UserServlet的doPost中添加實現用戶註冊
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String type=request.getParameter("type");
if("login".equals(type)){
String name = request.getParameter("name");
String pwd = request.getParameter("password");
UserDAO dao=new UserDAO();
User u=dao.login(name, pwd);
if(u!=null){
//request.getRequestDispatcher("index.php").forward(request, response);
request.getSession().setAttribute("user",u);
response.sendRedirect("../index.jsp");
}else{
response.sendRedirect("../index.jsp");
}
}else if("reg".equals(type)){
UserDAO dao = new UserDAO();
User u = new User();
u.setName(request.getParameter("name"));
String password=request.getParameter("password");
String pwd = MD5.MD5Encrypt(password);
u.setPassword(pwd);
u.setAddress(request.getParameter("address"));
u.setTel(request.getParameter("tel"));
u.setEmail(request.getParameter("email"));
u.setSex(request.getParameter("sex"));
dao.save(u);
response.sendRedirect("../index.jsp");
System.out.println("成功,xx!!");
}
}
(3)登陸處理修改
用戶輸入用戶名,密碼(password),將用戶輸入密碼md5加密,以後與數據庫中數據比較
UserServlet的 doPost添加一條語句,最後代碼以下
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String type=request.getParameter("type");
if("login".equals(type)){
String name = request.getParameter("name");
String pwd = request.getParameter("password");
pwd = MD5.MD5Encrypt(pwd);
UserDAO dao=new UserDAO();
User u=dao.login(name, pwd);
if(u!=null){
//request.getRequestDispatcher("index.php").forward(request, response);
request.getSession().setAttribute("user",u);
response.sendRedirect("../index.jsp");
}else{
response.sendRedirect("../index.jsp");
}
}else if("reg".equals(type)){
System.out.println("xx!!");
UserDAO dao = new UserDAO();
User u = new User();
u.setName(request.getParameter("name"));
String password=request.getParameter("password");
System.out.print(password);
String pwd = MD5.MD5Encrypt(password);
u.setPassword(pwd);
u.setAddress(request.getParameter("address"));
u.setTel(request.getParameter("tel"));
u.setEmail(request.getParameter("email"));
u.setSex(request.getParameter("sex"));
dao.save(u);
System.out.println("成功,xx!!");
response.sendRedirect("../index.jsp");
}
}
4、驗證碼登陸
<script language="javascript" type="text/javascript">
var code ; //在全局 定義驗證碼
function createCode(){
code = new Array();
var codeLength = 4;//驗證碼的長度
var checkCode = document.getElementById("checkCode");
checkCode.value = "";
var selectChar = new Array(2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z');
for(var i=0;i<codeLength;i++) {
var charIndex = Math.floor(Math.random()*32);
code +=selectChar[charIndex];
}
if(code.length != codeLength){
createCode();
}
checkCode.value = code;
}
function validate () {
var inputCode = document.getElementById("input1").value.toUpperCase();
if(inputCode.length <=0) {
alert("請輸入驗證碼!");
return false;
}
else if(inputCode != code ){
alert("驗證碼輸入錯誤!");
createCode();
return false;
}
else {
form_submit();
return true;
}
}
</script>
</head>
<body onLoad="createCode();">
<form id="login" name="login" action="#" method="post">
<div class="user">
<label>用戶名:
<input type="text" name="username" id="username" />
</label>
</div>
<div class="user">
<label>密 碼:
<input type="password" name="password" id="password" />
</label>
</div>
<div class="chknumber">
<label>驗證碼:
<input type="text" id="input1" />
<input type="button" id="checkCode" class="code" style="width:60px" onClick="createCode()" />
<a href="#" onClick="createCode()">看不清楚</a>
</div>