📄 shoppingcartservlet.java
字号:
package web.servlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dao.BookDao;
import entity.Book;
import entity.ShoppingCart;
public class ShoppingCartServlet extends HttpServlet {
public static final String CART_NAME = "cart";
private BookDao bookDao = new BookDao();
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
Object obj = session.getAttribute(CART_NAME);
ShoppingCart cart;
if( obj == null )
{
cart = new ShoppingCart();
session.setAttribute(CART_NAME, cart);
}
else
{
cart = (ShoppingCart) obj;
}
//获得op参数
String op = request.getParameter("op");
//获得isbn参数
String isbn = request.getParameter("isbn");
if( "doAdd".equals(op) )
{
//查书
Book book = null;
try {
book = bookDao.findByIsbn(isbn);
} catch (SQLException e) {
e.printStackTrace();
}
if(book!=null)
{
//添加到购物车中(购物车本身放在会话中)
cart.addItem(isbn, book);
}
}
else if( "doDelete".equals( op )) // op.equals( "doDelete")
{
cart.deleteItem(isbn);
}
else if( "doUpdate".equals( op ) )
{
try
{
int amount = Integer.parseInt( request.getParameter("amount"));
cart.updateAmount(isbn, amount);
}
catch(Exception ex)
{
//
}
}
//转发到cart.jsp,显示购物信息
request.getRequestDispatcher("cart.jsp").forward(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -