1. 程式人生 > >動態生成頁面(從資料庫中動態取出資料資訊生成頁面)

動態生成頁面(從資料庫中動態取出資料資訊生成頁面)

做課程設計的時候  做的有點煩了  所以就簡單的寫了點 以下就是將新增到購物車的商品動態的顯示到前臺頁面的程式碼

首先是我的head.jsp這裡面的“我的目錄“使用的不是直接連結而是一個servlet名稱叫做”selectUserCart“

我的裡面使用的user、books、userAccout類都是基本的記錄了基本資訊的類為其實現setXxx()和getXxx()方法

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link rel="stylesheet" type="text/css" href="style.css" />


  </head>
  
  <body >
  
  <div id="wrap" >
  <%
  
  		 if(session.getAttribute("username") == null) {
  
  %>
  <br/>你還沒有登入請<a href="login.jsp">登陸</a>/<a href="register.jsp">註冊</a>以檢視或購買 
  <%
  			}else{
  			
  		%>
  		<br/>您好!<%=session.getAttribute("username") %>
  	<% 
  		}
   %>
      <div class="header">
      
      <!-- <br/>你還沒有登入請<a href="login.jsp">登陸</a>/<a href="register.jsp">註冊</a>以檢視或購買 -->
    <div class="logo"><a href="index.htm"><img src="images/logo.gif" alt="" title="" border="0" /></a></div>
    <div id="menu">
      <ul>
        <li class="selected"><a href="index.jsp">主頁</a></li>
        <li><a href="about.jsp">關於我們</a></li>
        <li><a href="category">圖書</a></li>
        <li><a href="specials.jsp">特別推薦</a></li>
        <li><a href="selectUserCart">我的目錄</a></li>
        <li><a href="register.jsp">註冊</a></li>
        <li><a href="contact.jsp">購買</a></li>
        
      </ul>
    </div>
  </div>
  </div>
  </body>
</html>
然後是我使用到的兩個類:
搜尋我的購物車的工具類:myCartUtil.java
<pre name="code" class="java">package myCart;



import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;


import bookConnUtil.DBUtil;
import bookConnUtil.books;

