升入本科之后又学了一遍Jsp(jsp+servlet+javaBean),虽然之前没好好学,但对于课程中的各种技术还是有些面熟的。同时,作为一个考查的课程,老师还是教的蛮细心的,嗯,没白来。。。。。。
技术不用就会荒废,纸上得来终觉浅,绝知此事要躬行。
最近寻思着做一个小项目,回顾回顾所学的内容。。。。。。
化妆品销售网:myEclipse开发工具、JSP引擎为Tomcat 8.0,系统采用MVC模式实现各个模块,数据库使用MySQL(需要连接jar包)。
系统模块的构成:注册、登录、购物车、浏览化妆品、查询化妆品、确认订单、查询订单、退出登录。
数据库设计
建立数据库shop,其中包含四个表:user表、classify表、cosmeticForm表、orderForm表。
- user表:用于存储用户的注册信息,字段值:logname(主键)(存储注册的用户名)、password(存储密码)、 phone(存储电话)、address(存储地址)、realname(存储姓名)。
- classify表:对化妆品进行分类,存储化妆品类别,字段值:id(自增,主键)(化妆品的分类号 )、name(化妆品的分类 名称)。
- cosmeticForm表:存储化妆品信息,字段值:cosmetic_number(主键)(化妆品的产品标识号)、cosmetic_name(化妆品的名称)、cosmetic_made(化妆品的制造商)、cosmetic_price(化妆品的价格)、cosmetic_mess(化妆品产品介绍)、cosmetic_pic(主键)(存储和化妆品相关的一副图像文件的名字)、id(自增,外键)(作为classify表中id的外键)。
- orderForm表:存储订单信息,字段值:id(主键,自增)(存储订单序号)、logname(存储注册的用户名)、mess(订单信息)、sum(所选商品的价格总和)。
数据库连接:JDBC
String uri="jdbc://mysql://127.0.0.1/shop?"+"user=root&password=自己的密码&characterEncoding=utf-8";
Connection con=DriverManager.getConnection(uri);
导航条文件:head.jsp(其他页面使用<jsp:include page="head.jsp"/>包含导航条)
<body>
<div align="center">
<font color=red><h3>"青山绿水"化妆品销售网</h3></font>
<table cellSpacing="1" cellPadding="1" width="660" align="center" border="0">
<tr align="bottom">
<td><a href="index.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="login.jsp">登录</a></td>
<td><a href="inputRegisterMess.jsp">注册</a></td>
<td><a href="exitServlet">退出</a></td>
</tr>
</table>
</div>
<br><hr><br>
</body>
主页文件:index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><jsp:include page="head.jsp"/></head>
<body>
<title>首页</title>
<center>
<h1><font size=4 color=blue>
欢迎光临"青山绿水"化妆品销售网
</font></h1>
<img src="image/welcome.jpg" width=600 height=200/>
</center>
</body>
</html>
运行图:
配置Web服务目录文件:web.xml(系统的Servlet类的包名均为:myservlet.control)
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<servlet>
<servlet-name>registerServlet</servlet-name>
<servlet-class>myservlet.control.HandleRegister</servlet-class>
</servlet>
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>myservlet.control.HandleLogin</servlet-class>
</servlet>
<servlet>
<servlet-name>deleteServlet</servlet-name>
<servlet-class>myservlet.control.HandleDelete</servlet-class>
</servlet>
<servlet>
<servlet-name>buyServlet</servlet-name>
<servlet-class>myservlet.control.HandleBuyGoods</servlet-class>
</servlet>
<servlet>
<servlet-name>queryServlet</servlet-name>
<servlet-class>myservlet.control.QueryAllRecord</servlet-class>
</servlet>
<servlet>
<servlet-name>putGoodsServlet</servlet-name>
<servlet-class>myservlet.control.PutGoodsToCar</servlet-class>
</servlet>
<servlet>
<servlet-name>searchByConditionServlet</servlet-name>
<servlet-class>myservlet.control.SearchByCondition</servlet-class>
</servlet>
<servlet>
<servlet-name>exitServlet</servlet-name>
<servlet-class>myservlet.control.HandleExit</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>registerServlet</servlet-name>
<url-pattern>/registerServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>deleteServlet</servlet-name>
<url-pattern>/deleteServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>buyServlet</servlet-name>
<url-pattern>/buyServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>queryServlet</servlet-name>
<url-pattern>/queryServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>putGoodsServlet</servlet-name>
<url-pattern>/putGoodsServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>searchByConditionServlet</servlet-name>
<url-pattern>/searchByConditionServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>exitServlet</servlet-name>
<url-pattern>/exitServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
1、会员注册功能模块
(1)Model部分(JavaBean):Register.java文件
package mybean.data;
public class Register {
private String logname="";
private String phone="";
private String address="";
private String realname="";
private String backNews="请输入信息";
public String getLogname() {
return logname;
}
public void setLogname(String logname) {
this.logname = logname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public String getBackNews() {
return backNews;
}
public void setBackNews(String backNews) {
this.backNews = backNews;
}
}
(2)View部分(Jsp):inputRegisterMess.jsp文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!-- 功能:负责提交用户注册信息到HandleRegister 的servlet控制器,并负责显示注册是否成功 -->
<jsp:useBean id="userBean" class="mybean.data.Register" scope="request"/>
<head><jsp:include page="head.jsp"/></head>
<title>注册页面</title>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body background="image/back.jpg" style="color:white"><font size="3">
<div align="center">
<form action="registerServlet" method="post" name=form>
<table>
用户名由字母、数字、下划线组成,*注释的选项必须填写。
<br>
<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 property="backNews" name="userBean"/>
<table border="3">
<tr><td>会员名称:</td>
<td><jsp:getProperty property="logname" name="userBean"/></td>
</tr>
<tr><td>姓名:</td>
<td><jsp:getProperty property="realname" name="userBean"/></td>
</tr>
<tr><td>地址:</td>
<td><jsp:getProperty property="address" name="userBean"/></td>
</tr>
<tr><td>电话:</td>
<td><jsp:getProperty property="phone" name="userBean"/></td>
</tr>
</table>
</div>
</font>
</body>
</html>
(3)Control部分(Servlet):HandleRegister.java文件
package myservlet.control;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mybean.data.Register;
/**
*功能:接收inputRegisterMess.jsp提交的信息,注册用户
*/
public class HandleRegister extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
try{
Class.forName("com.mysql.jdbc.Driver");//加载mysql的jdbc驱动
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 汉字乱码处理
*/
public String handleString(String s){
try{
byte[] bb=s.getBytes("iso-8859-1");
s=new String(bb,"UTF-8");
}catch(Exception e){}
return s;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uri="jdbc:mysql://127.0.0.1/shop?"+"user=root&password=dpl1215&characterEncoding=utf-8";
Connection con;
PreparedStatement sql;
Register userBean=new Register();
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){//更新成功之后,将数据存到userBean中
backNews="注册成功,请登录!";
userBean.setBackNews(backNews);
userBean.setLogname(handleString(logname));
userBean.setPhone(handleString(phone));
userBean.setAddress(handleString(address));
userBean.setRealname(handleString(realname));
}
}
else{
backNews="您输入的信息不完整或用户名中有非法字符";
userBean.setBackNews(backNews);
}
con.close();
}catch(Exception e){
backNews="该会员名已被使用,请您更换名字"+e;
userBean.setBackNews(backNews);
}
//注册数据的页面显示
RequestDispatcher dispatcher=request.getRequestDispatcher("inputRegisterMess.jsp");
dispatcher.forward(request, response);
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
}
运行图:
2、会员登录功能模块
(1)Model部分(JavaBean):Login.java文件
package mybean.data;
import java.util.LinkedList;
//存储用户登录的信息
public class Login {
private String logname="";
private String backNews="未登录";
private LinkedList<String> car;//用户的购物车
public Login(){
car=new LinkedList<String>();
}
public String getLogname() {
return logname;
}
public void setLogname(String logname) {
this.logname = logname;
}
public String getBackNews() {
return backNews;
}
public void setBackNews(String backNews) {
this.backNews = backNews;
}
public LinkedList<String> getCar() {
return car;
}
}
(2)View部分(Jsp):login.jsp文件
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<jsp:useBean id="loginBean" class="mybean.data.Login" scope="session"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<jsp:include page="head.jsp"/>
</head>
<body background="image/login_back.jpg">
<font size=3>
<div align="center">
<table border="1">
<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>
<tr><td align="center"><input type="submit" name="g" value="提交" style="width: 60px"/></td></tr>
</form>
</table>
</div>
<div align="center">
登录信息反馈:<jsp:getProperty property="backNews" name="loginBean"/>
<br>账号:<jsp:getProperty property="logname" name="loginBean"/>
</div>
</font>
</body>
</html>
(3)Control部分(Servlet):HandleLogin.java文件
package myservlet.control;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
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 mybean.data.Login;
/**
* 功能:登录功能
*/
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,"UTF-8");
}catch(Exception e){}
return s;
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection con;
Statement sql;
String logname=request.getParameter("logname").trim();
String password=request.getParameter("password").trim();
logname=handleString(logname);
password=handleString(password);
String uri="jdbc:mysql://127.0.0.1/shop?"+"user=root&password=dpl1215&characterEncoding=utf-8";
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){
//调用登陆成功的方法
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(Exception e){
String backNews=""+e;
fail(request,response,logname,backNews);
}
}
private void fail(HttpServletRequest request, HttpServletResponse response,
String logname, String backNews) {
response.setContentType("text/html;charset=utf-8");
try{
PrintWriter out=response.getWriter();
out.println("<html><body>");
out.println("<h2>"+logname+"登陆反馈结果<br>"+backNews+"</h2>");
out.println("返回登录界面或主页<br>");
out.println("<a href=login.jsp>登录界面</a>");
out.println("<br><a href=index.jsp>主页</a>");
out.println("</body></html>");
}catch(Exception e){}
}
private void success(HttpServletRequest request,
HttpServletResponse response, String logname, String password) {
Login loginBean=null;
HttpSession session=request.getSession();
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 e){
loginBean=new Login();
session.setAttribute("loginBean", loginBean);
loginBean.setBackNews(logname+"登陆成功");
loginBean.setLogname(logname);
}
}
}
运行图:
3、浏览化妆品功能模块
(1)Model部分(JavaBean):DataByPage.java文件
package mybean.data;
import com.sun.rowset.CachedRowSetImpl;
/**
* 用于存储商品的数据库记录
*/
public class DataByPage {
CachedRowSetImpl rowSet=null; //存储表中全部记录的行集对象
private int pageSize=1; //每页显示的记录数
private int totalPages=1; //分页后的总页数
private int currentPage=1; //当前显示页
public void setRowSet(CachedRowSetImpl set){
rowSet=set;
}
public CachedRowSetImpl getRowSet(){
return rowSet;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
}
(2)View部分(Jsp):
lookCosmetic.jsp文件:(选择商品分类)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!-- 用于选择某个商品分类 -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<jsp:include page="head.jsp"/>
</head>
<body background="image/back.jpg">
<font size="3">
<div align="center">
<%
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){}
String uri="jdbc:mysql://127.0.0.1/shop?"+"user=root&password=dpl1215&characterEncoding=utf-8";
Connection con;
Statement sql;
ResultSet rs;
try{
con=DriverManager.getConnection(uri);
sql=con.createStatement();
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><input type='submit' value='提交'></form>");
con.close();
}catch(Exception e){
out.print(e);
}
%>
</div>
</font>
</body>
</html>
运行图:
byPageShow.jsp文件:(浏览选取的商品记录)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="mybean.data.DataByPage" %>
<%@ page import="com.sun.rowset.*" %>
<!-- 分页显示商品 -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<jsp:include page="head.jsp"/>
</head>
<jsp:useBean id="dataBean" class="mybean.data.DataByPage" scope="session"/>
<body background="image/back.jpg" style="color: white">
<font size="3">
<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 property="pageSize" name="dataBean" param="pageSize"/>
<jsp:setProperty property="currentPage" name="dataBean" 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+">"+ //隐藏hidden,提交时直接将其value的值提交
"<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 property="pageSize" name="dataBean"/>条信息
<br>当前显示第<font color=blue>
<jsp:getProperty property="currentPage" name="dataBean"/>
</font>页,共有
<font color=blue>
<jsp:getProperty property="totalPages" name="dataBean"/>
</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>
</font>
</body>
</html>
运行图:
showDetail.jsp文件:(商品详情页)
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<jsp:include page="head.jsp"/>
</head>
<jsp:useBean id="loginBean" class="mybean.data.Login" scope="session"/>
<body background="image/back.jpg" style="color: white">
<center>
<%
if(loginBean==null){
response.sendRedirect("login.jsp");//重定向到登录页面
}else{
boolean b=loginBean.getLogname()==null||loginBean.getLogname().length()==0;
if(b)
response.sendRedirect("login.jsp");
}
String numberID=request.getParameter("xijie");
out.print("<th>产品号"+numberID);
if(numberID==null){
out.print("没有产品号,无法查看细节!");
return;
}
Connection con;
Statement sql;
ResultSet rs;
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){}
String uri="jdbc:mysql://127.0.0.1/shop";
try{
con=DriverManager.getConnection(uri, "root", "dpl1215");
sql=con.createStatement();
rs=sql.executeQuery("select * from cosmeticForm where cosmetic_number='"+numberID+"'");
out.print("<table border=2>");
out.print("<tr>");
out.print("<th>产品号");
out.print("<th>名称");
out.print("<th>制造商");
out.print("<th>价格");
out.print("<th><font color=blue>放入购物车</font>");
out.print("</tr>");
String picture="welcome.jpg";
String detailMess=""; //产品详情
while(rs.next()){
String number=rs.getString(1);
String name=rs.getString(2);
String maker=rs.getString(3);
String price=rs.getString(4);
detailMess=rs.getString(5);
picture=rs.getString(6);
//便于购物车计算价格,尾缀上"#价格值"
String goods="("+number+","+name+","+maker+","+price+")#"+price;
goods=goods.replaceAll("\\p{Blank}", "");//用""代替空格或制表符(\\p{Blank})
String button="<form action='putGoodsServlet' method='post'>"+
"<input type='hidden' name='java' value= "+goods+">"+
"<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>"+button+"</td>");
out.print("</tr>");
}
out.print("</table>");
out.print("<br>产品详情:<br>");
out.println("<div align=center>"+detailMess+"</div><br>");
String pic="<img src='image/"+picture+"'width=260 height=200></img>";
out.print(pic);//产品图片
con.close();
}catch(Exception e){}
%>
</center>
</body>
</html>
运行图:
(3)Control部分(Servlet):
QueryAllRecord.java文件:(浏览提交分类商品的记录)
package myservlet.control;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletConfig;
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 com.sun.rowset.CachedRowSetImpl;
import mybean.data.DataByPage;
/**
* 功能:浏览商品记录
*/
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 destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String idNumber=request.getParameter("fenleiNumber");
if(idNumber==null)
idNumber="0";
int id=Integer.parseInt(idNumber);
HttpSession session=request.getSession();
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 e){
dataBean=new DataByPage();//创建JavaBean对象
session.setAttribute("dataBean", dataBean);
}
String uri="jdbc:mysql://127.0.0.1/shop";
try{
con=DriverManager.getConnection(uri, "root", "dpl1215");
Statement sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
//TYPE_SCROLL_SENSITIVE,双向滚动,并及时跟踪数据库的更新,以便更改ResultSet中的数据。
//ResultSet.CONCUR_READ_ONLY 不能用结果集更新数据库中的表。
ResultSet rs=sql.executeQuery("select * from cosmeticForm where id="+id);
rowSet=new CachedRowSetImpl();
rowSet.populate(rs);//填充结果集(CachedRowSetImpl代替ResultSet)
dataBean.setRowSet(rowSet);//行集数据存储在dataBean中
con.close();//关闭连接
}catch(Exception e){}
response.sendRedirect("byPageShow.jsp");//重定向byPageShow.jsp
}
}
PutGoodsToCar.java文件:(添加到购物车)
package myservlet.control;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import javax.servlet.ServletConfig;
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 mybean.data.Login;
/**
* 功能:商品添加到购物车
*/
public class PutGoodsToCar extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
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 e){}
}
private void speakSomeMess(HttpServletRequest request,
HttpServletResponse response, String goods) {
response.setContentType("text/html;charset=utf-8");
try{
PrintWriter out=response.getWriter();
out.print("<html><head>" +
"<div align='center'>" +
"<font color=red><h3>'青山绿水'化妆品销售网</h3></font> "+
"<table cellSpacing='1' cellPadding='1' width='660' align='center' border='0'>"+
"<tr align='bottom'>"+
"<td><a href='index.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='login.jsp'>登录</a></td>"+
"<td><a href='inputRegisterMess.jsp'>注册</a></td>"+
"<td><a href='exitServlet'>退出</a></td>"+
"</tr></table></div><br><hr><br></head>");
out.println("<body background='image/back.jpg' style='color:white'><center>");
out.println("<h2>商品已放入购物车</h2>");
out.println("查看购物车或返回浏览化妆品<br><br>");
out.println("<a href='lookShoppingCar.jsp'>查看购物车</a>");
out.println(" <a href='byPageShow.jsp'>浏览化妆品</a>");
out.println("</center></body></html>");
}catch(Exception e){}
}
}
运行图:
4、查看购物车功能模块
(1)Model部分(JavaBean):Login.java
(2)View部分(Jsp):lookShoppingCar.jsp文件
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!-- 查看购物车界面 (包含删除)-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<jsp:include page="head.jsp"/>
</head>
<jsp:useBean id="loginBean" class="mybean.data.Login" scope="session"/>
<body background="image/back.jpg" style="color:white">
<font size=3>
<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<String> 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>
(3)Control部分(Servlet):
HandleDelete.java文件(购物车删除功能)
package myservlet.control;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
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 mybean.data.Login;
/**
*功能:购物车商品删除
*/
public class HandleDelete extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String delete =request.getParameter("delete");
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.remove(delete);//删除商品
}catch(Exception e){
response.sendRedirect("login.jsp");
}
RequestDispatcher dispatcher=request.getRequestDispatcher("lookShoppingCar.jsp");
dispatcher.forward(request, response);
}
}
运行图:
HandleBuyGoods.java文件(生成订单功能)
package myservlet.control;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.LinkedList;
import javax.servlet.ServletConfig;
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 mybean.data.Login;
/**
* 功能:生成订单
*/
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 destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
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");//重定向到login.jsp
}catch(Exception e){
response.sendRedirect("login.jsp");
}
String uri="jdbc:mysql://127.0.0.1/shop?"+"user=root&password=dpl1215&characterEncoding=utf-8";
Connection con;
PreparedStatement sql;
try{
con=DriverManager.getConnection(uri);
sql=con.prepareStatement("insert into orderform values(?,?,?,?)");
sql.setInt(1, 0);//订单序号会自定增长
sql.setString(2, loginBean.getLogname());
sql.setString(3, buyGoodsMess);
sql.setFloat(4, sum);
sql.executeUpdate();
LinkedList<String> car=loginBean.getCar();
car.clear();//清空购物车
success(request,response,"生成订单成功");
}catch(Exception e){
fail(request, response, "生成订单失败"+e);
}
}
private void success(HttpServletRequest request,
HttpServletResponse response,String backNews) {
response.setContentType("text/html;charset=utf-8");
try{
PrintWriter out =response.getWriter();
out.println("<html><body background='image/back.jpg' style='color:white'>");
out.println("<h2>"+backNews+"</h2>");
out.println("返回主页");
out.println("<a href='index.jsp'>主页</a>");
out.println("<br>查看订单");
out.println("<a href='lookOrderForm.jsp'>查看订单</a>");
out.println("</body></html>");
}catch(Exception e){}
}
private void fail(HttpServletRequest request, HttpServletResponse response,
String backNews) {
response.setCharacterEncoding("utf-8");
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(Exception e){}
}
}
运行图:
5、查询化妆品功能模块
(1)Model部分(JavaBean):DataByPage.java
(2)View部分(Jsp):searchCosmetic.jsp文件(查询化妆品)
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!-- 查询化妆品页面 -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<jsp:include page="head.jsp"/>
</head>
<body background="image/back.jpg" style="color: white">
<font size="3">
<div align="center">
<br>查询时可以输入化妆品的版本号或化妆品名称及价格。<br>
化妆品名称支持模糊查询。
<br>输入价格是在2个值之间的价格,格式是:价格1-价格2<br>
例如258-689
<form action="searchByConditionServlet" method="post">
<br>输入查询信息:<input type="text" name="searchMess"><br>
<input type="radio" name="radio" value="cosmetic_number">化妆品版本号
<input type="radio" name="radio" value="cosmetic_name" checked="ok">化妆品名称
<input type="radio" name="radio" value="cosmetic_price">化妆品价格
<br><input type="submit" name="g" value="提交">
</form>
</div>
</font>
</body>
</html>
(3)Control部分(Servlet):SearchByCondition.java文件
package myservlet.control;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletConfig;
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 mybean.data.DataByPage;
import sun.print.resources.serviceui;
import com.sun.rowset.CachedRowSetImpl;
/**
* 功能:查询化妆品
*/
public class SearchByCondition 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 destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String searchMess=request.getParameter("searchMess");
String radioMess=request.getParameter("radio");
if(searchMess==null||searchMess.length()==0){
fail(request,response,"没有查询信息,无法查询");
return;
}
String condition="";
if(radioMess.equals("cosmetic_number")){
condition="select * from cosmeticForm where cosmetic_number='"+searchMess+"'";
}else if(radioMess.equals("cosmetic_name")){
condition="select * from cosmeticForm where cosmetic_name like '%"+searchMess+"%'";
}else if(radioMess.equals("cosmetic_price")){
double max=0,min=0;
String regex="[^0123456789.]";
String[] priceMess=searchMess.split(regex);
if(priceMess.length==1){
max=min=Double.parseDouble(priceMess[0]);
}else if(priceMess.length==2){
min=Double.parseDouble(priceMess[0]);
max=Double.parseDouble(priceMess[1]);
if(max<min){
double t=max;
max=min;
min=t;
}
}else{
fail(request,response,"输入的价格格式有错误");
return;
}
condition="select * from cosmeticForm where"+"cosmetic_price<="+max+"and cosmetic_price>="+min;
}
HttpSession session=request.getSession(true);
Connection con=null;
DataByPage dataBean=null;
try{
dataBean=(DataByPage) session.getAttribute("dataBean");
if(dataBean==null){
dataBean=new DataByPage();
session.setAttribute("dataBean", dataBean);
}
}catch(Exception e){
dataBean=new DataByPage();
session.setAttribute("dataBean", dataBean);
}
String uri="jdbc:mysql://127.0.0.1/shop?"+"user=root&password=dpl1215&characterEncoding=utf-8";
try{
con=DriverManager.getConnection(uri);
Statement sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs=sql.executeQuery(condition);
rowSet=new CachedRowSetImpl();//创建行集对象
rowSet.populate(rs);//填充结果集
dataBean.setRowSet(rowSet);//行集数据存储在dataBean中
con.close();
}catch(Exception e){}
response.sendRedirect("byPageShow.jsp");
}
private void fail(HttpServletRequest request, HttpServletResponse response,
String backNews) {
response.setContentType("text/html;charset=utf-8");
try{
PrintWriter out=response.getWriter();
out.println("<html><body background='image/back.jpg' style='color:white'>");
out.println("<h2>"+backNews+"</h2>");
out.println("返回:");
out.println("<a href='searchCosmetic.jsp'>查询化妆品</a>");
out.println("</body></html>");
}catch(Exception e){}
}
}
运行图:
6、查询订单功能模块
(1)Model部分(JavaBean):Login.java
(2)View部分(Jsp):lookOrderForm.jsp文件
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<jsp:include page="head.jsp"/>
</head>
<jsp:useBean id="loginBean" class="mybean.data.Login" scope="session"/>
<body background="image/back.jpg" style="color:white">
<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/shop";
String user="root";
String password="dpl1215";
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(Exception e){
out.print(e);
}
%>
</div>
</body>
</html>
(3)Control部分(Servlet):无
运行图:
7、退出登录模块
Control部分(Servlet):HandleExit.java文件
package myservlet.control;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 功能:退出登录
*/
public class HandleExit extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession(true);
session.invalidate();//销毁用户的session对象
response.sendRedirect("index.jsp");
}
}
嗯,UI有些丑,支付功能没做!