session 案例实现简单的购物

使用session完成简单的购物功能。

大型的上午网站一般使用cookie来实现,目的是减少服务器的压力。

package cn.itcast.shoping;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


//代表首页的servlet
public class ListBookServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");//第一句,设置服务器端编码
		response.setContentType("text/html;charset=utf-8");//第二句,设置浏览器端解码
		PrintWriter writer = response.getWriter();
		//1.输出网页所有商品
		writer.println("本网站所有商品:<br>");
		Map<String, Book> map = DB.getall();
		for(Map.Entry<String, Book> entry :map.entrySet()){
			Book book = entry.getValue();
			writer.print("<a href='/web2/servlet/BuyServlet?id=" + book.getId()+"' target='_blank\'>" + book.getName()+"</a><br/>");
			
		}
			
		}

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

	}
class DB{
	private static Map<String,Book> map = new LinkedHashMap();
	static {
		map.put("1", new Book("1","java web开发","老张","一本好书"));
		map.put("2", new Book("2","java jdbc开发","老张","一本好书"));
		map.put("3", new Book("3","java spring开发","老a","一本好书"));
		map.put("4", new Book("4","java struts开发","老v","一本好书"));
		map.put("5", new Book("5","java android开发","老b","一本好书"));
	}
	
	public static Map getall(){
		return map;
	}
	
	
}



class Book implements Serializable{
	private String id;
	private String name;
	private String author;
	private String description;
	
	
	
	public Book() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Book(String id, String name, String author, String description) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
		this.description = description;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	
	
	
	
}
package cn.itcast.shoping;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
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 id = request.getParameter("id");
		Book book = (Book) DB.getall().get(id);
		HttpSession  session = request.getSession();
		//手动cookie 形式发送sessionid,以解决关闭浏览器后上次买的东西还在 
		String sessionid = session.getId();
		
		Cookie cookie = new Cookie("JSESSIONID",sessionid);
		cookie.setMaxAge(30*60);
		System.out.println(request.getContextPath());
		cookie.setPath(request.getContextPath());
		response.addCookie(cookie);
		
		//从session中得到用户用于保存所有书的集合(购物车)
		List list = (List) session.getAttribute("list");
		if(list==null){
			list = new ArrayList();
			session.setAttribute("list", list);
		}
		list.add(book);
		System.out.println(book.getName());
		//request.getRequestDispatcher("/servlet/ListCarServlet").forward(request, response);
		response.sendRedirect(request.getContextPath()+"/servlet/ListCarServlet");
		
		
		
	}


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

	doGet(request, response);
	}

}

 

package cn.itcast.shoping;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");//第一句,设置服务器端编码
		response.setContentType("text/html;charset=utf-8");//第二句,设置浏览器端解码
		PrintWriter writer = response.getWriter();
		
		HttpSession session =  request.getSession(false);
		if(session==null){
			writer.println("您没有购买任何商品");
			return;
		}
		writer.println("您购买了如下商品:<br/>");
		List<Book> list = (List) session.getAttribute("list");
		for (Book book:list){
			writer.println(book.getName());
		}
	}


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

}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure, I can help you with that. Here is an example code for implementing Redis to share sessions in Java: ``` import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.Map; public class RedisSessionManager { private static final String REDIS_HOST = "localhost"; private static final int REDIS_PORT = 6379; private static final int MAX_IDLE = 10; private static final int MAX_TOTAL = 30; private static final int MAX_WAIT_MILLIS = 10000; private static final int TIMEOUT = 1000; private static final String SESSION_PREFIX = "session:"; private static final Map<String, HttpSession> sessions = new HashMap<>(); private static JedisPool jedisPool = null; static { JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxIdle(MAX_IDLE); poolConfig.setMaxTotal(MAX_TOTAL); poolConfig.setMaxWaitMillis(MAX_WAIT_MILLIS); jedisPool = new JedisPool(poolConfig, REDIS_HOST, REDIS_PORT, TIMEOUT); } public static HttpSession createSession() { Jedis jedis = jedisPool.getResource(); String sessionId = SESSION_PREFIX + UUID.randomUUID().toString(); HttpSession session = new RedisHttpSession(sessionId, jedis); sessions.put(sessionId, session); return session; } public static HttpSession getSession(String sessionId) { HttpSession session = sessions.get(sessionId); if (session == null) { Jedis jedis = jedisPool.getResource(); session = new RedisHttpSession(sessionId, jedis); sessions.put(sessionId, session); } return session; } public static void removeSession(String sessionId) { sessions.remove(sessionId); Jedis jedis = jedisPool.getResource(); jedis.del(sessionId); jedis.close(); } } ``` This code uses the Jedis library to connect to Redis and store session data. It provides methods for creating, getting and removing sessions. The sessions are stored in a HashMap in memory for fast access, but are also persisted to Redis so they can be shared across multiple servers. I hope this helps!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值