我试图使用jquery post调用servlet,但是它不是调用servlet而是在webcontent的jsp部分中搜索servlet。 我发布下面的代码
function getPackageList() {
alert("in package List");
var Criteria = "get_package_list";
var list;
// $('#package_list').empty();
$.post(
'${pageContext.request.contextPath}/PackageController',
{
criteria : Criteria
},
function(data) {
alert("Success " + data);
$(data).each(
function(index, element) {
list += "<li> <a href='#' id='" + element.Id
+ "' onClick='getSelectedPackage()'>"
+ element.PackageName + "</a></li>";
});
$('#package_list').html(list);
}, 'json').fail(function(jqXHR, textStatus, errorThrown) {
alert(error);
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
}
@WebServlet("/PackageController")
public class PackageController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static PackageDao packageDao = new PackageDaoImpl();
public PackageController() {
super();
// TODO Auto-generated constructor stub
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String criteria=request.getParameter("criteria");
System.out.println("The criteria is "+criteria);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try
{
String criteria=request.getParameter("criteria");
System.out.println("The criteria is "+criteria);
if(criteria.equalsIgnoreCase("get_package_list"))
{
List<Package> packageList = packageDao.getPackageList();
Iterator <Package> itTemp = packageList.iterator();
JSONObject json=null;
JSONArray json_data_array= new JSONArray();
PrintWriter out= response.getWriter();
System.out.println("The List Size is "+packageList.size());
while(itTemp.hasNext())
{
Package packageTemp = itTemp.next();
json = new JSONObject();
try {
json.put("Id", packageTemp.getPackageId());
json.put("PackageName", packageTemp.getPackageName());
json_data_array.put(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
json = new JSONObject();
json.put("Id", "custom");
json.put("PackageName", "Customise Package");
json_data_array.put(json);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(json_data_array);
}
}
catch(Exception e)
{
e.getMessage();
e.printStackTrace();
}
}
}
我在火虫控制台中遇到的错误是 健康/ JSP / $%7BpageContext.request.contextPath%7D / PackageController 找不到404
答案 0 :(得分:0)
从ajax帖子中删除${pageContext.request.contextPath}
。
`$.post(
'PackageController',
{
-------`
希望这会对你有所帮助。