未经作者允许,禁止转载。转载请注明出处。
一、项目概览
这是一个简单的web项目,只用到servlet、jsp、jdbc。想要完整项目,见文章底部自动获取方式(很方便),码字不易,点个赞吧。
二、项目的首页部分
这个界面是一个简单的JSP界面,注意它开始的两行(红字+超链接)部分,使用的include指令,静态包含到这个页面。提醒大家的是,包含的页面和被包含页面的page指令必须一模一样。
代码如下(head.txt和index.jsp):
<%@ page contentType="text/html;charset=GB2312" %>
<div align="center">
<Font color=red><H3>“青山不老绿水无忧”化妆品销售网</H3></Font>
<table cellSpacing="1" cellPadding="1" width="660" align="center" border="0">
<tr valign="bottom">
<td><A href="index.jsp">主页</A></td>
<td><A href="inputRegisterMess.jsp">注册</font></A></td>
<td><A href="login.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="exitServlet">退出</A></td>
</tr>
</table>
</div>
<%@ page contentType="text/html;charset=GB2312" %>
<HTML> <BODY>
<HEAD></HEAD>
<title>首页</title>
<%@ include file="head.txt" %>
<CENTER>
<h1><font Size=4 color=blue>欢迎光临“青山不老绿水无忧”化妆品销售网</font></h1>
<img src="image/welcome.jpg" width=600 height=200 ></img>
</CENTER>
</BODY></HTML>
head.txt前面介绍过了,紧接着是一个border为0的3行4列的表格,注意这个表格是被表单包裹着的。那么从下面那个表格,我们可以看出,它是想要把注册成功之后的信息显示到表格的第二列。怎么做呢?首先提交后的信息,必须到servlet中进行连接数据库,并且把数据插入到数据库中。同时要把提交的数据,保存到JavaBean中。先贴出代码,再分析。
inputRegisterMess.jsp:
<%@ page contentType="text/html;charset=GB2312" %>
<jsp:useBean id="userBean" class="mybean.data.Register" scope="request"/>
<HEAD><%@ include file="head.txt" %></HEAD>
<title>注册页面</title>
<HTML><BODY background=image/back.jpg><Font size=2>
<div align="center">
<FORM action="registerServlet" method="post" name=form>
<table>
用户名由字母、数字、下划线构成,*注释的项必须填写。
<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 name="userBean" property="backNews" />
<table border=3>
<tr><td>会员名称:</td>
<td><jsp:getProperty name="userBean" property="logname"/></td>
</tr>
<tr><td>姓名:</td>
<td><jsp:getProperty name="userBean" property="realname"/></td>
</tr>
<tr><td>地址:</td>
<td><jsp:getProperty name="userBean" property="address"/></td>
</tr>
<tr><td>电话:</td>
<td><jsp:getProperty name="userBean" property="phone"/></td>
</tr>
</table></div >
</Body></HTML>
HandleRegister.java:
package myservlet.control;
import mybean.data.*;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HandleRegister 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);
}
catch(Exception ee){}
return s;
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
String uri="jdbc:mysql://127.0.0.1:3306/shop?"+
"user=root&password=123456&characterEncoding=gb2312";
Connection con;
PreparedStatement sql;
//
// scope="request" />
Register userBean=new Register(); //创建的Javabean模型
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){
backNews="注册成功";
//
//
userBean.setLogname(logname);
userBean.setBackNews(backNews);
userBean.setPhone(handleString(phone));
userBean.setAddress(handleString(address));
userBean.setRealname(handleString(realname));
}
}
else {
backNews="信息填写不完整或名字中有非法字符";
userBean.setBackNews(backNews);
}
con.close();
}
catch(SQLException exp){
backNews="该会员名已被使用,请您更换名字"+exp;
userBean.setBackNews(backNews);
}
RequestDispatcher dispatcher=
request.getRequestDispatcher("inputRegisterMess.jsp");
dispatcher.forward(request, response);//转发
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
doPost(request,response);
}
}
1.init()函数中加载驱动,有个handleString()函数使用来将字符串以相应的编码方式转化成字节数组,之后再将字节数组作为参数,创建新的字符串并且返回。
2.doPost()方法中的业务逻辑(jdbc连接数据库就不解释了,很简单),它先new了一个Register,然后用set方法将表单中的数据设置该对象中。从注释中,我们可以看出它还可以通过jsp的标签进行创建,而且自动创建之后,可以用setProperty标签设置到对应的自动创建的对象中,从后面的注释中,我们也能看的出来。它提供了两种方法,逐个设置,或者设置全部。从中啊,我们可以看到,jsp的useBean标签、setProperty标签、getProperty标签本质上useBean标签就是把JavaBean来new出一个对象,setProperty标签对应于对象调用set方法设置属性,getProperty标签对应于对象打点调用get方法。底层应该就是封装了一把,定义了新的比较简单的JSP标签语法。
3.简单的说一下它的业务逻辑,取出form表单的内容,进行判断。首先,用户要是不设置用户名,密码。得有个判断不能让它通过,它最后使用字符串为0做判断不能通过。所以就设置为“”,null是调不出来length。接着,用户名密码有了,确认密码得判断相同,如果相同的话,转发到注册页面,结束本页面。注意的是,这里只能是转发,因为它的jsp页面scope是request。再之后那里是判断用户名必须是由字母数字组成,这里最好用正则表达式,能交给前端处理的,就别放在后端。最后的boo是最终确定用户名和密码的,如果是true则通过。
4.把数据放到数据库,这里的setString()参数是1开始,不要弄错了。把信息设置到数据库成功,就代表了注册成功。否则的话,只可能是含有非法字符。用户名是主键,如果数据库中存在了,再次插入,一定会报错的。在捕获异常中设置backNews信息,再转发到注册页面。
login.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<jsp:useBean id="loginBean" class="mybean.data.Login" scope="session"/>
<HTML><HEAD><%@ include file="head.txt" %></HEAD>
<BODY background=image/back.jpg><font size=2>
<div align="center">
<table border=2>
<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>
</table>
<Input type=submit name="g" value="提交">
</form>
</div >
<div align="center" >
登录反馈信息:<jsp:getProperty name="loginBean" property="backNews"/>
<br>登录名称:<jsp:getProperty name="loginBean" property="logname"/>
<div >
</font>
</BODY></HTML>
这里比较简单,看代码就会明白。
HandleLogin.java:
package myservlet.control;
import mybean.data.*;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
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);
}
catch(Exception ee){}
return s;
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
Connection con;
Statement sql;
String logname=request.getParameter("logname").trim(),
password=request.getParameter("password").trim();
logname=handleString(logname);
password=handleString(password);
String uri="jdbc:mysql://127.0.0.1/shop?"+
"user=root&password=123456&characterEncoding=gb2312";
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==true){
//调用登录成功的方法:
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(SQLException exp){
String backNews=""+exp;
fail(request,response,logname,backNews);
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
doPost(request,response);
}
public void success(HttpServletRequest request,HttpServletResponse response
,String logname,String password) {
Login loginBean=null;
HttpSession session=request.getSession(true);
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 ee){
loginBean=new Login();
session.setAttribute("loginBean",loginBean);
loginBean.setBackNews(logname+"登录成功");
loginBean.setLogname(logname);
}
}
public void fail(HttpServletRequest request,HttpServletResponse response
,String logname,String backNews) {
response.setContentType("text/html;charset=GB2312");
try {
PrintWriter out=response.getWriter();
out.println("");
out.println(""
+logname+"登录反馈结果
"+backNews+"2>") ;
out.println("返回登录页面或主页
");
out.println("登录页面");
out.println("
主页");
out.println("");
}
catch(IOException exp){}
}
}
得到用户名,密码,转换成对应的编码方式防止乱码。判断对应的字符串长度是否大于0。准备在数据库进行查询,判断是否长度为0。为零的话就去调用fail方法。fail方法是写了一个简答的反馈界面。不为0的话就能够去查询了,执行查询语句返回结果集。有结果的话就执行success方法。该方法做的是:先看看存在会话没有,如果没有的话就创建一个会话。通过会话取出loginbean,没有的话就创建一个,设置到会话中。这样不管如何只要是调用这个方法,就有会话,会话中就有loginbean。因为该判断的在调用该方法之前就已经判断了,这里主要就是创建会话维护登录。如果为空的话,登录成功。不为空,loginbean有对象,能调用出equals判断相等的话,就表明已经登录成功。
五、浏览商品的功能
lookCosmetic.jsp:
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="java.sql.*" %>
<HTML><HEAD><%@ include file="head.txt" %></HEAD>
<BODY background=image/back.jpg><font size=2>
<div align="center">
<% try { Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e){}
String uri="jdbc:mysql://127.0.0.1:3306/shop?"+
"user=root&password=123456&characterEncoding=gb2312";
Connection con;
Statement sql;
ResultSet rs;
try {
con=DriverManager.getConnection(uri);
sql=con.createStatement();
//读取classify表,获得分类:
rs=sql.executeQuery("SELECT * FROM classify ");
out.print(") ;
out.print(") ;
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
out.print("id+">"+name+"");
}
out.print("");
out.print("");
out.print("");
con.close();
}
catch(SQLException e){
out.print(e);
}
%>
</div></font>
</BODY></HTML>
QueryAllRecord.java
package myservlet.control;
import mybean.data.DataByPage;
import com.sun.rowset.*;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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 doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
request.setCharacterEncoding("gb2312");
String idNumber= request.getParameter("fenleiNumber");
if(idNumber==null)
idNumber="0";
int id = Integer.parseInt(idNumber);
HttpSession session=request.getSession(true);
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 exp){
dataBean=new DataByPage();
session.setAttribute("dataBean",dataBean);
}
String uri="jdbc:mysql://127.0.0.1:3306/shop";
try{
con=DriverManager.getConnection(uri,"root","123456");
Statement sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs=sql.executeQuery("SELECT * FROM cosmeticForm where id = "+id);
rowSet=new CachedRowSetImpl(); //创建行集对象
rowSet.populate(rs);
dataBean.setRowSet(rowSet); //行集数据存储在dataBean中
con.close(); //关闭连接
System.out.println("QueryAllRecord - select");
}
catch(SQLException exp){}
response.sendRedirect("byPageShow.jsp");//重定向到byPageShow.jsp
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
doPost(request,response);
}
}
从表单中获取到查的是哪个化妆品。把字符串的id转换成了int类型。创建session和对应的分页对象,并且把该对象放到session中。去查找对应的化妆品记录,并且创建CachedRowSetImpl行级对象。使得即使关闭数据库连接,结果集也存在,而且能在不同页面转换。bean中也有对应的行级对象。
byPageShow.jsp:
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="mybean.data.DataByPage" %>
<%@ page import="com.sun.rowset.*" %>
<jsp:useBean id="dataBean" class="mybean.data.DataByPage" scope="session"/>
<%@ include file="head.txt" %></HEAD>
<HTML><Body background=image/back.jpg><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 name="dataBean" property="pageSize" param="pageSize"/>
<jsp:setProperty name="dataBean" property="currentPage" 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="+
"+goods+">"+
"";
String detail="+
"+number+">"+
"";
out.print("");
out.print(""+number+" ");
out.print(""+name+" ");
out.print(""+maker+" ");
out.print(""+price+" ");
out.print(""+detail+" ");
out.print(""+button+" ");
out.print(" ");
boo=rowSet.next();
}
}
%>
</table>
<BR>每页最多显示<jsp:getProperty name="dataBean" property="pageSize"/>条信息
<BR>当前显示第<Font color=blue>
<jsp:getProperty name="dataBean" property="currentPage"/>
</Font>页,共有
<Font color=blue><jsp:getProperty name="dataBean" property="totalPages"/>
</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>
</BODY></HTML>
重点解释<%%>中的内容,得到行级对象后,判断里面有没有数据,没有数据就输出对应提示。从行级对象中得到全部的记录数有多少,得到每页要显示几条记录,相除得到总页数有多少。设置到对应的分页bean对象中。紧接着的判断分支表示只要有记录(第一个大if),判断当前页是否在1-总页数之间(两个小if),index表示锁定到当前页的哪行记录,最后通过rowSet.absolute(index);真正查询位置移动到currentPage页起始位置。for循环用来显示,把每条记录从数据库中拿出来,然后显示到表头下面那行,boo来确保当记录显示完毕之后就不在显示,否则会报错。最后那段HTML代码用来跳转上一页下一页,很简单用form表单,重复提交到本页面,再从头执行,如果本身有两页记录,却跳到第三页,它就会把你纠正回第一页。
PutGoodsToCar.java:
package myservlet.control;
import mybean.data.Login;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PutGoodsToCar extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
request.setCharacterEncoding("gb2312");
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 exp){
response.sendRedirect("login.jsp");//重定向到登录页面
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
doPost(request,response);
}
public void speakSomeMess(HttpServletRequest request,
HttpServletResponse response,String goods) {
response.setContentType("text/html;charset=GB2312");
try {
PrintWriter out=response.getWriter();
out.print("<%@ include file='head.txt' %>");
out.println("");
out.println(""
+goods+"放入购物车") ;
out.println("查看购物车或返回浏览化妆品
");
out.println("查看购物车");
out.println("
浏览化妆品");
out.println("");
}
catch(IOException exp){}
}
}
这段代码把session中的loginbean拿出来,之前for循环那里有一段goods信息,这里就是要把表单中那段信息添加进去。然后调用speakSomeMess方法显示出来,如第二张图。
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="mybean.data.Login" %>
<%@ page import="java.util.*" %>
<jsp:useBean id="loginBean" class="mybean.data.Login" scope="session"/>
<HTML><HEAD><%@ include file="head.txt" %></HEAD>
<BODY background=image/back.jpg><font size=2>
<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 car =loginBean.getCar();
if(car==null)
out.print(" 购物车没有物品.
");
else {
Iterator<String> 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="+
"+goods+">"+
"";
out.print(""+showGoods+" ");
out.print(""+del+" ");
}
out.print("
");
String orderForm = "+
" +buyGoods+" >"+
" +priceSum+" >"+
"";
out.print(orderForm);
}
%>
</div></font>
</BODY></HTML>
这里是把loginbean中对应的car取出来,类型是LinkedList,用迭代器遍历,在表格上一一显示。
HandleBuyGoods:
package myservlet.control;
import mybean.data.Login;
import java.sql.*;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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 doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
request.setCharacterEncoding("gb2312");
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");//重定向到登录页面
}
catch(Exception exp){
response.sendRedirect("login.jsp");//重定向到登录页面
}
String uri="jdbc:mysql://127.0.0.1/shop?"+
"user=root&password=123456&characterEncoding=gb2312";
Connection con;
PreparedStatement sql;
try{ con=DriverManager.getConnection(uri);
String insertCondition="INSERT INTO orderform VALUES (?,?,?,?)";
sql=con.prepareStatement(insertCondition);
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,"生成订单成功");
System.out.println("HandleBuyGoods - 生成订单成功");
}
catch(SQLException exp){
fail(request,response,"生成订单失败"+exp);
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
doPost(request,response);
}
public void success(HttpServletRequest request,HttpServletResponse response,
String backNews) {
response.setContentType("text/html;charset=GB2312");
try {
PrintWriter out=response.getWriter();
out.println("");
out.println(""
+backNews+"") ;
out.println("返回主页
");
out.println("
主页");
out.println("查看订单
");
out.println("
查看订单");
out.println("");
}
catch(IOException exp){}
}
public void fail(HttpServletRequest request,HttpServletResponse response,
String backNews) {
response.setContentType("text/html;charset=GB2312");
try {
PrintWriter out=response.getWriter();
out.println("");
out.println(""
+backNews+"") ;
out.println("返回主页:");
out.println("主页");
out.println("");
}
catch(IOException exp){}
}
}
对应第二张截图,主要用来判断能不能生成订单,并将信息插入到数据库。代码通俗易懂,不做解释。
lookOrderForm.jsp:
<%@ page contentType="text/html;charset=GB2312" %>
<jsp:useBean id="loginBean" class="mybean.data.Login" scope="session"/>
<%@ page import="java.sql.*" %>
<HTML><HEAD><%@ include file="head.txt" %></HEAD>
<BODY background=image/back.jpg>
<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:3306/shop";
String user="root";
String password="123456";
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(""+"订单号");
out.print(" "+"信息");
out.print(" "+"价格");
out.print(" ");
while(rs.next()){
out.print("");
out.print(""+rs.getString(1)+" ");
out.print(""+rs.getString(2)+" ");
out.print(""+rs.getString(3)+" ");
out.print(" ") ;
}
out.print("
");
con.close();
}
catch(SQLException e){
out.print(e);
}
%>
</div">
</BODY></HTML>
这里就是简单的显示,从数据库把插入的拿出来,再显示,比较简单。
这里比较简单,看代码就会明白。
这里比较简单,看代码就会明白。
注:最近要源码的同学比较多,频繁发送邮箱比较麻烦。 大家可以关注公众号:Carry互联网笔记,向后台发送“web项目”,自动获取,包含之前的数据表。公号也会向大家定期推送资源