public class myCartUtil {
	public static ArrayList<mycart> list = new ArrayList<mycart>();
	public static ArrayList<books> booklist = new ArrayList<books>();
	public static String msg;
	public static int countbook = 0;
	//public static  mycart[] cart = new mycart[10];
	public static int count = 0;
	public static boolean insertIntoMyCart(String username,String bookname,String pianduanName) throws SQLException{
		
		String cartInsert = "insert into userAccount valus(?,?,?)";
		boolean flag = false;
		Connection conn=null;
		PreparedStatement stmt=null;
		try{
			
			conn = DBUtil.getConnection(DBUtil.CONNECTION_SQL);
			
			stmt = conn.prepareStatement(cartInsert);
			stmt.setString(1, username);
			stmt.setString(2, bookname);
			stmt.setString(3, pianduanName);
			int count = stmt.executeUpdate();
			if(count>0){
				flag=true;
			}else{
				flag=false;
			}
			
			
			
		}catch(Exception e){
			System.out.println("真心對不住,您的程式出錯了");
			e.printStackTrace();
			
		}finally{
			conn.close();
			stmt.close();
			
		}
		return flag;
		
	}
	public static boolean selectUserCart(String userName) throws SQLException{
		boolean flag = false;
		String cartSelect = "select username,bookname,pianduanName,imagePath,price from userAccount where username =?";
		Connection conn=null;
		ResultSet rs=null;
		PreparedStatement stmt=null;
		try{
			
			conn = DBUtil.getConnection(DBUtil.CONNECTION_SQL);
			
			stmt = conn.prepareStatement(cartSelect);
			stmt.setString(1, userName);
			rs = stmt.executeQuery();
			
			
			
			
			while(rs.next()){
				
					mycart cart = new mycart();
					cart.setUserName(rs.getString(1));
					cart.setBookName(rs.getString(2));
					cart.setPianduanName(rs.getString(3));
					cart.setImagePath(rs.getString(4));
					cart.setPrice(rs.getInt(5));
					list.add(cart);
					count++;
					
					
				}
			System.out.println("++++++++++++++++"+count+"+++++++++++++");
			if(count==0){
				msg = "null";
			}else{
				msg = "full";
			}
			flag = true;
			
		
		}catch(Exception e){
			System.out.println("真心對不起,你的程式出錯了");
			e.printStackTrace();
			
		}finally{
			conn.close();
			stmt.close();
			
		}
		
		return flag ;
	}
	public static boolean selectAllBooks() throws SQLException{
		boolean flag = false;
		String cartSelect = "select bookId,bookName,pianduanName,imagesPath,price from books";
		Connection conn=null;
		ResultSet rs=null;
		PreparedStatement stmt=null;
		try{
			
			conn = DBUtil.getConnection(DBUtil.CONNECTION_SQL);
			
			stmt = conn.prepareStatement(cartSelect);
			
			rs = stmt.executeQuery();
			
			
			
			
			while(rs.next()){
				
					books book = new books();
					book.setBookID(rs.getString(1));
					book.setBookName(rs.getString(2));
					book.setPianduanName(rs.getString(3));
					book.setImagePath(rs.getString(4));
					book.setPrice(rs.getInt(5));
					booklist.add(book);
<span style="white-space:pre">					</span>//我沒怎麼好好做所以就用這個標記的 想要做的更好點請自行實現
					countbook++;
					
					
				}
			System.out.println("++++++++++++++++"+count+"+++++++++++++");
			if(count==0){
				msg = "null";
			}else{
				msg = "full";
			}
			flag = true;
			
		
		}catch(Exception e){
			System.out.println("真心對不起,你的程式出錯了");
			e.printStackTrace();
			
		}finally{
			conn.close();
			stmt.close();
			
		}
		
		return flag ;
	}
}

