为什么我调用这个Servlet 会执行2次
package servlet;
import java.io.IOException;
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 com.imooc.DAO.ItemsDao;
import com.imooc.model.Cart;
import com.imooc.model.Items;
/**
* Servlet implementation class CartServlet
*/
public class CartServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String action;//表示购物车的动作
ItemsDao dao = new ItemsDao();
public CartServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("我是GRT ,我执行了");
response.setContentType("text/html; charset=utf-8" );
if (request.getParameter("action")!=null) {
this.action=request.getParameter("action");
if (action.equals("add")) {
if (addToCart(request,response)) {
request.getRequestDispatcher("../success.jsp").forward(request, response);
}else {
request.getRequestDispatcher("../failure.jsp").forward(request, response);
}
}else {
request.getRequestDispatcher("../cart.jsp").forward(request, response);
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
private boolean addToCart(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
String id = request.getParameter("id");
String number = request.getParameter("num");
Items item = dao.getItemsBYid(Integer.parseInt(id));
//判断是否是第一次加入购物车,需要给Session添加一个新的购物车对象
if (request.getSession().getAttribute("cart")==null) {
Cart cart = new Cart();
request.getSession().setAttribute("cart",cart);
}
Cart cart = (Cart) request.getSession().getAttribute("cart");
if (cart.addCommodity(item, Integer.parseInt(number))) {
return true;
}else {
return false;
}
}
}
输出结果
我是GRT ,我执行了
我是GRT ,我执行了