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
});
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to send a file from my jsp to controller via ajax, im getting EXCEPTION:Null Error, below is my code:
Controller:
#RequestMapping(value = "/schedulebatch",method =
RequestMethod.POST,params="insertData")
public #ResponseBody String addBatch(#RequestParam(
#RequestParam(value="upfile",required=false) MultipartFile upfile) throws
Exception { if(!upfile.isEmpty()){
System.out.println("test1");}
View:
$("#submit-btn").click(function(){
var upfile = document.getElementById('upfile').enctypeVIEW;
alert('test');
if(batchname==null || fromdate == null || partners == null || interval ==
null){
$('#insertmodalalert').empty();
$('#insertmodalalert').append('<div class="alert alert-info"><strong
>NOTICE |</strong> Please fill out the required form. </div>');
$('#alertMod').modal();
$('#okbtn').click(function(){
window.location.reload(true);
});
}
else{
$.ajax({
type: "POST",
url: "schedulebatch?insertData",
data: {"upfile" : upfile},
success: function(response){
// alert('test');
$('#insertmodalalert').empty();
$('#insertmodalalert').append('<div class="alert alert-
info"><strong >NOTICE |</strong> '+response+' </div>');
$('#alertMod').modal();
$('#okbtn').click(function(){
$('#alertMod').modal('hide');
window.location.reload(true);
});
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
// alert('test');
// Display the specific error raised by the server
(e.g. not a
// valid value for Int32, or attempted to divide by
zero).
$('#insertmodalalert').append('<div class="alert
alert-danger"><strong >NOTICE |</strong> '+err.Message+'</div>');
$('#activateMod').modal();
$('#okbtn').click(function(){
$('#alertMod').modal('hide');
window.location.reload(true);
});
}
});
//alert("Test");
}
HTML:
File to upload: <input class="form-control" type="file" name="upfile"
accept=".csv" id="upfile">
<button type="submit" class="btn btn-success" id="submit-
btn">Submit</button>
I narrowed down the code to the only thing that gives me error, thanks in advance. It gets the Multipart file successfully but im not sure why it gives a null exception error
When I uploading files with my RestController in Spring Boot I used like below and everything is fine :
#PostMapping
public ResponseEntity<User> post(UserCreateRequest request, #RequestPart("file") MultipartFile file) throws IOException {
ftpService.uploadPhoto(file.getOriginalFilename(), file.getInputStream());
return ResponseEntity.ok(userService.create(request));
}
So may be you can try to change your code as below:
#RequestMapping(value = "/schedulebatch",method =
RequestMethod.POST,params="insertData")
public #ResponseBody String addBatch(#RequestPart("upfile") MultipartFile upfile) throws Exception {
if(!upfile.isEmpty()){
System.out.println("test1");
}
}
And your content-type should be multipart/form-data so I added an example html&ajax form request:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#btnSubmit').click( function(e) {
e.preventDefault();
var form = $('#my-form')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "http://localhost:8080/schedulebatch",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
alert("success")
},
error: function (e) {
alert("ERROR : ", e);
}
});
});
});
</script>
</head>
<body>
<form method="POST" enctype="multipart/form-data" id="my-form">
<input type="file" name="upfile"/><br/><br/>
<input type="submit" value="Submit" id="btnSubmit"/>
</form>
</body>
</html>
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.
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"));
What I'm trying to do
I'm building a small webapp with Netbeans, which can search for a ZIP-Code. The layout is made with bootstrap.css. Now I made following form in my (index.jsp):
<form id="form_submit_search"
class="navbar-form navbar-right"
role="form"
action="zipSearchHandler"
method="get">
<div class="form-group">
<input name="tv_zip"
type="text"
placeholder="ZIP Code..."
class="form-control">
</div>
<button id="submit_search"
type="submit"
class="btn btn-success">Search</button>
</form>
When the Button is klicked following method in the servlet is getting called:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String zipCode = request.getParameter("tv_zip");
System.out.println(zipCode + " habe den zip bekommen");
response.setContentType("text/html;charset=UTF-8");
List<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
list.add("item3");
list.add(zipCode);
String json = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
This give's me back a simple json-array, which is opened in a new site, but I'd like to show that response in some <div> in my index.jsp. How can I do that?
You could use something like this
$.ajax(
{
type: "POST",
url: "/TestServlet",
data: { tv_zip: '90210' }, // zipcode
dataType: "json",
success: function(response) {
// replace the contents of div with id=some_div with the response.
// You will want to format / tweak this.
$('#some_div').html(response);
},
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
}
);
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.