下面是實現資料庫連線類:
<pre name="code" class="java">package bookConnUtil;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class DBUtil {
	public static final int CONNECTION_MYSQL=2;
	public static final int CONNECTION_SQL=1;
	public static final int CONNECTION_ODBC=0;
	public DBUtil() {	}
	public static Connection getConnection(int connection_type)throws Exception
	{
		switch (connection_type)
		{
			case CONNECTION_ODBC:
				return getConnectionODBC();
			case CONNECTION_SQL:
				return getConnectionSQL();
			case CONNECTION_MYSQL:
				return getConnectionMYSQL();
		}
		return null;
	}
	
	/**
	 * �ر����Ӷ���
	 */
	private static Connection getConnectionODBC()throws Exception
	{
		Connection conn=null;
		try
		{
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			System.out.println("abc");
			conn=DriverManager.getConnection("jdbc:odbc:mybook","sa","123");
			System.out.println("連線成功");
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		return conn;
	}
	private static Connection getConnectionSQL() throws Exception
	{
		Connection conn=null;
		String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=user;";
		try
		{
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		
			conn=DriverManager.getConnection(connectionUrl,"sa","123");
			System.out.println("連線成功");
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		return conn;
	}
	private static Connection getConnectionMYSQL() throws Exception
	{
		String connectionUrl = "jdbc:mysql://localhost:3306/user"; 
		String username = "root"; 
		String password = "mysql"; 
		Connection conn=null;
		
		try
		{
			Class.forName("com.mysql.jdbc.Driver"); 
			
			conn=DriverManager.getConnection(connectionUrl, username,password);
			System.out.println("連線成功");
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		return conn;
		
	}
	public static void close(Connection conn) throws Exception
	{
		if(conn!=null)
		{
			try
			{
				conn.close();
			}
			catch(SQLException e)
			{
				e.printStackTrace();
				throw e;
			}
		}
	}
	
	
	

}

下面是實現使用者購物車搜尋類:
<pre name="code" class="java">package myCart;

import java.io.IOException;
import java.sql.SQLException;

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

import bookConnUtil.bookDAO;

public class selectUserCart extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public int count = myCartUtil.count;
	
	
	 


	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session=req.getSession();
		String username =(String) session.getAttribute("username");
		
		try {
			//System.out.println("還沒執行到查詢過程這裡");
			boolean flag=myCartUtil.selectUserCart(username);
			if(flag==true){
				/*for(mycart message:myCartUtil.list){
					for(int i=0;i<3;i++){
						String A = message.getUserName();
					}
				}*/
				//session.setAttribute("count",countNum);
				if(myCartUtil.msg.equals("null")){
					session.setAttribute("null", myCartUtil.msg);
				}else{
					session.setAttribute("full", myCartUtil.msg);
				}
				req.getRequestDispatcher("selectMyAcccount.jsp").forward(req, resp);
				
			}else{
				req.getRequestDispatcher("error.html").forward(req, resp);
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	

}

我的目錄實現程式碼:
<pre name="code" class="html"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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%>">
    
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <title>Book Store</title>
     <link rel="stylesheet" type="text/css" href="style.css" />


  </head>
  
  <body onload="selectUserCart">
  <jsp:include  page="head.jsp"/> 
    
    <div id="wrap">
    <div class="center_content">
    <div class="left_content">
          <%
       if(session.getAttribute("username") == null) {
        %>
         <script type="text/javascript" language="javascript">  
            alert("您還沒有登入,請登入...");  
            window.document.location.href="login.jsp";  
        </script> 
        <%
             }
          %>
      <div class="title"><span class="title_icon"><img src="images/bullet1.gif" alt="" title="" /></span>My account</div>
      <div class="feat_prod_box_details">
        <p class="details"> 我還沒有什麼時間進行修改,所以使用的是以前的版本這樣的話造成的不便請您諒解。所有權為作者所有我還沒有什麼時間進行修改,所以使用的是以前的版本這樣的話造成的不便請您諒解。所有權為作者所有我還沒有什麼時間進行修改,所以使用的是以前的版本這樣的話造成的不便請您諒解。所有權為作者所有我還沒有什麼時間進行修改,所以使用的是以前的版本這樣的話造成的不便請您諒解。所有權為作者所有 </p>
        <div class="contact_form">
          <div class="form_subtitle">登陸 以檢視清單</div>
          <form name="register" method="post" action="UserDAO">
            <div class="form_row">
              <label class="contact"><strong>使用者名稱:</strong></label>
              <input type="text" class="contact_input" name="userName" />
            </div>
            <div class="form_row">
              <label class="contact"><strong>密  碼:</strong></label>
              <input type="password" class="con tact_input" name="password" />
            </div>
            <div class="form_row">
              <div class="terms">
                <input type="checkbox" name="terms" />
                	記住密碼 </div>
            </div>
            <div class="form_row">
              <input type="submit" class="register" value="登陸" />
            </div>
          </form>
        </div>
        <div class="contact_form">
          <div class="form_subtitle">更新書籍資訊</div>
          <form name="updateBookMsg" method="post" action="updateBookMsg">
            <div class="form_row">
              <label class="contact"><strong>圖  書ID:</strong></label>
              <input type="text" class="contact_input" name="bookId" />
            </div>
            <div class="form_row">
              <label class="contact"><strong>圖 書 名:</strong></label>
              <input type="text" class="contact_input" name="bookName" />
            </div>
            <div class="form_row">
              <label class="contact"><strong>圖書簡介:</strong></label>
              <input type="text" class="contact_input" name="pianduanName" />
            </div>
           
            <div class="form_row">
              <input type="submit" class="register" value="提交" />
            </div>
          </form>
        </div>
        
      </div>
      <div class="clear"></div>
    </div>
    <jsp:include  page="broadside.jsp"/> 
    </div>
    </div>
  </body>
</html>