here's my js code :
function sendMP3ViaAJAX(MP3File) {
console.log(MP3File.name); //file is present, as I can get its name
$.ajax({type: "POST",
url: "saveMP3",
enctype: 'multipart/form-data',
processData: false,
data: {'mp3File': MP3File},
success: function (text)
{
response = text;
},
complete: function () {
$("#retourAJAX").html("blah blah");
}
});
}
but if I debug my Project
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part part = request.getPart("MP3FILE"); //request.parts is null...
(constant CHAMP_FICHIER equals the one defined in AJAX call, i.e. mp3File ...) Do you know what's missing ? As I already have dynamically loaded content on the page, I don't want the default HTML POST submit behavior to happen...
Related
I am working on a jsp application and I have a download zip file feature
I have done
#RequestMapping(value = {"/retrieve"}, method = RequestMethod.POST)
public void logDownload(#RequestBody ResponseDto responseDto, Model model, HttpServletResponse response) throws ServletException, IOException {
Byte[] arraObj=downloadService.getdownloadFile();
response.setContentType("application/octate-stream");
response.setHeader("Content-Disposition","attachment;filename=user.zip",
response.getOutputStream().write(arraObj);
}
I am making a ajax call for this controller
JSP Side code
$.ajax({
type: 'POST',
url: "${pageContext.request.contextPath}/retrieve",
headers: { "X-CSRF-TOKEN": token },
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(retrieveDto),
success: function (res) {
window.location = "${pageContext.request.contextPath}/result";
},
error: function (e) {
// window.location="${pageContext.request.contextPath}/result";
console.log("There was an error with your request..." + JSON.stringify(e));
}
});
I am unable to download the file
Can someone tell me how to fix this issue
I am trying to read a json object that I sent from my ajax to servlet but then I keep receiving null as the value. I tried to log the json object that I am sending from my ajax and it looks fine to me. Can someone tell me what could be my error?
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
event.preventDefault();
var data = $("#register").serialize().split("&");
var obj={};
for(var key in data)
{
console.log(data[key]);
obj[data[key].split("=")[0]] = data[key].split("=")[1];
}
console.log(obj);
$.ajax({
type: "POST",
url: "HomeServlet",
dataType:'json',
data:JSON.stringify(obj),
success: function(data){
console.log(data);
},
error:function(){
console.log("error");
},
});
});
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out= response.getWriter();
String data = request.getParameter("obj");//this is what I get as null
String n = request.getParameter("apiname");
String p = request.getParameter("apiendpoint");
String e = request.getParameter("apiversion");
}
The json object that I am sending
{
"apiname": "jdjdj",
"apiendpoint": "sdjsdj",
"apiversion": "djdjd",
"source": "internet"
}
I am trying to set up a login page for my website, however at the moment I am stuck on the sendRedirect method, as it doesn't appear to load a new page when required.
My login page is a .jsp file that passes the username and password information via AngularJS $scope to the servlet, which contains the following code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("Redirecting...");
response.sendRedirect("https://www.youtube.com/");
return;
}
The System.out.println("Redirecting..."); works, however it does not redirect to the URL provided, no matter what that is. I have read other advice which mentioned to add the return; line, and I have tried other URLs specific to my project (e.g. index.jsp, \index.jsp, etc.), however none of these have made a difference and it still does not work.
Would window.location be a more suitable approach for this? What code should I be modifying here?
So I've made the webpage finally redirect correctly and I'm posting this just in case someone else stumbles upon the same issue.
As mentioned in previous comments, the response should be sent from the Java servlet to AngularJS, I have made the redirection occur as follows in my logincontroller.js file:
var app = angular.module('myApp', []);
function LoginController($scope, $http, $window)
{
$scope.login = function()
{
$http({
url: 'login',
method: 'POST',
data:
{
'username': $scope.username,
'password': $scope.password
}
}).success(function(data, status, headers, config) {
alert("SUCCESS! Data: " + data);
$scope.details = data;
$window.location.href = "home.jsp"; //This line redirects.
}).error(function(data, status, headers, config) {
alert('ERROR!');
});
};
};
I am trying to make a simple ajax call. No matter what I do, it always executes the error block. I have a sysout in the doPost that is never hit. Someone please tell me what I am doing wrong. Here is my code.
javascript----
$.ajax({
url: "GetBulletAjax",
dataType: 'json',
success: function(data) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR+" - "+textStatus+" - "+errorThrown);
}
});
Java----
public class GetBulletAjax extends HttpServlet {
private static final long serialVersionUID = 1L;
public GetBulletAjax() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("made it to servlet");
PrintWriter out = response.getWriter();
User user = (User) request.getSession().getAttribute("user");
int userId = user.getId();
List<Bullet> bullets;
BulletDAO bulletdao = new BulletDAOImpl();
try {
bullets = bulletdao.findBulletsByUser(userId);
Gson gson = new Gson();
String json = gson.toJson(bullets);
System.out.println(json);
out.println(json);
out.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
web.xml----
<servlet>
<servlet-name>GetBulletAjax</servlet-name>
<servlet-class>bulletAjax.GetBulletAjax</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetBulletAjax</servlet-name>
<url-pattern>/GetBulletAjax</url-pattern>
</servlet-mapping>
What's the URL for your client? Your URL is going to be relative -- so if your page's URL is <server>/foo/bar.html, your ajax request is going to go to <server>/foo/GetBulletAjax. But your servlet definition is <server>/GetBulletAjax.
Change your url in your ajax request to /GetBulletAjax. You need the leading forward slash to tell the browser the resource is located off the root of the site.
in Jquery documentation
http://api.jquery.com/jQuery.ajax/
type (default: 'GET')
Type: String
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
seems that you miss the type attribute which needs to be POST. default is GET as mentioned by documentation. You dont have a doGet in your servlet to support that.
$.ajax({
url: "GetBulletAjax",
dataType: 'json',
type:POST,
success: function(data) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR+" - "+textStatus+" - "+errorThrown);
}
});
Here is my Ajax code:
var email="abc#abc.com";
$.ajax({
url : "ships",
data : "{email" + email.toString() + "}",
success : function(data){
alert(data)
},
error : function(data) {
console.log("error:", data);
},
type : "post"
});
And here is my Java Servlet code:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameter("email"));
}
I CANNOT read data in Java Servlet The console prints out the following value for email:
null
I am using Tomcat 7
Can anyone please tell me what i am doing wrong and why i cannot read data in Java Servlet_
The property data of the param object is a JavaScript object, so to send a parameter named EmailAddress you would do:
...
url : "ships",
data : {
EmailAddress: email.toString()
},
success : function(data){
...