JavaWeb实用项目之----化妆品销售网

升入本科之后又学了一遍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(其他页面使用包含导航条)


   
  


主页文件:index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>



  
    首页
    

欢迎光临"青山绿水"化妆品销售网

 运行图:

JavaWeb实用项目之----化妆品销售网_第1张图片

 配置Web服务目录文件:web.xml(系统的Servlet类的包名均为:myservlet.control)



  
  
    registerServlet
    myservlet.control.HandleRegister
  
  
    loginServlet
    myservlet.control.HandleLogin
  
  
    deleteServlet
    myservlet.control.HandleDelete
  
  
    buyServlet
    myservlet.control.HandleBuyGoods
  
  
    queryServlet
    myservlet.control.QueryAllRecord
  
  
    putGoodsServlet
    myservlet.control.PutGoodsToCar
  
  
    searchByConditionServlet
    myservlet.control.SearchByCondition
  
  
    exitServlet
    myservlet.control.HandleExit
  

  
    registerServlet
    /registerServlet
  
  
    loginServlet
    /loginServlet
  
  
    deleteServlet
    /deleteServlet
  
  
    buyServlet
    /buyServlet
  
  
    queryServlet
    /queryServlet
  
  
    putGoodsServlet
    /putGoodsServlet
  
  
    searchByConditionServlet
    /searchByConditionServlet
  
  
    exitServlet
    /exitServlet
  	
  
    index.jsp
  

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"%>





注册页面



  
  
用户名由字母、数字、下划线组成,*注释的选项必须填写。
*用户名称: *用户密码:
*重复密码: 联系电话:
邮寄地址: 真实姓名:

注册反馈:

会员名称:
姓名:
地址:
电话:

(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='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
	}
}

运行图:

JavaWeb实用项目之----化妆品销售网_第2张图片

2、会员登录功能模块

(1)Model部分(JavaBean):Login.java文件

package mybean.data;

import java.util.LinkedList;
//存储用户登录的信息
public class Login {
   private String logname="";
   private String backNews="未登录";
   private LinkedList car;//用户的购物车
   public Login(){
	   car=new LinkedList();
   }
   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 getCar() {
		return car;
   } 
}

(2)View部分(Jsp):login.jsp文件

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>



  
    
   
  
    
    
登录
账号:
密码:
登录信息反馈:
账号:

