Lưu Trữ Danh Sách Giá Trị (HttpSession)

Bài này trình bày đơn giản cách chúng ta lưu trữ các giá trị trong một Collection . Thao tác với đối tượng HttpsSession .

Cấu trúc của project đơn giản chỉ gồm 1 trang Shopping.jsp và 1 Servlet ShowOrder.java

FILE : Shopping.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 <h1>Shopping : </h1>
 <form action="show" method="post">
 Choose : <select name="items">
 <option value="Dress">Dress</option>
 <option value="Skirt">Skirt</option>
 <option value="Hat">Hat</option>
 <option value="Trousers">Trousers</option>
 <input type="submit" value="Show Order">



package thaihoanghai.wordpress.com.servlets;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

 * Servlet implementation class ShowOrder
public class ShowOrder extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		synchronized (session) {
			ArrayList<String> items =
			(ArrayList<String>) session.getAttribute("items");
			if(items == null)
				items = new ArrayList<String>();
			String newItem = request.getParameter("items");
			if(newItem != null && !newItem.trim().equals(""))
			session.setAttribute("items", items);
			PrintWriter out = response.getWriter();
			String title = "Items Purchased";
			String docType =
					"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
			out.println(docType +
					"<HTML>\n" +
					"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
					"<BODY BGCOLOR=\"#FDF5E6\">\n" +
					"<H1>" + title + "</H1>");
			if(items.size() == 0){
				out.println("<I don't want to buy anything !!!>");
				for(String obj : items){
					out.println("<LI>" + obj);



			out.println("<br>Do You want to buy ???" + "<a href=\"Shopping.jsp\">Click Here</a>");




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: