Trying to post form data to servlet using JQuery - java

I am attempting to post data to a servlet where it will be inserted in to a mysql database.
Here is the html form:
<form id="commentForm" name="commentForm" action="http://server.co.uk/dbh" method="POST">
<input type="text" name="name" placeholder="Your name" required="required">
<textarea name="comment" placeholder="Enter your comment here" required="required"></textarea>
<input type="hidden" name="postID" id="postID" value="<%= postID %>">
<input type="submit" name="submit" id="commentSubmit" value="submit">
</form>
The Jquery:
$("#commentSubmit").click(function(e){
var postData = $("#commentForm").serializeArray();
var formURL = $("#commentForm").attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$("#commentFormWrap").html("<p>Success</p>");
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#commentFormWrap").html("<p>error: "+errorThrown+"</p>");
}
});
e.preventDefault(); //STOP default action
$("#commentForm").hide();
});
A simplified dbh servlet:
import javax.servlet.annotation.WebServlet;
...
#WebServlet(description = "Handles connection to MySql database", urlPatterns = { "/dbh" })
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
postArray = request.getParameterValues("postData");
commentName = postArray[0];
comment = postArray[1];
postID = Integer.parseInt(postArray[3]);
try{
submitComment();
}catch(Exception e){
e.printStackTrace();
}
}
public void submitComment() throws Exception{
try{
sql="INSERT INTO crm_comments (comment_name, comment_content, comment_date, post_id) VALUES (?, ?, NOW(), ?)";
prep = conn.prepareStatement(sql);
prep.setString(1, commentName);
prep.setString(2, comment);
prep.setInt(3, postID);
rs = prep.executeQuery();
}catch(Exception e){
e.printStackTrace();
}
}
Currently the ajax call is returning the error block error:. But nothing as the errorThrown variable.
From what I can see the servlet is written correctly. Is there something wrong between the html and the Jquery ajax call, that it isn't posting the data to the servlet?

postArray = request.getParameterValues("postData");
I think you can replace this with actual field names
commentName = request.getParameter("name");
comment = request.getParameter("comment");
this will solve your problem

According to the jQuery documentation, the serializeArray method returns a JavaScript array of objects. This method will generate a JSON object from your form, that will look like: [{"name":"name",value:"<your name input value>"},{"name":"comment",value:"<your comment>"},{"name":"postID",value:"<postID value>"} ...]. Only the content of the postData variable will be sent: you won't have any reference at all to that postData keyword in your Servlet.
So in your Servlet, the request.getParameterValues("postData"); call seems to be invalid. Try this instead:
commentName = request.getParameterValues("name");
comment = request.getParameterValues("comment");
postID = Integer.parseInt(request.getParameterValues("postID"));

Related

How can i require and print an object array beetwen a jsp page and a servlet using JQuery?

