欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

session案例:使用Session完成简单的购物功能

程序员文章站 2022-03-14 22:49:45
...
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%--sale.jsp--%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>    
  </head>
  
  <body>
 	<a href="<%=request.getContextPath() %>/servlet/BuyServlet?prod=洗衣机">洗衣机</a> 
 	<a href="<%=request.getContextPath() %>/servlet/BuyServlet?prod=电视机">电视机</a>
 	<a href="<%=request.getContextPath() %>/servlet/PayServlet">结账</a>   
  </body>
</html>


package it.com.session;

import java.io.IOException;

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 BuyServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String prod=request.getParameter("prod");
		prod=new String(prod.getBytes("iso8859-1"),"utf-8");//解决乱码问题
		HttpSession session=request.getSession();
		session.setAttribute("prod", prod);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

package it.com.session;

import java.io.IOException;

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 PayServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");	//解决乱码问题
		HttpSession session=request.getSession();
		String prod=(String)session.getAttribute("prod");
		response.getWriter().write("您购买的是:"+prod+"应付10000元");

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

相关标签: session