购物车(1)

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

注册功能的实现:
1.register.html
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN"
"/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="/1999/xhtml"xml:lang="en"lang="en"> <head>
<title>register.html</title>
<meta http-equiv="content-type"content="text/html; charset=UTF-8"/> </head>
<body>
<form action="./reg"name="logon"method="post">
UserName<input type="text"name="user"/><br/>
Password<input type="password"name="pwd"/><br/>
<input type="submit"name="sub"/><br/></form>
</body>
</html>
2.RegServlet.java
package .neusoft.servlets;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet("/reg")
public class RegServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
String user=request.getParameter("user");
String pwd=request.getParameter("pwd");
Map users=
(Map)this.getServletContext().getAttribute("users");
if(users==null){
users=new HashMap();
}
if(users.get(user)!=null){
response.sendRedirect("./register.html");
}else{
users.put(user, pwd);
}
this.getServletContext().setAttribute("users", users);
out.println(user+",恭喜您,注册成功!");
out.print("<a href='./login.html'>转去登录</a>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
登录:
3. login. html
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN"
"/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="/1999/xhtml" xml:lang="en"lang="en"> <head>
<title>login.xhtml</title>
<meta http-equiv="content-type"content="text/html; charset=UTF-8"/>
<body>
<form action="./logon"name="logon"method="post">
UserName<input type="text"name="user"/><br/>
Password<input type="password"name="pwd"/><br/>
登录状态保留:<input type="radio"name="time"value="-1"/>不保存
<input type="radio"name="time"value="86400"checked/>一天
<input type="radio"name="time"value="604800"/>一周
<input type="radio"name="time"value="2592000"/>一个月
<input type="radio"name="time"value="31536000"/>永久
<br/>
<input type="submit"name="sub"value="登录"/><br/></form> </body>
</html>
LogonServlet.java
package .neusoft.servlets;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet("/logon")
public class LogonServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
String time = request.getParameter("time");
int i_time = Integer.parseInt(time);
Map users = (Map)
this.getServletContext().getAttribute("users");
if (users == null) {
response.sendRedirect("./register.html");
} else {
if (users.get(user) != null &&
users.get(user).equals(pwd)) {
HttpSession session = request.getSession();
session.setAttribute("T", user);
Cookie c = new Cookie("user", user);
c.setMaxAge(i_time);
response.addCookie(c);
c = new Cookie("JSESSIONID", session.getId());
c.setMaxAge(session.getMaxInactiveInterval());
response.addCookie(c);
out.println(user + "恭喜您,登录成功");
out.println("<a href='./p/goods'>转去购物</a>");
} else {
response.sendRedirect("./login.html");
}
}
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
显示商品列表
5. GoodsServlet.java
package .neusoft.servlets;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet("/p/goods")
public class GoodsServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
StringBuffer form=new StringBuffer();
form.append("<form action=\"buy\" name=\"shop\"
method=\"post\">"+
"<table align=center border=1>"+
"<tr><th>商品编号<th>商品名称<th>商品价格"+
"<tr><td><input type=\"radio\" value=\"图书\"
name=\"list\">1<td>图书<td>20"+
"<tr><td><input type=\"radio\" value=\"CD\"
name=\"list\">2<td>CD<td>10"+
"<tr><td><input type=\"radio\" value=\"衣服\"
name=\"list\">3<td>衣服<td>390"+
"<tr><td><input type=\"radio\" value=\"玩具\"
name=\"list\">4<td>玩具<td>390"+
"<tr><td><input type=\"radio\" value=\"手机\" name=\"list\">3<td>手机<td>390"+
"<tr><td colspan='3' align='center'><input
type=\"submit\" name=\"sub\" value=\"购买\" /></td></tr>"+ "</table></form>");
//输出form表单
out.println(form.toString());
out.println("<center><a href=\"./show\">显示购物车
</a><br></center>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
购买商品
BuyServlet.java
package .neusoft.servlets;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet("/p/buy")
public class BuyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
HttpSession session=request.getSession();
String good=request.getParameter("list");
//获取用户选中的物品名称
if(good!=null){
//如果用户确实选中要购买的物品
Map shopcart=(Map)session.getAttribute("shopcart");
//获取session中该物品的数量
if(shopcart!=null){
//如果不等于null,则意味着购买过货物
Integer count=(Integer)shopcart.get(good);
if(count==null){
count=new Integer(1);
}else{
count=count+1;
}
shopcart.put(good, count);
}else{
//以前从未购买过此物品
shopcart=new HashMap();
shopcart.put(good, new Integer(1));
//将购买数量设置为1
}
session.setAttribute("shopcart",shopcart);
}
out.print("<a href=\"./checkout\">转去结账</a><br>");
out.println("<a href=\"./show\">显示购物车</a><br>");
out.println("<a href=\"./goods\">继续购物</a>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
结账:
CheckoutServlet.java
package .neusoft.servlets;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet("/p/checkout")
public class CheckoutServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
String
user=(String)request.getSession().getAttribute("T");
Map
shopcart=(Map)request.getSession().getAttribute("shopcart");
if(shopcart!=null){
String
path=this.getServletContext().getRealPath("/WEB-INF/checkout/" );
File file=new File(path);
if(!file.exists()) file.mkdirs();
file=new File(path+"/"+user+".buy");
if(!file.exists()) file.createNewFile();
BufferedWriter bw=
new BufferedWriter(new FileWriter(file));
Object[] goodNames=(Object[])shopcart.keySet().toArray();
out.println("<table border=\"1\"><tr><th>物品名称</th><th>数量</th></tr>");
for(Object x:goodNames){
Integer count=(Integer)shopcart.get(x);
//输出到持久存储文件中
bw.write(x+"="+count+"\n");
//输出物品名
out.print("<tr><td>"+x+"</td>");
//输出物品数量
out.print("<td>"+count+"</td></tr>");
}
out.println("</table>");
request.getSession().removeAttribute("shopcart");
bw.close();
out.println("结帐成功");
}else{
out.println("您没有购买任何物品");
}
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
显示购物车:
ShowServlet.java
package .neusoft.servlets;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
/**
* Servlet implementation class ShowServlet
*/
@WebServlet("/p/show")
public class ShowServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ShowServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
Map shopcart = (Map)
request.getSession().getAttribute("shopcart");
if (shopcart != null) {
Object[] goodNames = (Object[])
shopcart.keySet().toArray();
out.println("<table border=\"1\"><tr><th>物品名称
</th><th>数量</th></tr>");
for (Object x : goodNames) {
Integer count = (Integer) shopcart.get(x);
// 输出物品名
out.print("<tr><td>" + x + "</td>");
// 输出物品数量
out.print("<td>" + count + "</td></tr>");
}
out.println("</table>");
out.print("<a href=\"./checkout\">转去结账</a><br>");
} else {
out.println("您还未购买任何物品");
}
out.println("<a href=\"./goods\">继续购物</a>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
Session销毁时自动保存已购买商品信息。

AutoSaveListener.java
package .neusoft.listeners;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebListener
public class AutoSaveListener implements HttpSessionListener { public void sessionCreated(HttpSessionEvent se) {
// TODO Auto-generated method stub
}
public void sessionDestroyed(HttpSessionEvent se) { HttpSession session=se.getSession();
String user=(String)session.getAttribute("T");
Map shopcart=(Map)session.getAttribute("shopcart");
try{
if(shopcart!=null){
String
path=session.getServletContext().getRealPath("/WEB-INF/uncheck out/");
File file=new File(path);
if(!file.exists()) file.mkdirs();
file=new File(path+"/"+user+".un");
if(!file.exists()) file.createNewFile();
BufferedWriter bw=
new BufferedWriter(new FileWriter(file));
Object[] goodNames=(Object[])shopcart.keySet().toArray();
for(Object x:goodNames){
Integer count=(Integer)shopcart.get(x);
//输出到持久存储文件中
bw.write(x+"="+count+"\n");
//输出物品名
}
//session.removeAttribute("shopcart");
bw.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
再次访问时自动加载以购买信息
package .neusoft.filters;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebFilter("/*")
public class AutoLoadFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request=
(HttpServletRequest)req;
HttpSession session=request.getSession();
if(session.isNew()){
Cookie[] cookies=request.getCookies();
if(cookies!=null){
for(Cookie x:cookies){
if(x.getName().equals("user")){
session.setAttribute("T", x.getValue());
String path=
session.getServletContext()
.getRealPath("/WEB-INF/uncheckout/"
+x.getValue()+".un");
System.out.println("filter:"+path);
File file=new File(path);
if(file.exists()){
try {
LineNumberReader lnr=
new LineNumberReader(
new BufferedReader(
new FileReader(file)));
Map shopcart=new HashMap();
String line=lnr.readLine();
while(line!=null){
if(line.indexOf("=")>0){
//图书=3
String name=line.substring(0,
line.indexOf("="));
String
value=line.substring(line.indexOf("=")+1
,line.length());
int count=Integer.parseInt(value);
shopcart.put(name, count);
}
line=lnr.readLine();
}
lnr.close();
file.delete();
session.setAttribute("shopcart", shopcart);
/*
RequestDispatcher
rd=request.getRequestDispatcher("/p/goods");
rd.forward(req, resp);
*/
String
context=session.getServletContext().getContextPath();
HttpServletResponse
response=(HttpServletResponse)resp;
response.sendRedirect(context+"/p/show");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
break;
}
}
}
}
//System.out.println("filter:goo");
chain.doFilter(req, resp);
}
public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub
}
}
如果用户没有登录,不允许访问/p/*目录下的资源
package .neusoft.filters;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebFilter("/p/*")
public class IsLogonFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
{
HttpServletRequest request=(HttpServletRequest)req;
HttpSession session=request.getSession();
Object user=session.getAttribute("T");
if(user!=null){
chain.doFilter(req, res);
}else{
HttpServletResponse response=(HttpServletResponse)res;
String path=
request.getSession().getServletContext().getContextPath();
response.sendRedirect(path+"/login.html");
}
}
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
处理请求以及相应的编码问题。

package .neusoft.filters;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebFilter("/*")
public class CharsetFilter implements Filter{
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest req,
ServletResponse res,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)req;
request.setCharacterEncoding("UTF-8");
res.setContentType("text/html;charset=UTF-8");
chain.doFilter(req, res);
}
public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub
}
}
为了不致等的太长时间才能看到页面效果,我们对Session的生命周期时间加以修改,将其改为最大不活动时间为3分钟,具体办法是:在web.xml文件中加入如下代码:
<session-config>
<session-timeout>3</session-timeout>
</session-config>。

相关文档
最新文档