近日写了一个简单的网上书店系统与大家共享:
实例包含两个JSP文件:index.jsp和login.jsp
5个JavaBean:User.java BookDetails.java BookDB.java CookieApply.java ParamUtils.java
我的目录结构如图:
index.jsp文件源码:
<%--下面三行解决中文乱码问题--%>
<%@page pageEncoding="gb2312"%>
<%@page contentType="text/html; charset=gb2312"%>
<%request.setCharacterEncoding("gb2312");%>
<%@ page import="book.ParamUtils,book.bookstore.*,java.util.*"%>
<%--实例化CookieApply类,关于Cookie的操作在此类中--%>
<jsp:useBean id="cookieApply" scope="session" class="book.bookstore.CookieApply" />
<%
//如果是第一次访问本站点,重定向至登录页面
if(cookieApply.isFirstAccess(request)){
response.sendRedirect("login.jsp");
return;
}
//doOrder的值来自表单的隐藏域,用来判断用户是否提交了表单
boolean doOrder=ParamUtils.getBooleanParameter(request,"doOrder");
if(doOrder) {
//将用户定购的书籍存入cookie
cookieApply.orderBooks(request,response);
}
//获得用户对象
User user=cookieApply.getUser();
%>
<HTML>
<HEAD>
<TITLE>Cookie实例-网上书店购物系统</TITLE>
</HEAD>
<BODY>
<H2>Cookie实例-网上书店购物系统</H2>
<HR>
<%=user.getUsername()%>,您好!欢迎光临本店。<br>
<FORM name="orderForm" method="get">
<input type="hidden" name=doOrder value=true>
<br><font size="4" color="red">第一类</font><br>
<INPUT type="checkbox" name=bookID value=11>JSP程序设计
<INPUT type="checkbox" name=bookID value=12>Linux入门与提高
<INPUT type="checkbox" name=bookID value=13>计算机网络
<br><font size="4" color="red">第二类</font><br>
<INPUT type="checkbox" name=bookID value=14>鲁迅全集
<INPUT type="checkbox" name=bookID value=15>古文观止
<INPUT type="checkbox" name=bookID value=16>*的葬礼
<br><font size="4" color="red">第三类</font><br>
<INPUT type="checkbox" name=bookID value=17>大学物理
<INPUT type="checkbox" name=bookID value=18>核物理
<INPUT type="checkbox" name=bookID value=19>有机化学
<INPUT type="checkbox" name=bookID value=20>无机化学
<br>
<INPUT type="submit" value="定购">
</FORM>
<H3>您曾经在本店定购过下列图书:</H3>
<%
//迭代显示用户曾经定购过的图书
Iterator iter=user.getBookOrdered();
while(iter.hasNext()){
BookDetails book=(BookDetails)iter.next();
out.println(book.getBookName()+"<BR>");
}
%>
</BODY>
</HTML>
login.jsp文件源代码:
<%--下面三行解决中文乱码问题--%>
<%@page pageEncoding="gb2312"%>
<%@page contentType="text/html; charset=gb2312"%>
<%request.setCharacterEncoding("gb2312");%>
<%@ page import="book.ParamUtils"%>
<jsp:useBean id="cookieApply" scope="session" class="book.bookstore.CookieApply" />
<%
//注意此处使用ParamUtils.java类获取表单数据
boolean doLogin=ParamUtils.getBooleanParameter(request,"doLogin");
String username=ParamUtils.getParameter(request,"username");
String password=ParamUtils.getParameter(request,"password");
String useremail=ParamUtils.getParameter(request,"useremail");
if(doLogin && username!=null){ //用户提交了表单,且用户名不为空
//将用户名、密码、邮箱地址写入Cookie
cookieApply.login(response,username,password,useremail);
//进入index.jsp页面
response.sendRedirect("index.jsp");
//必须从此处返回,否则重定向会失败
return;
}
%>
<HTML>
<HEAD>
<TITLE>Cookie实例-网上书店购物系统</TITLE>
</HEAD>
<BODY>
<H2>Cookie实例-网上书店购物系统</H2>
<H3>欢迎您第一次来到网上书店定购系统</H3>
请您填写名字、密码及邮箱地址<br>
<FORM name="loginForm" method="post">
<input type="hidden" name=doLogin value=true>
姓 名:<INPUT type="text" name="username"><br>
密 码:<INPUT type="password" name="password"><br>
email:<INPUT type="text" name="useremail"><br>
<INPUT name="login" type=submit value=登录>
</FORM>
</BODY>
</HTML>
BookDetails.java源代码:
package book.bookstore;
public class BookDetails {
private String bookID;
private String bookName;
public BookDetails(String bookID,String bookName){
this.bookID=bookID;
this.bookName=bookName;
}
public String getBookID(){
return bookID;
}
public String getBookName(){
return bookName;
}
}
BookDB.java源代码:
package book.bookstore;
import java.util.*;
/**
* 图书类,存放本站点的所有图书
*/
public class BookDB {
private ArrayList books;
//构造函数,把所有图书放入books链表
public BookDB(){
books=new ArrayList();
BookDetails book;
book=new BookDetails("11","JSP应用开发技术");
books.add(book);
book=new BookDetails("12","Linux入门与提高");
books.add(book);
book=new BookDetails("13","计算机网络");
books.add(book);
book=new BookDetails("14","鲁迅全集");
books.add(book);
book=new BookDetails("15","古文观止");
books.add(book);
book=new BookDetails("16","*的葬礼");
books.add(book);
book=new BookDetails("17","大学物理");
books.add(book);
book=new BookDetails("18","核物理");
books.add(book);
book=new BookDetails("19","有机化学");
books.add(book);
book=new BookDetails("20","无机化学");
books.add(book);
}
/*
* 根据bookID,得到BookDeatils对象
*/
public BookDetails getBook(String bookID){
if(bookID==null) return null;
for(Iterator iter=books.iterator();iter.hasNext();){
BookDetails book=(BookDetails)iter.next();
if((book.getBookID()).equals(bookID)){
return book;
}
}
return null;
}
}
CookieApply.java源代码:
package book.bookstore;
import javax.servlet.http.*;
import java.util.*;
/*
* Cookie操作类,该类封装了对Cookie操作,并负责维护User对象。
*/
public class CookieApply {
private static int expireTime = 30* 24 * 60 * 60;//Cookie的有效时间为一个月
private User user;
public User getUser(){
return user;
}
/*
* 根据Cookie判断用户是否第一次访问,如果不是第一次访问,取出Cookie内记录的用户信息,
* 并根据这些信息实例化User类
*/
public boolean isFirstAccess(HttpServletRequest request){
String username =getCookieValue(request.getCookies(),"username",null);
String password =getCookieValue(request.getCookies(),"password",null);
String useremail=getCookieValue(request.getCookies(),"useremail",null);
if(username!=null){ //username不为空,说明用户不是第一次访问
user=new User(username,password,useremail);
//将定购过的图书信息从Cookie中取出,放入user对象内
String booksIDOrdered=getCookieValue(request.getCookies(),"booksID",null);
if(booksIDOrdered!=null){
String[] booksID=booksIDOrdered.split("-");
booksOrdered(booksID);
}
return false;
}
return true;
}
/*
* 用户登录,将用户信息写入Cookie,并实例化User类
*/
public void login(HttpServletResponse response, String username,
String password,String useremail)
{
saveCookie(response,"username",username);
saveCookie(response,"password",password);
saveCookie(response,"useremail",useremail);
user=new User(username,password,useremail);
}
/*
* 写Cookie的通用方法
*/
public void saveCookie(HttpServletResponse response, String name,
String value)
{
// Check to make sure the new value is not null (appservers like Tomcat
// 4 blow up if the value is null).
if (value == null) {
value = "";
}
//将值存入Cookie前,使用chineseToUnicode()方法转换编码,解决中文问题
Cookie cookie = new Cookie(name, chineseToUnicode(value));
cookie.setMaxAge(expireTime);
cookie.setPath("/");
response.addCookie(cookie);
}
/*
* 读Cookie的通用方法
*/
public String getCookieValue(Cookie[] cookies,String cookieName,String defaultValue)
{
if(cookies==null) return(defaultValue);
for(int i=0; i<cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
//返回Cookie值前,使用chineseToUnicode()方法转换编码,解决中文问题
return(unicodeToChinese(cookie.getValue()));
}
return(defaultValue);
}
/*
* 将用户定购的图书写入Cookie。
*/
public void orderBooks(HttpServletRequest request,HttpServletResponse response){
String[] booksID=request.getParameterValues("bookID");
if(booksID==null) return;
BookDB bookDB=new BookDB();
for(int i=0;i<booksID.length;i++){
String bookID=booksID[i];
BookDetails book=bookDB.getBook(bookID);
//更新用户的历史定购信息
user.addBookOrdered(book);
}
//将用户曾经定购图书写入Cookie:图书ID转换类似"1-12-13-18...."的形式存入Cookie
String booksIDOrdered="";
Iterator books=user.getBookOrdered();
while (books.hasNext()){
BookDetails bookOrdered=(BookDetails)books.next();
booksIDOrdered=booksIDOrdered + "-" + bookOrdered.getBookID();
}
saveCookie(response,"booksID",booksIDOrdered);
}
//把图书放到用户的历史定购链表中
public void booksOrdered(String[] booksID){
BookDB bookDB=new BookDB();
for(int i=0;i<booksID.length;i++){
String bookID=booksID[i];
BookDetails book=bookDB.getBook(bookID);
user.addBookOrdered(book);
}
}
/*
* 将Unicode编码转换为汉字编码,解决汉字乱码问题
*/
public String unicodeToChinese(String unicodeStr) {
if(unicodeStr==null) return null;
try{
unicodeStr = new String(unicodeStr.getBytes("ISO8859_1"), "gb2312");
return unicodeStr;
}catch(Exception e){
return null;
}
}
/*
* 将汉字编码转换为Unicode编码,解决汉字乱码问题
*/
public String chineseToUnicode(String chineseStr) {
if(chineseStr==null) return null;
try{
chineseStr = new String(chineseStr.getBytes("gb2312"), "ISO8859_1");
return chineseStr;
}catch(Exception e){
return null;
}
}
}
User.java源代码:
package book.bookstore;
import java.util.*;
/**
* 用户类
*/
public class User {
private String username=null;
private String password=null;
private String useremail=null;
private boolean isFirstAccess=true;
//用户访定购过的图书
private ArrayList booksOrdered=new ArrayList();
//构造函数
public User(String username,String password,String useremail){
this.username=username;
this.password=password;
if(password==null) password="";
this.useremail=useremail;
if(useremail==null) useremail="";
}
public String getUsername(){
return username;
}
public void setUsername(String username){
this.username=username;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password=password;
}
public String getUseremail(){
return useremail;
}
public void setUseremail(String useremail){
this.useremail=useremail;
}
//把定购的图书放到链表(booksOrdered)中
public void addBookOrdered(BookDetails book){
if(book==null) return;
for(Iterator iter=booksOrdered.iterator();iter.hasNext();){
BookDetails viewedBook=(BookDetails)iter.next();
if((viewedBook.getBookID()).equals(book.getBookID()))
return;
}
booksOrdered.add(book);
}
//获取booksOrdered变量的迭代子
public Iterator getBookOrdered(){
return booksOrdered.iterator();
}
}
ParamUtils.java源代码:
package book;
import javax.servlet.http.*;
public class ParamUtils {
/**
* Gets a parameter as a string.
* @param request The HttpServletRequest object, known as "request" in a
* JSP page.
* @param name The name of the parameter you want to get
* @return The value of the parameter or null if the parameter was not
* found or if the parameter is a zero-length string.
*/
public static String getParameter(HttpServletRequest request, String name) {
return getParameter(request, name, false);
}
/**
* Gets a parameter as a string.
* @param request The HttpServletRequest object, known as "request" in a
* JSP page.
* @param name The name of the parameter you want to get
* @param emptyStringsOK Return the parameter values even if it is an empty string.
* @return The value of the parameter or null if the parameter was not
* found.
*/
public static String getParameter(HttpServletRequest request,
String name, boolean emptyStringsOK)
{
String temp = request.getParameter(name);
if (temp != null) {
if (temp.equals("") && !emptyStringsOK) {
return null;
}
else {
return temp;
}
}
else {
return null;
}
}
/**
* Gets a parameter as a boolean.
* @param request The HttpServletRequest object, known as "request" in a
* JSP page.
* @param name The name of the parameter you want to get
* @return True if the value of the parameter was "true", false otherwise.
*/
public static boolean getBooleanParameter(HttpServletRequest request,
String name)
{
return getBooleanParameter(request, name, false);
}
/**
* Gets a parameter as a boolean.
* @param request The HttpServletRequest object, known as "request" in a
* JSP page.
* @param name The name of the parameter you want to get
* @return True if the value of the parameter was "true", false otherwise.
*/
public static boolean getBooleanParameter(HttpServletRequest request,
String name, boolean defaultVal)
{
String temp = request.getParameter(name);
if ("true".equals(temp) || "on".equals(temp)) {
return true;
}
else if ("false".equals(temp) || "off".equals(temp)) {
return false;
}
else {
return defaultVal;
}
}
/**
* Gets a parameter as an int.
* @param request The HttpServletRequest object, known as "request" in a
* JSP page.
* @param name The name of the parameter you want to get
* @return The int value of the parameter specified or the default value if
* the parameter is not found.
*/
public static int getIntParameter(HttpServletRequest request,
String name, int defaultNum)
{
String temp = request.getParameter(name);
if(temp != null && !temp.equals("")) {
int num = defaultNum;
try {
num = Integer.parseInt(temp);
}
catch (Exception ignored) {}
return num;
}
else {
return defaultNum;
}
}
/**
* Gets a list of int parameters.
* @param request The HttpServletRequest object, known as "request" in a
* JSP page.
* @param name The name of the parameter you want to get
* @param defaultNum The default value of a parameter, if the parameter
* can't be converted into an int.
*/
public static int[] getIntParameters(HttpServletRequest request,
String name, int defaultNum)
{
String[] paramValues = request.getParameterValues(name);
if (paramValues == null) {
return null;
}
if (paramValues.length < 1) {
return new int[0];
}
int[] values = new int[paramValues.length];
for (int i=0; i<paramValues.length; i++) {
try {
values[i] = Integer.parseInt(paramValues[i]);
}
catch (Exception e) {
values[i] = defaultNum;
}
}
return values;
}
/**
* Gets a parameter as a double.
* @param request The HttpServletRequest object, known as "request" in a
* JSP page.
* @param name The name of the parameter you want to get
* @return The double value of the parameter specified or the default value
* if the parameter is not found.
*/
public static double getDoubleParameter(HttpServletRequest request,
String name, double defaultNum)
{
String temp = request.getParameter(name);
if(temp != null && !temp.equals("")) {
double num = defaultNum;
try {
num = Double.parseDouble(temp);
}
catch (Exception ignored) {}
return num;
}
else {
return defaultNum;
}
}
/**
* Gets a parameter as a long.
* @param request The HttpServletRequest object, known as "request" in a
* JSP page.
* @param name The name of the parameter you want to get
* @return The long value of the parameter specified or the default value if
* the parameter is not found.
*/
public static long getLongParameter(HttpServletRequest request,
String name, long defaultNum)
{
String temp = request.getParameter(name);
if (temp != null && !temp.equals("")) {
long num = defaultNum;
try {
num = Long.parseLong(temp);
}
catch (Exception ignored) {}
return num;
}
else {
return defaultNum;
}
}
/**
* Gets a list of long parameters.
* @param request The HttpServletRequest object, known as "request" in a
* JSP page.
* @param name The name of the parameter you want to get
* @param defaultNum The default value of a parameter, if the parameter
* can't be converted into a long.
*/
public static long[] getLongParameters(HttpServletRequest request,
String name, long defaultNum)
{
String[] paramValues = request.getParameterValues(name);
if (paramValues == null) {
return null;
}
if (paramValues.length < 1) {
return new long[0];
}
long[] values = new long[paramValues.length];
for (int i=0; i<paramValues.length; i++) {
try {
values[i] = Long.parseLong(paramValues[i]);
}
catch (Exception e) {
values[i] = defaultNum;
}
}
return values;
}
/**
* Gets a parameter as a string.
* @param request The HttpServletRequest object, known as "request" in a
* JSP page.
* @param name The name of the parameter you want to get
* @return The value of the parameter or null if the parameter was not
* found or if the parameter is a zero-length string.
*/
public static String getAttribute(HttpServletRequest request, String name) {
return getAttribute (request, name, false);
}
/**
* Gets a parameter as a string.
* @param request The HttpServletRequest object, known as "request" in a
* JSP page.
* @param name The name of the parameter you want to get
* @param emptyStringsOK Return the parameter values even if it is an empty string.
* @return The value of the parameter or null if the parameter was not
* found.
*/
public static String getAttribute(HttpServletRequest request,
String name, boolean emptyStringsOK)
{
String temp = (String)request.getAttribute(name);
if (temp != null) {
if (temp.equals("") && !emptyStringsOK) {
return null;
}
else {
return temp;
}
}
else {
return null;
}
}
/**
* Gets an attribute as a boolean.
* @param request The HttpServletRequest object, known as "request" in a
* JSP page.
* @param name The name of the attribute you want to get
* @return True if the value of the attribute is "true", false otherwise.
*/
public static boolean getBooleanAttribute(HttpServletRequest request,
String name)
{
String temp = (String)request.getAttribute(name);
if (temp != null && temp.equals("true")) {
return true;
}
else {
return false;
}
}
/**
* Gets an attribute as a int.
* @param request The HttpServletRequest object, known as "request" in a
* JSP page.
* @param name The name of the attribute you want to get
* @return The int value of the attribute or the default value if the
* attribute is not found or is a zero length string.
*/
public static int getIntAttribute(HttpServletRequest request,
String name, int defaultNum)
{
String temp = (String)request.getAttribute(name);
if (temp != null && !temp.equals("")) {
int num = defaultNum;
try {
num = Integer.parseInt(temp);
}
catch (Exception ignored) {}
return num;
}
else {
return defaultNum;
}
}
/**
* Gets an attribute as a long.
* @param request The HttpServletRequest object, known as "request" in a
* JSP page.
* @param name The name of the attribute you want to get
* @return The long value of the attribute or the default value if the
* attribute is not found or is a zero length string.
*/
public static long getLongAttribute(HttpServletRequest request,
String name, long defaultNum)
{
String temp = (String)request.getAttribute(name);
if (temp != null && !temp.equals("")) {
long num = defaultNum;
try {
num = Long.parseLong(temp);
}
catch (Exception ignored) {}
return num;
}
else {
return defaultNum;
}
}
}