I am developing WEB PROJECT using JSP and SERVLET.
I am trying to upload file using AJAX called.
File is successfully uploaded.
but, while ajax called controller (servlet file) send request and response object to jsp file.
JSP file
$(document).ready(function(){
$(':file').change(function(){
var fileObj = this.files[0];
var form = $('#mOBJ');
var fd = new FormData();
fd.append( 'file', fileObj);
$.ajax({
url:form.attr('action'),
type:form.attr('method'),
data:fd,
processData: false,
contentType: false,
async:false,
}).done(function(){
alert('ajax complete');
////////////////////////////////////////////////////////////////
Here i am getting old request value.
I want new request and response object after ajax called.
var Check2Bool = <%=context.getAttribute("comeFromUploadTemp")%>;
var check2 = <%=request.getAttribute("comeFromUploadTemp")%>;
alert(Check2Bool + " " + check2);
}).fail(function() {
alert( "error" );
$('#ldiv').hide();
});
});
Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext();
/**
* Display XML file to the user
*/
TemplateVO template = null;
TemplateUtil util = new TemplateUtil();
//Prepare XML file path
String path=(String) context.getAttribute(Constants.USER_DIR);
String strFilePath = null;
//Upload XML file
if(ServletFileUpload.isMultipartContent(request)){
try{
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
request.setAttribute("FileName",name);
String path1 = path + File.separator + "data-in";
strFilePath = FileUtil.createFileOnFileSystem(item,path1,name,"xml");
}
}
}catch(Exception ex){
ex.printStackTrace();
}
}
//set variables into Request Object
template = util.readXML(strFilePath);
context.setAttribute("comeFromUploadTemp", true);
request.setAttribute("comeFromUploadTemp", true);
request.getRequestDispatcher("mappingObject.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
the request is JSP workspace, notajax.
u should pass data through response i.o. request.
like:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//... your code here
response.getOutputStream().write(data);
}
then u can parse response and get data as you want.
http://www.coderanch.com/t/522069/Servlets/java/Adding-Custom-Data-Response-Headers
http://www.w3schools.com/ajax/ajax_xmlhttprequest_response.asp
Related
I have a local directory which contains some images. I am trying to display the list of images from the local directory but nothing is displayed. I am getting the error exception handling message that the directory is empty.I don't know what I am doing wrong.
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List imgUrlList = new ArrayList();
File imageDir = new File("/images");
File[] files=imageDir.listFiles();
if(files!=null) {
for (File imageFile : files) {
String imageFileName = imageFile.getName();
imgUrlList.add(imageFileName);
}
}
else {
System.out.println("directory is empty");
}
req.setAttribute("imgUrlList", imgUrlList);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/test/test.jsp");
dispatcher.forward(req, resp);
}
<c:forEach var="img" items="${imgUrlList}"> <img > </c:forEach>
Not sure how to solve this, need some help here.
Ajax call brings user information to servlet, I save user object in HttpSession and control goes back to Ajax from where i redirect control to next JSP page via controller servlet. However, if i try to retrieve object from HttpSession it is null .. not sure how to solve this issue.
here is my code for firstservlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get values from http request
// persist "user" object to database
HttpSession session = request.getSession(); //
session.setAttribute("user", user); //setting session variable
Gson gson = new Gson();
JsonElement jsonElement = null;
jsonElement = gson.toJsonTree("/nextservlet");
response.setContentType("text/plain");
PrintWriter out=response.getWriter();
}
here is my Javascript / AJAX code to redirect request to nextservlet
$.ajax({
type: 'POST',
url: ‘firstservlet’,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(quiz),
success: function(result) {
//result = /nextservlet
window.location.href = result;
},
error:function(data,status,er) {
console.log("Error:",er);
}
});
and finally control comes to nextservlet - where i would like to process data and then show new JSP page.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession();
User user = session.getAttribute(“user”); //<--- this is NULL
LOG.warning("User id is : " + user.getId()); //<--- hence error here
RequestDispatcher dispatcher = request.getRequestDispatcher
("/anotherpage.jsp");
dispatcher.forward(request, response);
}
is issue because i am using -> window.location.href = result to send request to nextservlet .. and it goes to doGet??
I am not sure it but I see in Ajax
url: ‘firstservlet’,
type: 'POST'
and control goes to doGet method of nextservlet. It should be nextservlet of post method so use method doPost.
18.12.22
i'm not sure... but try it
success: function(result) {
// result = /nextservlet
var form = document.createElement('form');
form.action = result;
form.method = 'GET'
form.submit();
}
18.12.26
Javascript
$.ajax({
type: 'POST',
url: '/firstservlet',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringfy(quiz),
success: function(result) {
console.info(result);
var form = document.createElement('form');
form.action = result;
form.method = 'GET';
document.body.appendChild(form);
form.submit();
},
error: function(data, status, err) {
console.log("Error: ", err);
}
});
Servlet
HttpSession session = request.getSession();
session.setAttribute("test", "test");
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree("/nextservlet");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.print(gson.toJson(jsonElement));
It can read session attribute in doGet Method try it.
I have to write a controller in my project using servlets. I've done it before but I've never worked with AngularJS, so I did it via request.setAttribute() and request.getParameter() and put Java code inside of a JSP page. But now frontend developer used AngularJS and I have to return him a JSON object. And I have no idea how to do it. Here's the code of abTestCtrl.js:
app.controller("abTestCtrl", function($scope, $location, $http) {
$scope.title = "no title";
$scope.description = "no description";
$scope.getParam = $location.search()['id'];
if($scope.getParam === undefined)$scope.getParam = 0;
//$scope.getParam=2;
//path: localhost8080/UIUM.../servlet-name.java
//with two ids
//web.xml: serverlet mapping for the path
if($scope.getParam==='0'||$scope.getParam === 0){
var saveButton = document.getElementById("saveButton");
saveButton.classList.remove("hidden");
}
else{
$http.get('http://localhost:8080/UIUM_IMT4003/ABTestController', {command:'getTestCaseInfo', testcaseID:$scope.getParam}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log('request succesful');
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('request not succesful');
});
}
and my processRequest() code from the servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, ClassNotFoundException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json; charset=UTF-8");
//PrintWriter printout = response.getWriter();
JSONObject jObject = null;
RequestDispatcher view = null;
TestcaseRepository testcaseRepo = new TestcaseRepository();
String command = request.getParameter("command");
if(command == null)
{
view = request.getRequestDispatcher("/testcases.jsp");
view.forward(request, response);
}
if(command.equals("getTestCaseInfo")){
String testcaseId = request.getParameter("testcaseID");
Testcase testcase = testcaseRepo.getTestcaseById(testcaseId);
jObject = new JSONObject();
jObject.put("id", testcaseId);
jObject.put("title", testcase.getTestcaseName());
jObject.put("testscenario", testcase.getTestcaseDescription());
// printout.print(jObject);
// printout.flush();
jObject.write(response.getWriter());
}
Can you please help me to process this request and finally return this poor JSON!
BTW, Servlet doesn't recognize command parameter. It gets null. But there is such parameter in AngularJS function.
Try using the javax.json.JsonObject as follow:
JsonObject jo=Json.createObjectBuilder()
.add("id", testcaseId)
.add("title", testcase.getTestcaseName())
.add("testscenario", testcase.getTestcaseDescription()).build();
Then set the response content type to json and send your json object in the response:
response.setContentType("application/json");// set content to json
PrintWriter out = response.getWriter();
out.print(jo);
out.flush();
I am having formData that contains a file
Like :
var files = document.getElementById("uploadfile").files;
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
var file = files[0];
alert(file.name);
formData.append('uploadfile', file, file.name);
client.open("POST", "fileupload?q="+uploadfile,true);
client.setRequestHeader("Content-Type", "multipart/form-data");
client.send(formData); /* Send to server */
Now i want to use this form data in my servlet fileupload.How to use it their ?Please help.
I am giving an example how I handled it in my project. I used doPost function to get it.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
Do whatever you want with that item.
}
I'm doing file upload using XMLHttpRequest() in my jsp and when I do request.getContentType() in my controller I'm getting:
multipart/form-data; boundary=---------------------------4664151417711.
Further I'm not getting how to get the file and get the contents of it in my controller. Please anyone help.
Update --
I'm doing this in my jsp.
function fileUpload() {
var url= document.getElementById("urlId").value;
var file= document.getElementById("xslId").files[0];
var formdata = new FormData();
formdata.append("url", url);
formdata.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open("POST","http://localhost:8080/XlsUpload/openSource.htm", true);
xhr.send(formdata);
xhr.onload = function(e) {
};
}
and in my controller--
public void openSource(#ModelAttribute("domTool") DomTool domTool,HttpServletRequest request,HttpServletResponse response){
String type=request.getContentType();
Further I'm struck how to get the contents of the uploaded file and the value of text field i.e.,URL in my controller. The type i'm getting as multipart/form-data
There is an Apache commons solution called commons-fileupload for parsing multipart content. You can find it here.
The most simple example copied from their tutorial looks like this:
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
// iterate over items (i.e. list of FileItem) and access
// the content with getInputStream()
}