編寫一個簡單的javaweb網上商城專案
未經作者允許,禁止轉載。轉載請註明出處。
一、專案概覽
這是一個簡單的web專案,只用到servlet、jsp、jdbc。想要完整專案,評論區留下郵箱,碼字不易,點個贊吧。
二、專案的首頁部分
這個介面是一個簡單的JSP介面,注意它開始的兩行(紅字+超連結)部分,使用的include指令,靜態包含到這個頁面。提醒大家的是,包含的頁面和被包含頁面的page指令必須一模一樣。
程式碼如下(head.txt和index.jsp):
<%@ page contentType="text/html;charset=GB2312" %> <div align="center"> <Font color=red><H3>“青山不老綠水無憂”化妝品銷售網</H3></Font> <table cellSpacing="1" cellPadding="1" width="660" align="center" border="0"> <tr valign="bottom"> <td><A href="index.jsp">主頁</A></td> <td><A href="inputRegisterMess.jsp">註冊</font></A></td> <td><A href="login.jsp">登入</A></td> <td><A href="lookCosmetic.jsp">瀏覽化妝品</A></td> <td><A href="searchCosmetic.jsp">查詢化妝品</A></td> <td><A href="lookShoppingCar.jsp">檢視購物車</A></td> <td><A href="lookOrderForm.jsp">檢視訂單</A></td> <td><A href="exitServlet">退出</A></td> </tr> </table> </div>
<%@ page contentType="text/html;charset=GB2312" %> <HTML> <BODY> <HEAD></HEAD> <title>首頁</title> <%@ include file="head.txt" %> <CENTER> <h1><font Size=4 color=blue>歡迎光臨“青山不老綠水無憂”化妝品銷售網</font></h1> <img src="image/welcome.jpg" width=600 height=200 ></img> </CENTER> </BODY></HTML>
三、專案的註冊功能
head.txt前面介紹過了,緊接著是一個border為0的3行4列的表格,注意這個表格是被表單包裹著的。那麼從下面那個表格,我們可以看出,它是想要把註冊成功之後的資訊顯示到表格的第二列。怎麼做呢?首先提交後的資訊,必須到servlet中進行連線資料庫,並且把資料插入到資料庫中。同時要把提交的資料,儲存到JavaBean中。先貼出程式碼,再分析。
inputRegisterMess.jsp:
<%@ page contentType="text/html;charset=GB2312" %> <jsp:useBean id="userBean" class="mybean.data.Register" scope="request"/> <HEAD><%@ include file="head.txt" %></HEAD> <title>註冊頁面</title> <HTML><BODY background=image/back.jpg><Font size=2> <div align="center"> <FORM action="registerServlet" method="post" name=form> <table> 使用者名稱由字母、數字、下劃線構成,*註釋的項必須填寫。 <tr><td>*使用者名稱稱:</td><td><Input type=text name="logname" ></td> <td>*使用者密碼:</td><td><Input type=password name="password"> </td></tr> <tr><td>*重複密碼:</td><td> <Input type=password name="again_password"></td> <td>聯絡電話:</td><td><Input type=text name="phone"></td></tr> <tr><td>郵寄地址:</td><td><Input type=text name="address"></td> <td>真實姓名:</td><td><Input type=text name="realname"></td> <td><Input type=submit name="g" value="提交"></td> </tr> </table> </Form> </div > <div align="center"> <p> 註冊反饋: <jsp:getProperty name="userBean" property="backNews" /> <table border=3> <tr><td>會員名稱:</td> <td><jsp:getProperty name="userBean" property="logname"/></td> </tr> <tr><td>姓名:</td> <td><jsp:getProperty name="userBean" property="realname"/></td> </tr> <tr><td>地址:</td> <td><jsp:getProperty name="userBean" property="address"/></td> </tr> <tr><td>電話:</td> <td><jsp:getProperty name="userBean" property="phone"/></td> </tr> </table></div > </Body></HTML>
HandleRegister.java:
package myservlet.control;
import mybean.data.*;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HandleRegister extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
try { Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e){}
}
public String handleString(String s)
{ try{ byte bb[]=s.getBytes("iso-8859-1");
s=new String(bb);
}
catch(Exception ee){}
return s;
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
String uri="jdbc:mysql://127.0.0.1:3306/shop?"+
"user=root&password=123456&characterEncoding=gb2312";
Connection con;
PreparedStatement sql;
// <jsp:useBean id="userBean" class="Register的完整類名"
// scope="request" />
Register userBean=new Register(); //建立的Javabean模型
request.setAttribute("userBean",userBean);
// 臨時變數, 儲存表單資料
// 合法性校驗後,儲存到成員變數
String logname=request.getParameter("logname").trim();
String password=request.getParameter("password").trim();
String again_password=request.getParameter("again_password").trim();
String phone=request.getParameter("phone").trim();
String address=request.getParameter("address").trim();
String realname=request.getParameter("realname").trim();
if(logname==null)
logname="";
if(password==null)
password="";
if(!password.equals(again_password)) {
userBean.setBackNews("兩次密碼不同,註冊失敗,");
RequestDispatcher dispatcher=
request.getRequestDispatcher("inputRegisterMess.jsp");
dispatcher.forward(request, response);//轉發
return;
}
boolean isLD=true;
for(int i=0;i<logname.length();i++){
char c=logname.charAt(i);
if(!((c<='z'&&c>='a')||(c<='Z'&&c>='A')||(c<='9'&&c>='0')))
isLD=false;
}
boolean boo=logname.length()>0&&password.length()>0&&isLD;
String backNews="";
try{ con=DriverManager.getConnection(uri);
String insertCondition="INSERT INTO user VALUES (?,?,?,?,?)";
sql=con.prepareStatement(insertCondition);
if(boo)
{ sql.setString(1,handleString(logname));
sql.setString(2,handleString(password));
sql.setString(3,handleString(phone));
sql.setString(4,handleString(address));
sql.setString(5,handleString(realname));
int m=sql.executeUpdate();
if(m!=0){
backNews="註冊成功";
// <jsp:setProperty name="userBean" property="logname" param="logname" />
// <jsp:setProperty name="userBean" property="*" />
userBean.setLogname(logname);
userBean.setBackNews(backNews);
userBean.setPhone(handleString(phone));
userBean.setAddress(handleString(address));
userBean.setRealname(handleString(realname));
}
}
else {
backNews="資訊填寫不完整或名字中有非法字元";
userBean.setBackNews(backNews);
}
con.close();
}
catch(SQLException exp){
backNews="該會員名已被使用,請您更換名字"+exp;
userBean.setBackNews(backNews);
}
RequestDispatcher dispatcher=
request.getRequestDispatcher("inputRegisterMess.jsp");
dispatcher.forward(request, response);//轉發
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
doPost(request,response);
}
}
1.init()函式中載入驅動,有個handleString()函式使用來將字串以相應的編碼方式轉化成位元組陣列,之後再將位元組陣列作為引數,建立新的字串並且返回。
2.doPost()方法中的業務邏輯(jdbc連線資料庫就不解釋了,很簡單),它先new了一個Register,然後用set方法將表單中的資料設定該物件中。從註釋中,我們可以看出它還可以通過jsp的標籤進行建立,而且自動建立之後,可以用setProperty標籤設定到對應的自動建立的物件中,從後面的註釋中,我們也能看的出來。它提供了兩種方法,逐個設定,或者設定全部。從中啊,我們可以看到,jsp的useBean標籤、setProperty標籤、getProperty標籤本質上useBean標籤就是把JavaBean來new出一個物件,setProperty標籤對應於物件呼叫set方法設定屬性,getProperty標籤對應於物件打點呼叫get方法。底層應該就是封裝了一把,定義了新的比較簡單的JSP標籤語法。
3.簡單的說一下它的業務邏輯,取出form表單的內容,進行判斷。首先,使用者要是不設定使用者名稱,密碼。得有個判斷不能讓它通過,它最後使用字串為0做判斷不能通過。所以就設定為“”,null是調不出來length。接著,使用者名稱密碼有了,確認密碼得判斷相同,如果相同的話,轉發到註冊頁面,結束本頁面。注意的是,這裡只能是轉發,因為它的jsp頁面scope是request。再之後那裡是判斷使用者名稱必須是由字母數字組成,這裡最好用正則表示式,能交給前端處理的,就別放在後端。最後的boo是最終確定使用者名稱和密碼的,如果是true則通過。
4.把資料放到資料庫,這裡的setString()引數是1開始,不要弄錯了。把資訊設定到資料庫成功,就代表了註冊成功。否則的話,只可能是含有非法字元。使用者名稱是主鍵,如果資料庫中存在了,再次插入,一定會報錯的。在捕獲異常中設定backNews資訊,再轉發到註冊頁面。
四、登入功能的實現
login.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<jsp:useBean id="loginBean" class="mybean.data.Login" scope="session"/>
<HTML><HEAD><%@ include file="head.txt" %></HEAD>
<BODY background=image/back.jpg><font size=2>
<div align="center">
<table border=2>
<tr> <th>登入</th></tr>
<FORM action="loginServlet" Method="post">
<tr><td>登入名稱:<Input type=text name="logname"></td></tr>
<tr><td>輸入密碼:<Input type=password name="password"></td></tr>
</table>
<Input type=submit name="g" value="提交">
</form>
</div >
<div align="center" >
登入反饋資訊:<jsp:getProperty name="loginBean" property="backNews"/>
<br>登入名稱:<jsp:getProperty name="loginBean" property="logname"/>
<div >
</font>
</BODY></HTML>
這裡比較簡單,看程式碼就會明白。
HandleLogin.java:
package myservlet.control;
import mybean.data.*;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class HandleLogin extends HttpServlet{
public void init(ServletConfig config) throws ServletException{
super.init(config);
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e){}
}
public String handleString(String s){
try{ byte bb[]=s.getBytes("iso-8859-1");
s=new String(bb);
}
catch(Exception ee){}
return s;
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
Connection con;
Statement sql;
String logname=request.getParameter("logname").trim(),
password=request.getParameter("password").trim();
logname=handleString(logname);
password=handleString(password);
String uri="jdbc:mysql://127.0.0.1/shop?"+
"user=root&password=123456&characterEncoding=gb2312";
boolean boo=(logname.length()>0)&&(password.length()>0);
try{
con=DriverManager.getConnection(uri);
String condition="select * from user where logname = '"+logname+
"' and password ='"+password+"'";
sql=con.createStatement();
if(boo){
ResultSet rs=sql.executeQuery(condition);
boolean m=rs.next();
if(m==true){
//呼叫登入成功的方法:
success(request,response,logname,password);
RequestDispatcher dispatcher=
request.getRequestDispatcher("login.jsp");//轉發
dispatcher.forward(request,response);
}
else{
String backNews="您輸入的使用者名稱不存在,或密碼不般配";
//呼叫登入失敗的方法:
fail(request,response,logname,backNews);
}
}
else{
String backNews="請輸入使用者名稱和密碼";
fail(request,response,logname,backNews);
}
con.close();
}
catch(SQLException exp){
String backNews=""+exp;
fail(request,response,logname,backNews);
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
doPost(request,response);
}
public void success(HttpServletRequest request,HttpServletResponse response
,String logname,String password) {
Login loginBean=null;
HttpSession session=request.getSession(true);
try{ loginBean=(Login)session.getAttribute("loginBean");
if(loginBean==null){
loginBean=new Login(); //建立新的資料模型
session.setAttribute("loginBean",loginBean);
loginBean=(Login)session.getAttribute("loginBean");
}
String name =loginBean.getLogname();
if(name.equals(logname)) {
loginBean.setBackNews(logname+"已經登入了");
loginBean.setLogname(logname);
}
else { //資料模型儲存新的登入使用者
loginBean.setBackNews(logname+"登入成功");
loginBean.setLogname(logname);
}
}
catch(Exception ee){
loginBean=new Login();
session.setAttribute("loginBean",loginBean);
loginBean.setBackNews(logname+"登入成功");
loginBean.setLogname(logname);
}
}
public void fail(HttpServletRequest request,HttpServletResponse response
,String logname,String backNews) {
response.setContentType("text/html;charset=GB2312");
try {
PrintWriter out=response.getWriter();
out.println("<html><body>");
out.println("<h2>"+logname+"登入反饋結果<br>"+backNews+"</2>") ;
out.println("返回登入頁面或主頁<br>");
out.println("<a href =login.jsp>登入頁面</a>");
out.println("<br><a href =index.jsp>主頁</a>");
out.println("</body></html>");
}
catch(IOException exp){}
}
}
得到使用者名稱,密碼,轉換成對應的編碼方式防止亂碼。判斷對應的字串長度是否大於0。準備在資料庫進行查詢,判斷是否長度為0。為零的話就去呼叫fail方法。fail方法是寫了一個簡答的反饋介面。不為0的話就能夠去查詢了,執行查詢語句返回結果集。有結果的話就執行success方法。該方法做的是:先看看存在會話沒有,如果沒有的話就建立一個會話。通過會話取出loginbean,沒有的話就建立一個,設定到會話中。這樣不管如何只要是呼叫這個方法,就有會話,會話中就有loginbean。因為該判斷的在呼叫該方法之前就已經判斷了,這裡主要就是建立會話維護登入。如果為空的話,登入成功。不為空,loginbean有物件,能調用出equals判斷相等的話,就表明已經登入成功。
五、瀏覽商品的功能
lookCosmetic.jsp:
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="java.sql.*" %>
<HTML><HEAD><%@ include file="head.txt" %></HEAD>
<BODY background=image/back.jpg><font size=2>
<div align="center">
<% try { Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e){}
String uri="jdbc:mysql://127.0.0.1:3306/shop?"+
"user=root&password=123456&characterEncoding=gb2312";
Connection con;
Statement sql;
ResultSet rs;
try {
con=DriverManager.getConnection(uri);
sql=con.createStatement();
//讀取classify表,獲得分類:
rs=sql.executeQuery("SELECT * FROM classify ");
out.print("<form action='queryServlet' method ='post'>") ;
out.print("<select name='fenleiNumber'>") ;
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
out.print("<option value ="+id+">"+name+"</option>");
}
out.print("</select>");
out.print("<input type ='submit' value ='提交'>");
out.print("</form>");
con.close();
}
catch(SQLException e){
out.print(e);
}
%>
</div></font>
</BODY></HTML>
QueryAllRecord.java
package myservlet.control;
import mybean.data.DataByPage;
import com.sun.rowset.*;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class QueryAllRecord extends HttpServlet{
CachedRowSetImpl rowSet=null;
public void init(ServletConfig config) throws ServletException{
super.init(config);
try { Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e){}
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
request.setCharacterEncoding("gb2312");
String idNumber= request.getParameter("fenleiNumber");
if(idNumber==null)
idNumber="0";
int id = Integer.parseInt(idNumber);
HttpSession session=request.getSession(true);
Connection con=null;
DataByPage dataBean=null;
try{
dataBean=(DataByPage)session.getAttribute("dataBean");
if(dataBean==null){
dataBean=new DataByPage(); //建立Javabean物件
session.setAttribute("dataBean",dataBean);
}
}
catch(Exception exp){
dataBean=new DataByPage();
session.setAttribute("dataBean",dataBean);
}
String uri="jdbc:mysql://127.0.0.1:3306/shop";
try{
con=DriverManager.getConnection(uri,"root","123456");
Statement sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs=sql.executeQuery("SELECT * FROM cosmeticForm where id = "+id);
rowSet=new CachedRowSetImpl(); //建立行集物件
rowSet.populate(rs);
dataBean.setRowSet(rowSet); //行集資料儲存在dataBean中
con.close(); //關閉連線
System.out.println("QueryAllRecord - select");
}
catch(SQLException exp){}
response.sendRedirect("byPageShow.jsp");//重定向到byPageShow.jsp
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
doPost(request,response);
}
}
從表單中獲取到查的是哪個化妝品。把字串的id轉換成了int型別。建立session和對應的分頁物件,並且把該物件放到session中。去查詢對應的化妝品記錄,並且建立CachedRowSetImpl行級物件。使得即使關閉資料庫連線,結果集也存在,而且能在不同頁面轉換。bean中也有對應的行級物件。
byPageShow.jsp:
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="mybean.data.DataByPage" %>
<%@ page import="com.sun.rowset.*" %>
<jsp:useBean id="dataBean" class="mybean.data.DataByPage" scope="session"/>
<%@ include file="head.txt" %></HEAD>
<HTML><Body background=image/back.jpg><center>
<BR>當前顯示的內容是:
<table border=2>
<tr>
<th>化妝品標識號</th>
<th>化妝品名稱</th>
<th>化妝品製造商</th>
<th>化妝品價格</th>
<th>檢視詳情</th>
<td><font color=blue>新增到購物車</font></td>
</tr>
<jsp:setProperty name="dataBean" property="pageSize" param="pageSize"/>
<jsp:setProperty name="dataBean" property="currentPage" param="currentPage"/>
<%
CachedRowSetImpl rowSet=dataBean.getRowSet();
if(rowSet==null) {
out.print("沒有任何查詢資訊,無法瀏覽");
return;
}
rowSet.last();
int totalRecord=rowSet.getRow();
out.println("全部記錄數"+totalRecord); //全部記錄數
int pageSize=dataBean.getPageSize(); //每頁顯示的記錄數
int totalPages = dataBean.getTotalPages();
if(totalRecord%pageSize==0)
totalPages = totalRecord/pageSize;//總頁數
else
totalPages = totalRecord/pageSize+1;
dataBean.setPageSize(pageSize);
dataBean.setTotalPages(totalPages);
if(totalPages>=1) {
if(dataBean.getCurrentPage()<1)
dataBean.setCurrentPage(dataBean.getTotalPages());
if(dataBean.getCurrentPage()>dataBean.getTotalPages())
dataBean.setCurrentPage(1);
int index=(dataBean.getCurrentPage()-1)*pageSize+1;
rowSet.absolute(index); //查詢位置移動到currentPage頁起始位置
boolean boo=true;
for(int i=1;i<=pageSize&&boo;i++) {
String number=rowSet.getString(1);
String name=rowSet.getString(2);
String maker=rowSet.getString(3);
String price=rowSet.getString(4);
String goods =
"("+number+","+name+","+maker+
","+price+")#"+price;//便於購物車計算價格,尾綴上"#價格值"
goods = goods.replaceAll("\\p{Blank}","");
String button="<form action='putGoodsServlet' method = 'post'>"+
"<input type ='hidden' name='java' value= "+goods+">"+
"<input type ='submit' value='放入購物車' ></form>";
String detail="<form action='showDetail.jsp' method = 'post'>"+
"<input type ='hidden' name='xijie' value= "+number+">"+
"<input type ='submit' value='檢視細節' ></form>";
out.print("<tr>");
out.print("<td>"+number+"</td>");
out.print("<td>"+name+"</td>");
out.print("<td>"+maker+"</td>");
out.print("<td>"+price+"</td>");
out.print("<td>"+detail+"</td>");
out.print("<td>"+button+"</td>");
out.print("</tr>");
boo=rowSet.next();
}
}
%>
</table>
<BR>每頁最多顯示<jsp:getProperty name="dataBean" property="pageSize"/>條資訊
<BR>當前顯示第<Font color=blue>
<jsp:getProperty name="dataBean" property="currentPage"/>
</Font>頁,共有
<Font color=blue><jsp:getProperty name="dataBean" property="totalPages"/>
</Font>頁。
<Table>
<tr><td><FORM action="" method=post>
<Input type=hidden name="currentPage" value=
"<%=dataBean.getCurrentPage()-1 %>">
<Input type=submit name="g" value="上一頁"></FORM></td>
<td><FORM action="" method=post>
<Input type=hidden name="currentPage"
value="<%=dataBean.getCurrentPage()+1 %>">
<Input type=submit name="g" value="下一頁"></FORM></td></tr>
<tr><td> <FORM action="" method=post>
每頁顯示<Input type=text name="pageSize" value =1 size=3>
條記錄<Input type=submit name="g" value="確定"></FORM></td>
<td> <FORM action="" method=post>
輸入頁碼:<Input type=text name="currentPage" size=2 >
<Input type=submit name="g" value="提交"></FORM></td></tr>
</Table>
</Center>
</BODY></HTML>
重點解釋<%%>中的內容,得到行級物件後,判斷裡面有沒有資料,沒有資料就輸出對應提示。從行級物件中得到全部的記錄數有多少,得到每頁要顯示幾條記錄,相除得到總頁數有多少。設定到對應的分頁bean物件中。緊接著的判斷分支表示只要有記錄(第一個大if),判斷當前頁是否在1-總頁數之間(兩個小if),index表示鎖定到當前頁的哪行記錄,最後通過rowSet.absolute(index);真正查詢位置移動到currentPage頁起始位置。for迴圈用來顯示,把每條記錄從資料庫中拿出來,然後顯示到表頭下面那行,boo來確保當記錄顯示完畢之後就不在顯示,否則會報錯。最後那段HTML程式碼用來跳轉上一頁下一頁,很簡單用form表單,重複提交到本頁面,再從頭執行,如果本身有兩頁記錄,卻跳到第三頁,它就會把你糾正回第一頁。
六、購物車功能
PutGoodsToCar.java:
package myservlet.control;
import mybean.data.Login;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PutGoodsToCar extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
request.setCharacterEncoding("gb2312");
String goods = request.getParameter("java");
System.out.println(goods);
Login loginBean=null;
HttpSession session=request.getSession(true);
try{ loginBean=(Login)session.getAttribute("loginBean");
boolean b =loginBean.getLogname()==null||
loginBean.getLogname().length()==0;
if(b)
response.sendRedirect("login.jsp");//重定向到登入頁面
LinkedList<String> car = loginBean.getCar();
car.add(goods);
speakSomeMess(request,response,goods);
}
catch(Exception exp){
response.sendRedirect("login.jsp");//重定向到登入頁面
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
doPost(request,response);
}
public void speakSomeMess(HttpServletRequest request,
HttpServletResponse response,String goods) {
response.setContentType("text/html;charset=GB2312");
try {
PrintWriter out=response.getWriter();
out.print("<%@ include file='head.txt' %></HEAD>");
out.println("<html><body>");
out.println("<h2>"+goods+"放入購物車</h2>") ;
out.println("檢視購物車或返回瀏覽化妝品<br>");
out.println("<a href =lookShoppingCar.jsp>檢視購物車</a>");
out.println("<br><a href =byPageShow.jsp>瀏覽化妝品</a>");
out.println("</body></html>");
}
catch(IOException exp){}
}
}
這段程式碼把session中的loginbean拿出來,之前for迴圈那裡有一段goods資訊,這裡就是要把表單中那段資訊新增進去。然後呼叫speakSomeMess方法顯示出來,如第二張圖。
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="mybean.data.Login" %>
<%@ page import="java.util.*" %>
<jsp:useBean id="loginBean" class="mybean.data.Login" scope="session"/>
<HTML><HEAD><%@ include file="head.txt" %></HEAD>
<BODY background=image/back.jpg><font size=2>
<div align="center">
<% if(loginBean==null){
response.sendRedirect("login.jsp");//重定向到登入頁面
}
else {
boolean b =loginBean.getLogname()==null||
loginBean.getLogname().length()==0;
if(b)
response.sendRedirect("login.jsp");//重定向到登入頁面
}
LinkedList car =loginBean.getCar();
if(car==null)
out.print("<h2> 購物車沒有物品.</h2>");
else {
Iterator<String> iterator=car.iterator();
StringBuffer buyGoods = new StringBuffer();
int n=0;
double priceSum =0;
out.print("購物車中的物品:<table border=2>");
while(iterator.hasNext()) {
String goods=iterator.next();
String showGoods="";
n++;
//購車車物品的字尾是“#價格數字",比如“化妝品價格3989 #3989”
int index=goods.lastIndexOf("#");
if(index!=-1){
priceSum+=Double.parseDouble(goods.substring(index+1));
showGoods = goods.substring(0,index);
}
buyGoods.append(n+":"+showGoods);
String del="<form action='deleteServlet' method = 'post'>"+
"<input type ='hidden' name='delete' value= "+goods+">"+
"<input type ='submit' value='刪除' ></form>";
out.print("<tr><td>"+showGoods+"</td>");
out.print("<td>"+del+"</td></tr>");
}
out.print("</table>");
String orderForm = "<form action='buyServlet' method='post'>"+
" <input type ='hidden' name='buy' value= "+buyGoods+" >"+
" <input type ='hidden' name='price' value= "+priceSum+" >"+
"<input type ='submit' value='生成訂單'></form>";
out.print(orderForm);
}
%>
</div></font>
</BODY></HTML>
這裡是把loginbean中對應的car取出來,型別是LinkedList,用迭代器遍歷,在表格上一一顯示。
七、生成訂單功能
HandleBuyGoods:
package myservlet.control;
import mybean.data.Login;
import java.sql.*;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HandleBuyGoods extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e){}
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
request.setCharacterEncoding("gb2312");
String buyGoodsMess = request.getParameter("buy");
if(buyGoodsMess==null||buyGoodsMess.length()==0) {
fail(request,response,"購物車沒有物品,無法生成訂單");
return;
}
String price = request.getParameter("price");
if(price==null||price.length()==0) {
fail(request,response,"沒有計算價格和,無法生成訂單");
return;
}
float sum = Float.parseFloat(price);
Login loginBean=null;
HttpSession session=request.getSession(true);
try{ loginBean=(Login)session.getAttribute("loginBean");
boolean b =loginBean.getLogname()==null||
loginBean.getLogname().length()==0;
if(b)
response.sendRedirect("login.jsp");//重定向到登入頁面
}
catch(Exception exp){
response.sendRedirect("login.jsp");//重定向到登入頁面
}
String uri="jdbc:mysql://127.0.0.1/shop?"+
"user=root&password=123456&characterEncoding=gb2312";
Connection con;
PreparedStatement sql;
try{ con=DriverManager.getConnection(uri);
String insertCondition="INSERT INTO orderform VALUES (?,?,?,?)";
sql=con.prepareStatement(insertCondition);
sql.setInt(1,0); //訂單序號會自定增加
sql.setString(2,loginBean.getLogname());
sql.setString(3,buyGoodsMess);
sql.setFloat(4,sum);
sql.executeUpdate();
LinkedList car=loginBean.getCar();
car.clear(); //清空購物車
success(request,response,"生成訂單成功");
System.out.println("HandleBuyGoods - 生成訂單成功");
}
catch(SQLException exp){
fail(request,response,"生成訂單失敗"+exp);
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
doPost(request,response);
}
public void success(HttpServletRequest request,HttpServletResponse response,
String backNews) {
response.setContentType("text/html;charset=GB2312");
try {
PrintWriter out=response.getWriter();
out.println("<html><body>");
out.println("<h2>"+backNews+"</h2>") ;
out.println("返回主頁<br>");
out.println("<br><a href =index.jsp>主頁</a>");
out.println("檢視訂單<br>");
out.println("<br><a href =lookOrderForm.jsp>檢視訂單</a>");
out.println("</body></html>");
}
catch(IOException exp){}
}
public void fail(HttpServletRequest request,HttpServletResponse response,
String backNews) {
response.setContentType("text/html;charset=GB2312");
try {
PrintWriter out=response.getWriter();
out.println("<html><body>");
out.println("<h2>"+backNews+"</h2>") ;
out.println("返回主頁:");
out.println("<a href =index.jsp>主頁</a>");
out.println("</body></html>");
}
catch(IOException exp){}
}
}
對應第二張截圖,主要用來判斷能不能生成訂單,並將資訊插入到資料庫。程式碼通俗易懂,不做解釋。
lookOrderForm.jsp:
<%@ page contentType="text/html;charset=GB2312" %>
<jsp:useBean id="loginBean" class="mybean.data.Login" scope="session"/>
<%@ page import="java.sql.*" %>
<HTML><HEAD><%@ include file="head.txt" %></HEAD>
<BODY background=image/back.jpg>
<div align="center">
<% if(loginBean==null){
response.sendRedirect("login.jsp");//重定向到登入頁面
}
else {
boolean b =loginBean.getLogname()==null||
loginBean.getLogname().length()==0;
if(b)
response.sendRedirect("login.jsp");//重定向到登入頁面
}
Connection con;
Statement sql;
ResultSet rs;
try{ Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e){}
try { String uri= "jdbc:mysql://127.0.0.1:3306/shop";
String user="root";
String password="123456";
con=DriverManager.getConnection(uri,user,password);
sql=con.createStatement();
String cdn=
"SELECT id,mess,sum FROM orderform where logname= '"+loginBean.getLogname()+"'";
rs=sql.executeQuery(cdn);
out.print("<table border=2>");
out.print("<tr>");
out.print("<th width=100>"+"訂單號");
out.print("<th width=100>"+"資訊");
out.print("<th width=100>"+"價格");
out.print("</TR>");
while(rs.next()){
out.print("<tr>");
out.print("<td >"+rs.getString(1)+"</td>");
out.print("<td >"+rs.getString(2)+"</td>");
out.print("<td >"+rs.getString(3)+"</td>");
out.print("</tr>") ;
}
out.print("</table>");
con.close();
}
catch(SQLException e){
out.print(e);
}
%>
</div">
</BODY></HTML>
這裡就是簡單的顯示,從資料庫把插入的拿出來,再顯示,比較簡單。
這裡比較簡單,看程式碼就會明白。
這裡比較簡單,看程式碼就會明白。