I have a situation in which I want to select all records from a database given a specific id. The request is first sent from JavaScript, which is received by a Servlet which accesses a DAO that in turn queries a database. The data will then, obviously, make its way back to the front-end. I'm just a little cloudy on passing these parameters along so that the database is queried correctly.
I am currently getting a 500 error which is due to my parameters not being passed along correctly.
Starting at the JavaScript with the initial request:
let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080/project1attempt/reimbursement?
employee_id=' + x._id, true);
xhr.send();
Receiving the parameters at the Servlet is my biggest point of confusion, therefore the code here is incomplete (rs is a Reimbursement Service):
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("application/json");
int id = ;
List<Reimbursement> reimbursements = rs.findAllReimbursements(id);
String json = new ObjectMapper().writeValueAsString(reimbursements);
resp.getWriter().write(json);
}
And the query:
public List<Reimbursement> findAllReimbursements(int id) {
List<Reimbursement> reimbursements = new ArrayList<>();
try
(Connection c = manager.getConnection()) {
String sql = "SELECT reimbursement_id, date, description, amount,
typing_id, employee_id" +
"FROM reimbursements" +
"WHERE reimbursement_id = ?";
PreparedStatement ps = c.prepareStatement(sql);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
Reimbursement r = null;
while (rs.next()) {
r = new Reimbursement();
r.setId(rs.getInt("reimbursement_id"));
r.setDate(rs.getDate("date"));
r.setDescription(rs.getString("description"));
r.setAmount(rs.getDouble("amount"));
r.setTypingId(rs.getInt("typing_id"));
r.setEmployeeId(rs.getInt("employee_id"));
reimbursements.add(r);
}
return reimbursements;
} catch (SQLException e) {
throw new BlabApplicationDataException("Could not connect to
Reimbursement Repository" + id);
}
}
You can use getParameter method of HttpServletRequest to get the URL parameter you need.
Probably, this is the line you are looking for.
String idStr = req.getParameter('employee_id');
if(idStr != null) {
int id = Integer.parseInt(idStr);
}
Related
how can i pass a JSON Array/Object with the JQUERY get Method to my Java Servlet?
So far , here's my code:
var json = {
MA_ID : $("#emplID").val(),
MA_Nachname : $("#nachname").val()
}
$.get(url + "/MA_Update", json)
[...]
MA_Update.java
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuffer jb = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
jb.append(line);
}
try {
JSONObject jsonObject = HTTP.toJSONObject(jb.toString());
System.out.println(jsonObject);
} catch (JSONException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
}
But I only get
{"Request-URI":"","Method":"","HTTP-Version":""}
from my request
Do not use request.getReader(), use request.getParameter("MA_ID") etc., or request.getParameterMap() (and iterate over it).
The thing is, that $.get(url, jsObject) creates a HTTP GET request, where the fields of the jsObject are transformed into query parameters, i.e. http://your.server.com/MA_Update?MA_ID=someID&MA_Nachname=SomeLastName, so they are NOT available in the request body (as they would be in a POST request).
I am trying to delete an item from shopping cart using Ajax with javascript, but I have trouble passing parameters to the controller. The parameters are null in controller.
My javascript code shows as below:
function removeRow(itemId, rowID){
if (xmlHttp == null)
{
alert("Your browser does not support AJAX!");
return;
}
var query = "action=remove&item=" + itemId;
/* alert(query); */
xmlHttp.onreadystatechange = function stateChanged()
{
if (xmlHttp.readyState == 4)
{
var row = document.getElementById(rowID);
row.parentNode.removeChild(row);
}
};
xmlHttp.open("GET", "addTo.htm", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(query);
return false;
/* var row = document.getElementById(rowID);
row.parentNode.removeChild(row); */
}
My controller code shows as below:
#Controller
#RequestMapping("/addTo.htm")
public class AddToController{
#RequestMapping(method=RequestMethod.GET)
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
String action = request.getParameter("action");
System.out.println(action);
ModelAndView mv = new ModelAndView();
ArrayList<Item> cart;
if(action.equals("remove")){
System.out.println("cart size is" + cart.size());
Long itemId = Long.parseLong(request.getParameter("item"));
ItemDAO itemDao= new ItemDAO();
Item item = itemDao.get(itemId);
cart.remove(item);
System.out.println(cart.size());
}
return mv;
}
}
The action and item are null in the controller.
Can anyone help with this problem?
You're sending a GET request, so add the parameters as a query after your URL:
xmlHttp.open("GET", "addTo.htm?" + query, true);
and pass in null (rather than your query string) when calling the .send method:
xmlHttp.send(null);
Also, the "application/x-www-form-urlencoded" header is only used when you're sending serialised parameters but using POST, so remove the xmlHttp.setRequestHeader line.
More info: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
I am attempting to pass a PDF I have generated on frontend javascript using jsPDF to a Spring Framework MVC backend. Below is the front end code I have written:
var filename = "thefile";
var constructURL = '/daas-rest-services/dashboard/pdfPrintUpload/' + filename;
var url = restService.getUrl(constructURL);
var fileBytes = btoa(pdf.output());
$http.post(url, fileBytes).success(function(data) {
console.log(data);
})
.error(function(e, a) {
console.log(e);
console.log(a);
});
The pdf variable has been generated properly and can confirm is opens correctly when calling pdf.save("filename"). Below is the Java code which has been written on the Spring MVC backend for this call:
#RequestMapping(method = RequestMethod.POST, value = "/pdfPrintUpload/{documentName}")
public #ResponseBody String postPrintDocument(#PathVariable String documentName, #RequestParam byte[] fileBytes) {
String methodName = "postPrintDocument";
if(logger.isLoggable(Level.FINER)){
logger.entering(CLASS_NAME, methodName);
}
String check;
if(fileBytes != null){
check = "not null";
} else {
check = "null ";
}
//Decoding the bytestream
//Save to file location
//return file location
String returnValue = "HI " + documentName + " " + check;
if (logger.isLoggable(Level.FINER)) {
logger.exiting(CLASS_NAME, methodName);
}
return returnValue;
}
Each time I make a request, I am getting 400 Errors telling me:
Error 400: Required byte[] parameter 'fileBytes' is not present
I can confirm in the request payload that a large amount of data is being transmitted, however the backend does not seem to want to accept the parameter.
The purpose of doing this is that I want to be able to get the data from the pdf and then decode it on the backend so I can later publish the pdf to a location on the server. Is there something I am missing in my code for these requests to keep failing, and is there an easier more efficient way to achieve this functionality?
The solution was changing the #RequestParam to #RequestBody. #RequestParam is a parameter which is sent in the path.
#RequestParam vs #PathVariable
Try using ng-file-upload. The link and the examples are available on the link
ng-file-upload
for the sever side code try using this
#RequestMapping(value = "/pdfPrintUpload")
#ResponseBody
public void postPrintDocument(#RequestParam("file") MultipartFile file) {
InputStream is = file.getInputStream();
OutputStream os = new FileOutputStream(/*path to save file*/);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0)
os.write(buffer, 0, length);
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This is my javascript part
<script language=javascript type="text/javascript">
function myFunction() {
var request = new XMLHttpRequest();
request.open("GET", "http://localhost:8080/Test/Servlet");
request.send();
//document.write("Request GET enviado!");
}
</script>
This is my doGEt part
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Request GET recebido!");
// JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/Tests";
// Database credentials
String USER = "fabio";
String PASS = "hacking";
Connection conn = null;
Statement stmt = null;
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM people";
ResultSet rs = stmt.executeQuery(sql);
out.println("<html><body>");
// Extract data from result set
while (rs.next()) {
//Retrieve by column name
int person_id = rs.getInt("person_id");
String first_name = rs.getString("first_name");
String last_name = rs.getString("last_name");
//Display values
out.println("Person ID: " + person_id + " | ");
out.println("First name: " + first_name + " | ");
out.println("Last name: " + last_name + "<br>");
}
out.println("</body></html>");
// Clean-up environment
out.close();
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println(e);
}
}
They work until the point that data is retrieved from DB. The part that does not work is posting the out.println back to HTML page. Could someone please advise?
Thanks,
It is not obvious for me from the question if you did anything with the response like this:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
var respdiv = document.getElementById("respdiv");
respdiv.innerHTML = "Response=" + xhr.responseText;
}
xhr.open("GET", "http://localhost:8080/Test/Servlet", true);
xhr.send(null);
Also it was interesting that running in built in eclipse browser it responded with "hello" instead of "SOMETHING" (did not check why) but worked when opened in chrome.
doGet code:
PrintWriter out = response.getWriter();
out.println("SOMETHING");
out.flush();
out.close();
I am trying send a file to a servlet.
function sendToServlet(){
var file = Components.classes["#mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("C:\\Documents and Settings\\me\\Meus documentos\\Downloads\\music.mp3");
var boundary = "--------------" + (new Date).getTime();
var stream = Components.classes["#mozilla.org/network/file-input-stream;1"]
.createInstance(Components.interfaces.nsIFileInputStream);
stream.init(file, 0x04 | 0x08, 0644, 0x04); // file is an nsIFile instance
// Send
var req = Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
req.open('POST', 'http://localhost:8080/app/server' , false);
var contentType = "multipart/form-data; boundary=" + boundary;
req.setRequestHeader("Content-Type", contentType);
req.send(stream);
}
The source of javascript:
https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest#Sending_binary_data
But does not work.
Hi, this the serlevt code used:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int size = 1024*20000;
long sizeFile = 0;
File savedFile = null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(new Long("-1"));
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
try {
if (item.isFormField()) {
;
}else{
String itemName = item.getName();
int sizeName = itemName.length();
int end = itemName.indexOf('\n');
int start = itemName.lastIndexOf('\\');
itemName = itemName.substring(start + 1, sizeName-end-1);
savedFile = new File("C:\\Documents and Settings\\eric.silva\\Meus documentos\\"+itemName);
item.write(savedFile);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}//metodo
But when i try to send a file the servlet dont create the file sent.
Quando eu tento enviar via javascript a requisição é enviada. Mas o arquivo não é criado no lado do servidor. Acredito que o código apresentado no site da MDN esteja incompleto.
When I try to send via javascript the request is sent. But the file is not created on the server side. I believe the code shown on the site of the MDN is incomplete.
Note how the example code you are using is sending data with method PUT - valid multipart-formdata request needs to have some additional headers, not only the file itself. For example, the file you are sending should have a name (normally the name of the form field). You should use a FormData object instead, it will generate a valid request automatically. You should be able to create a File object directly. Something along these lines:
var file = File("C:\\Documents and Settings\\me\\Meus documentos\\Downloads\\music.mp3");
var data = new FormData();
data.append("file", file);
var req = Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
req.open('POST', 'http://localhost:8080/app/server', false);
request.send(data);
Note that creating File objects like this is only supported starting with Firefox 6.
The problem lies more likely in how you're trying to obtain the uploaded file with the servlet. Being a low level impelementation, the servlet doesn't have much of an abstraction for handling uploaded files (multi part requests). Luckily there are libraries who take care of that for you like commons.FileUpload:
http://commons.apache.org/fileupload/using.html
Just set up a servlet with fileUpload like it sais in the doc, then make a simple html page with a form that has a file upload input, and use that as a basic functional test to see that it works, then return to making your own client.