How can i print messages2 into div class=chat?
A message is composed by:
- Id
- Text
I can't read JSON file which servlet send to me with my JQuery function.
I'm new in JQuery and this script isn't mine but i used it because it works to send messages to servelt.
This is my form where i will take a text from input.
home.jsp
<form method="post" id="messageForm" enctype="multipart/form-data">
<div class="chat">
//where i will print the array
</div>
<div class="send">
<div class="text-message-container">
<input type="text" name="testMessage" class="text-message" id="toSend">
<button type="submit" class="send-message" onclick="addMessage();" ><img src="img/send1.png" class="img-send"></button>
</div>
</div>
</form>
<script>
function addMessage(){
if(window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState === 4 && xhttp.status === 200) {
var myArr = JSON.parse(xhttp.responseText);
}
}
xhttp.open("POST","messageServlet",true);
var formData = new FormData(document.getElementById('messageForm'));
xhttp.send(formData);
}
else console.log('not working');
} </script>
This is my Servlet:
#WebServlet(name = "messageServlet", urlPatterns = {"/messageServlet"})
#MultipartConfig
public class messageServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String msg = req.getParameter("testMessage");
SessionFactory factory = session.getSessionFactory();
Session s = factory.openSession();
Message m = new Message();
m.setMessage(msg);
s.beginTransaction();
s.save(m);
s.getTransaction().commit();
List<Message> messages2 = s.createQuery("From Message").list();
String json = new Gson().toJson(messages2);
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write(json);
}
Your home.jsp has a syntax error in the Javascript code:
var myArr = JSON.parse(
Everything else looks fine as far as I can see.

not responding while sending json object from jsp to servlet

This is not functioning. What might be the error? I wanted to get name and password from clientside in the form of json to servlet.
index.jsp
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js”>
</script>
<script type="text/html">
function callFun(){
var n = document.getElementById('n1').value;
var p = document.getElementById('n2').value;
var myData = {"mydata" :{"name":n,"password":p}};
$.ajax({
type:'POST',
url:'/Page',
data:{jsonData:JSON.stringify(myData)},
dataType:'json',
success:function(data){
alert(json["resultText"]);
}
});
}
</script>
<form>
Name:<input type="text" name="nam" id="n1"><br>
Password:<input type="password" name="password" id="n2"><br>
<input type="button" onclick="callFun()" value="submit">
</form>
this is servlet class Page.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject newObj = new JSONObject();
try(){
String json = request.getParameter("jsonData");
JSONObject jsonData = (JSONObject) JSONValue.parse(json);
String name = (String) jsonData.get("name");
System.out.println(name));
}catch(JSONException e){
e.printStackTrace();
}
}
Did you mean alert(data["resultText"]);
Also note you are using an old version of Jquery AJAX. Check the official Jquery AJAX guide for current version. In current version you can use .fail call to get the error message
var request = $.ajax({
url: "script.php",
method: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$( "#log" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus ); //Dipslay the error here
});

Send image to mySQL with servlet, ajax, jquery [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet and Ajax?
(4 answers)
Closed 7 years ago.
Trying to upload a file to my servlet without page refresh with ajax.
Been stuck at this for some days now, and just can't let it go.
my form:
<form method="POST" id="changeImage2" enctype="multipart/form-data">
<input type="file" name="photo" /> <br>
<input type="button" value="Change Picture" id="changeImage1">
</form>
my servlet:
#MultipartConfig
public class changeImage extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
Part filePart = req.getPart("photo");
Object email = req.getSession().getAttribute("email");
Object name = req.getSession().getAttribute("name");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection myConn = DriverManager.getConnection("", "", "");
PreparedStatement ps = myConn.prepareStatement("update user set profilePicture=? where email=? and name=?");
ps.setBlob(1, filePart.getInputStream());
ps.setString(2, (String) email);
ps.setString(3, (String) name);
ps.executeUpdate();
} catch (Exception e){
e.printStackTrace();
}
}
}
my ajax/jquery:
<script>
$(document).ready(function() {
$('#changeImage1').click(function() {
var dataForm = $('#changeImage2').serialize();
$.ajax({
type : 'POST',
url : 'changeImage',
data : dataForm,
success : function(data) {
$('#gg1').text(data);
},
error : function() {
$('#gg1').text("Fail");
},
});
});
});
</script>
When running this I get the error:
SEVERE: Servlet.service() for servlet [changeImage] in context with
path [/Event] threw exception
[org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException:
the request doesn't contain a multipart/form-data or
multipart/form-data stream, content type header is null] with root
cause
org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException:
the request doesn't contain a multipart/form-data or
multipart/form-data stream, content type header is null
I tried use another form and do without the ajax/jquery:
<form action="changeImage" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Change Picture" />
</form>
With this it works. So I'm guessing the JDBC and Servlet is sat up properly. And that I'm not using Ajax/Jquery properly.
In your code you write:
ps.setBlob(5, (Blob) InputStream);
According to javadoc for PreparedStatement this int, 5 is the parameter index. As the error is stating you only have 3 parameters.
You need to change this to 3? - looking at your SQL statement I think you may have forgotten you have copied and pasted from somewhere and haven't yet edited it.
These lines are the problem, you can't use Part object as Blob or InputStream. A cast exception should happen there.
Part filePart = req.getPart("photo");
Part InputStream = filePart; //this line is not needed at all
ps.setBlob(1, (Blob) InputStream);
Try something like this
ps.setBlob(1, filePart.getInputStream());
or
ps.setBinaryStream(1, filePart.getInputStream());

How to pass multiple values to servlet using Jquery

