在我的servlet中,我正在使用用户选择的产品并通过AJAX将产品ID传递给servlet
@WebServlet("/productSelected")
public class ProductCompareAJAX extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String productCode=request.getParameter("productCode");
System.out.print("Product Code"+productCode);
Set <String>prodCodeList=new HashSet<String>();
prodCodeList.add(productCode);
System.out.println(prodCodeList.toString());
request.getSession().setAttribute("sessionProductCode", prodCodeList);
System.out.println("Value in session *************"+request.getSession().getAttribute("sessionProductCode").toString());
//String sessionProdId=request.getSession().getAttribute("sessionProductCode").toString();
String nextJSP = "jsp/index.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
}
当用户从列表
中选择产品时,会触发此ajax调用function addToCompare() {
console.log("Product ID: "+ this.id);
console.log("Product ID: "+ this.dataset.productId);
var productCode;
if($("input[id="+this.id+"]").is(':checked'))
{
//ajax call
productCode=this.dataset.productId;
alert(productCode);
$.ajax({
type: 'POST',
url: 'productSelected',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8;',
data: {productCode:"productCode"},
cache: false,
success: function (data) {
alert("Success");
}
});
// ajax call ends
}
else
{
alert("Not selected");
}
}
$(function() {
$('.productCheckbox').click(addToCompare);
console.log("Document is ready");
});
//Output
Product Codenull[null]
Value in session *************[null]
请告诉我为什么我的servlet中的值为null
。
答案 0 :(得分:1)
在ajax
数据选项中,您写为
data: {productCode:"productCode"},
因此productCode
的值始终为 productCode 。
将其更改如下:
data: {productCode:productCode},