(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("");
			out.println("

"+logname+"登陆反馈结果
"+backNews+"

"); out.println("返回登录界面或主页
"); out.println("登录界面"); out.println("
主页"); out.println(""); }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); } } }

运行图:

JavaWeb实用项目之----化妆品销售网_第3张图片

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.*" %>



  
    
  
  
  
    
    
<% 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("
"); out.print("
"); con.close(); }catch(Exception e){ out.print(e); } %>

运行图:JavaWeb实用项目之----化妆品销售网_第4张图片

    byPageShow.jsp文件:(浏览选取的商品记录)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="mybean.data.DataByPage" %>
<%@ page import="com.sun.rowset.*" %>




  
    
  
  
  
     
     

当前显示的内容是: <% 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="
"+ ""+ //隐藏hidden,提交时直接将其value的值提交 ""; String detail="
"+ ""+ "" ; out.print("
"); out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); boo=rowSet.next(); } } %>
化妆品标识号 化妆品名称 化妆品制造商 化妆品价格 查看详情 添加到购物车
"+number+""+name+""+maker+""+price+""+detail+""+button+"

每页最多显示条信息
当前显示第 页,共有 页。
每页显示 条记录
输入页码:

运行图:JavaWeb实用项目之----化妆品销售网_第5张图片   

showDetail.jsp文件:(商品详情页)

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.sql.*" %>


  
    
  
  
  
    
<% 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("产品号"+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(""); out.print(""); out.print(""); 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=""+ ""+ ""; out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); } out.print("
产品号"); out.print("名称"); out.print("制造商"); out.print("价格"); out.print("放入购物车"); out.print("
"+number+""+name+""+maker+""+price+""+button+"
"); out.print("
产品详情:
"); out.println("
"+detailMess+"

"); String pic=""; out.print(pic);//产品图片 con.close(); }catch(Exception e){} %>

运行图:JavaWeb实用项目之----化妆品销售网_第6张图片

(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 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("" +
					"
" + "

'青山绿水'化妆品销售网

"+ ""+ ""+ ""+ ""+ ""+ ""+ ""+ ""+ ""+ ""+ "
主页浏览化妆品查询化妆品查看购物车查看订单登录注册退出



"); out.println("
"); out.println("

商品已放入购物车

"); out.println("查看购物车或返回浏览化妆品

"); out.println("查看购物车"); out.println("     浏览化妆品"); out.println("
"); }catch(Exception e){} } }

运行图:JavaWeb实用项目之----化妆品销售网_第7张图片

4、查看购物车功能模块 

(1)Model部分(JavaBean):Login.java 

(2)View部分(Jsp):lookShoppingCar.jsp文件

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>



  
     
  
  
  
    
    
<% 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("

购物车没有物品

"); else{ Iterator iterator=car.iterator(); StringBuffer buyGoods=new StringBuffer(); int n=0; double priceSum=0; out.print("购物车中的物品:"); 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=""+ ""+ ""; out.print(""); out.print(""); } out.print("
"+showGoods+""+del+"
"); String orderForm="
"+ ""+ ""+ "
"; out.print(orderForm); } %>

(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 car=loginBean.getCar();
			car.remove(delete);//删除商品
		}catch(Exception e){
			response.sendRedirect("login.jsp");
		}
		RequestDispatcher dispatcher=request.getRequestDispatcher("lookShoppingCar.jsp");
		dispatcher.forward(request, response);
	}

}

   运行图:

JavaWeb实用项目之----化妆品销售网_第8张图片 

   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 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("");
			out.println("

"+backNews+"

"); out.println("返回主页"); out.println("主页"); out.println("
查看订单"); out.println("查看订单"); out.println(""); }catch(Exception e){} } private void fail(HttpServletRequest request, HttpServletResponse response, String backNews) { response.setCharacterEncoding("utf-8"); try{ PrintWriter out=response.getWriter(); out.println(""); out.println("

"+backNews+"

"); out.println("返回主页:"); out.println("主页"); out.println(""); }catch(Exception e){} } }

运行图:

JavaWeb实用项目之----化妆品销售网_第9张图片

5、查询化妆品功能模块

 (1)Model部分(JavaBean):DataByPage.java

 (2)View部分(Jsp):searchCosmetic.jsp文件(查询化妆品)

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>




  
    
  
  
  
    
    

查询时可以输入化妆品的版本号或化妆品名称及价格。
化妆品名称支持模糊查询。
输入价格是在2个值之间的价格,格式是:价格1-价格2
例如258-689

输入查询信息:
化妆品版本号 化妆品名称 化妆品价格

(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;
        }
        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("");
			out.println("

"+backNews+"

"); out.println("返回:"); out.println("查询化妆品"); out.println(""); }catch(Exception e){} } }

运行图:

JavaWeb实用项目之----化妆品销售网_第10张图片

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"%>



  
    
  
  
  
    
<% 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(""); out.print(""); out.print(""); while(rs.next()){ out.print(""); out.print(""); out.print(""); out.print(""); out.print(""); } out.print("
"+"订单号"); out.print(""+"信息"); out.print(""+"价格"); out.print("
"+rs.getString(1)+""+rs.getString(2)+""+rs.getString(3)+"
"); con.close(); }catch(Exception e){ out.print(e); } %>

  (3)Control部分(Servlet):无

运行图:

JavaWeb实用项目之----化妆品销售网_第11张图片

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有些丑,支付功能没做!

源码

你可能感兴趣的:(Java)