I have an Html form from that i need to pass values to servlet using jquery and there it will validates the information and returns the result.But when i try to pass the data using jQuery.
The servlet showing that null value received.
<div class="ulogin">
<h2>Login</h2>
<div id="error"></div>
<form action="Login" method="post" id="spsignin">
<input type="text" name="uname" class="text validate[required]" id="name" placeholder="Username"/>
<input type="password" name="pass" class="text validate[required]" id="password" placeholder="Password"/>
<input type="submit" value="" id="memberlogin"/>
</form>
</div>
My javascript file is
$(document).ready(function() {
//Stops the submit request
$("#spsignin").submit(function(e){
e.preventDefault();
});
//checks for the button click event
$("#memberlogin").click(function(e){
//get the form data and then serialize that
dataString = $("#spsignin").serialize();
dataString1 = $("#spsignin").serialize();
var uname = $("input#name").val();
var pass = $("input#password").val();
$.ajax({
type: "POST",
url: "Login",
data:'uname=' +encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass),
dataType: "json",
//if received a response from the server
success: function( data, textStatus, jqXHR) {
if(data.success)
{
$("#error").html("<div><b>success!</b></div>"+data);
}
//display error message
else {
$("#error").html("<div><b>Information is Invalid!</b></div>"+data);
}
},
//If there was no resonse from the server
error: function(jqXHR, textStatus, errorThrown){
console.log("Something really bad happened " + textStatus);
$("#error").html(jqXHR.responseText);
},
//capture the request before it was sent to server
beforeSend: function(jqXHR, settings){
//disable the button until we get the response
$('#memberlogin').attr("disabled", true);
},
complete: function(jqXHR, textStatus){
//enable the button
$('#memberlogin').attr("disabled", false);
}
});
});
});
And the servlet is
package skypark;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Login
*/
#WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
Boolean success=true;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
super();
// TODO Auto-generated constructor stub
}
public static Connection prepareConnection()throws ClassNotFoundException,SQLException
{
String dcn="oracle.jdbc.OracleDriver";
String url="jdbc:oracle:thin:#//localhost:1521/skypark";
String usname="system";
String pass="tiger";
Class.forName(dcn);
return DriverManager.getConnection(url,usname,pass);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String uname,pass;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
response.setContentType("text/html");
response.setHeader("Cache-control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Max-Age", "86400");
uname=request.getParameter("uname");
pass=request.getParameter("pass");
Boolean suc;
try {
suc = check(uname,pass);
out.println(suc);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.flush();
out.close();
}
public Boolean check(String uname,String pass) throws SQLException, ClassNotFoundException
{
ResultSet rs = null;
int i=0;
Connection con=prepareConnection();
String Query="select uname,email from passmanager where pass=?";
PreparedStatement ps=con.prepareStatement(Query);
try
{
ps.setString(1,pass);
rs=ps.executeQuery();
while(rs.next())
{
if (uname.equalsIgnoreCase(rs.getString("uname")) || uname.equalsIgnoreCase(rs.getString("email")))
{
rs.close();
ps.close();
ps = null; con.close();
con = null;
success=true;
i=1;
break;
}
}
}
catch(Exception e)
{
System.out.println(e);
}
if(i==0)
{
success=false;
}
return success;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request,response);
}
}
I think error is with jquery. please any one help me to overcome from this...
The problem is with this line:
data:'uname=' +encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass)
which should be
data: 'uname='+encodeURIComponent(uname)+'&'+'pass='+encodeURIComponent(pass)
note the missing + after encodeURIComponent(uname)
I spot one little error on your Ajax script, your ampersand sign is not part of the string:
data:'uname=' + encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass),
should be
data:'uname=' + encodeURIComponent(uname) + '&pass=' + encodeURIComponent(pass),
If that doesn't fix it then here's few more things you can check:
Check you only have one input element with id 'name' on your html
Check your request went to right servlet on your servlet mapping
Check you don't have any filters that intercepts and modify / redirect requests
Other than that your code seem fine
well the issue has been cleared already but other than passing the values one by one you can submit the whole form at once ,have a look at this .
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing spinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
and you form would be like this
<form id="tempForm" enctype="multipart/form-data">
<input type="text" name="" id="" />
<input type="text" name="" id="" />
<input type="file" name="" id="" />
</form>
and you can find the plug in enter link description here

java.io.EOFException: No content to map to Object due to end of input Spring MVC Jackson Processor

I am using Spring MVC and JSP to send JSON to Spring MVC Controller. Actually, my JSON works for 1 method but does not work for another and I don't understand why. The code is below:
JSP - index.jsp
<%#page language="java" contentType="text/html"%>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#myForm').submit(function() {
var form = $( this ),
url = form.attr('action'),
userId = form.find('input[name="userId"]').val(),
dat = JSON.stringify({ "userId" : userId });
$.ajax({
url : url,
type : "POST",
traditional : true,
contentType : "application/json",
dataType : "json",
data : dat,
success : function (response) {
alert('success ' + response);
},
error : function (response) {
alert('error ' + response);
},
});
return false;
});
});
</script>
<script type="text/javascript">
$(function() {
$('#emailForm').submit(function() {
var form = $( this ),
url = form.attr('action'),
from = form.find('input[name="from"]').val(),
to = form.find('input[name="to"]').val(),
body = form.find('input[name="body"]').val(),
subject = form.find('input[name="subject"]').val(),
fileName = form.find('input[name="fileName"]').val(),
location = form.find('input[name="location"]').val(),
dat = JSON.stringify({ "from" : from,"to" : to,"body" : body,"subject" : subject,"fileName" : fileName,"location" : location });
$.ajax({
url : url,
type : "GET",
traditional : true,
contentType : "application/json",
dataType : "json",
data : dat,
success : function (response) {
alert('success ' + response);
},
error : function (response) {
alert('error ' + response);
},
});
return false;
});
});
</script>
</head>
<body>
<h2>Application</h2>
<form id="myForm" action="/application/history/save" method="POST">
<input type="text" name="userId" value="JUnit">
<input type="submit" value="Submit">
</form>
<form id="emailForm" action="/application/emailService/sendEmail" method="GET">
<input type="text" name="from" value="name#localhost.com">
<input type="text" name="to" value="user#localhost.com">
<input type="text" name="body" value="JUnit E-mail">
<input type="text" name="subject" value="Email">
<input type="text" name="fileName" value="attachment">
<input type="text" name="location" value="location">
<input type="submit" value="Send Email">
</form>
</body>
</html>
The 1st form works correctly and is deserilized in Spring MVC. A sample of that code is:
#Controller
#RequestMapping("/history/*")
public class HistoryController {
#RequestMapping(value = "save", method = RequestMethod.POST, headers = {"content-type=application/json"})
public #ResponseBody UserResponse save(#RequestBody User user) throws Exception {
UserResponse userResponse = new UserResponse();
return userResponse;
}
For the 2nd form I am getting exceptions:
#Controller
#RequestMapping("/emailService/*")
public class EmailController {
#RequestMapping(value = "sendEmail", method = RequestMethod.GET, headers = {"content-type=application/json"})
public void sendEmail(#RequestBody Email email) {
System.out.println("Email Body:" + " " + email.getBody());
System.out.println("Email To: " + " " + email.getTo());
}
}
Below is the stack trace:
java.io.EOFException: No content to map to Object due to end of input
org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2022)
org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1974)
org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1331)
org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:135)
org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:154)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.readWithMessageConverters(HandlerMethodInvoker.java:633)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestBody(HandlerMethodInvoker.java:597)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:346)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
I have tried using the POST too, but still the same problem. I need to use JSP to send JSON data to the Spring MVC Controller.
I am not sure where the problem is.
beans.xml
<context:component-scan base-package="com.web"/>
<mvc:annotation-driven/>
<context:annotation-config/>
Any ideas?
EDIT
public class Email implements Serializable {
private String from;
private String to;
private String body;
private String subject;
private String fileName;
private String location;
public Email() {
}
// Getters and setters
}
JSON sent is in form2 which is #emailForm.
You should check if you have set "content-length" header.
I ran into the same problem, but I used curl to verify the server side function.
The initial data section in my curl command is
-d "{'id':'123456', 'name':'QWERT'}"
After I changed the command to
-d '{"id":"123456", "name":"QWERT"}'
then it worked.
Hope this gives some hints.
I had this problem when I tried to use POST method with path parameter, but I forgot to put '#PathParam("id") Integer id', I just had 'Integer id ' in parameters.

Categories

Resources