您的位置:首页 > Web前端 > JavaScript

jsp web之路 jsp总结 通过cookie实现浏览记录展示功能

2018-01-10 22:44 513 查看
功能:浏览商品数据,显示浏览记录,商品存于数据库中。商品属性为id name city price number

一、链接数据库 DBHelper.java

package util;

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

public class DBHelper {
private static final String driver = "com.mysql.jdbc.Driver";
private static final String username = "root"; //数据库用户名
private static final String password = "123456";  //数据库密码
private static final String url = "jdbc:mysql://localhost:3306/shopping"; //库名shopping

private static Connection conn = null;
// 静态代码块加载驱动
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

//获得数据库的链接
public static Connection getConnection() {
if (conn == null) {
try {
conn = DriverManager.getConnection(url, username, password);
return conn;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return conn;
}

//测试数据库接连
public static void main(String[] args) {
if(DBHelper.getConnection()!=null){
System.out.println("ok");
}else{
System.out.println("failed");
}
}
}

运行结果:

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
ok

最新的driver已经改变,修改driver

private static final String driver = "com.mysql.cj.jdbc.Driver";


运行结果:java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone.

java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:695)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:663)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:653)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:638)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:606)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:624)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:620)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:69)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1663)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:662)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:352)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:221)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at util.DBHelper.getConnection(DBHelper.java:28)
at util.DBHelper.main(DBHelper.java:40)failed

Caused by: com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:54)
at com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:73)
at com.mysql.cj.jdbc.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:118)
at com.mysql.cj.mysqla.MysqlaSession.configureTimezone(MysqlaSession.java:315)
at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:2446)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1797)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1653)
... 7 more


时区不对,修改数据库链接url

private static final String url = "jdbc:mysql://localhost:3306/shopping?serverTimezone=UTC";

再运行 ok

二、创建商品信息实体类

package entity;

public class Items {
private int id;
private String name;
private String city;
private int price;
private int number;
private String picture;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}

}


三、创建业务类,从数据库中获得所有商品信息

package com.DAO;

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

import entity.Items;
import util.DBHelper;

public class ItemsDAO {
Connection conn=null;
ResultSet rs=null;
PreparedStatement stmt=null;
ArrayList<Items> list=new ArrayList<Items>(); //保存所有的商品

public ArrayList<Items> getAllItems(){
String sql="select * from items;";
try {
conn=DBHelper.getConnection();//创建数据库链接
stmt=conn.prepareStatement(sql); //创建链接对象
rs=stmt.executeQuery(); //执行获得数据集

while(rs.next()){
Items item = new Items();

item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setCity(rs.getString("city"));
list.add(item);
}
return list;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}finally {
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rs=null;
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stmt=null;
}
}
}
}


四、创建jsp页面显示商品信息

<%@page import="entity.Items"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<jsp:useBean id="itemsDAO" class="com.DAO.ItemsDAO" />
<jsp:useBean id="items" class="entity.Items" />
<body>
<%
ArrayList<Items> getitems = new ArrayList<Items>();
getitems = itemsDAO.getAllItems();
for (int i = 0; i < getitems.size(); i++) {
items = getitems.get(i);
}
%>
<a href="detail.jap?id=<%=items.getId() %>">
商品名称:<%=items.getName()%><br></a>
商品数量:<%=items.getNumber()%><br>
商品价格:<%=items.getPrice()%><br>
商品产地:<%=items.getCity()%><br><hr>

</body>
</html>


以上页面运行后,只显示了排序在最后的商品信息,需要将商品显示信息内容写在循环体内,修改后为

<%@page import="entity.Items"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<jsp:useBean id="itemsDAO" class="com.DAO.ItemsDAO" />
<jsp:useBean id="items" class="entity.Items" />
<body>
<%
ArrayList<Items> getitems = new ArrayList<Items>();
getitems = itemsDAO.getAllItems();
for (int i = 0; i < getitems.size(); i++) {
items = getitems.get(i);
%>
<a href="detail.jap?id=<%=items.getId() %>">
商品名称:<%=items.getName()%><br></a>
商品数量:<%=items.getNumber()%><br>
商品价格:<%=items.getPrice()%><br>
商品产地:<%=items.getCity()%><br><hr	>
<%
}  //主要这个位置,循环体的花括号是可以分的
%>

</body>
</html>

三、将浏览的商品信息存入cookie中,在detail.jsp中追加内容

<!-- 获得的id保存进入cookie,会获得一系列的id,所以将id都存入一条字符串中,然后将这符串存入cookie -->
<%
String idlist = "";
Cookie idcookie = null;
//获得已存在的记录
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie c : cookies) {
if (c.getName().equals("id_list_cookie")) {
//将新的id追加进已存在记录中
idlist = c.getValue() + request.getParameter("id") + "/";
}
idcookie = new Cookie("id_list_cookie", idlist);
response.addCookie(idcookie);
}

}
%>
四、修改ItemsDAO类,获得cookie的id值,通过id查询商品信息,追加内容

/**
* 获得cookie中的所有id并查询记录
*/
public ArrayList<Items> getItemByCookie(String idlist){

ArrayList<Items> itemslist = new ArrayList<Items>();
Items item = new Items();
System.out.println(idlist);
if(idlist!=null){
String[] ids = idlist.split("/");
for (int i=ids.length-1;i>=0;i--) {
item = getItemById(Integer.parseInt(ids[i]));
itemslist.add(item);
}
return itemslist;
}else{
return null;
}

}


五、detail.jsp中追加通过cookie里的id序列获得浏览商品信息,追加内容

<%-- 	读取cookie获得浏览记录id:<%=ids%> --%>
<p>
<hr>
以下是浏览记录
<%
ArrayList<Items> array_list_items = new ArrayList<Items>();
array_list_items = itemsDAO.getItemByCookie(idlist);
for (Items i : array_list_items) {
%>
<div>

<p>商品名称:<%=i.getName() %>
</div>
<%
}

%>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: