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); }
}
);
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>
I have written a jsp file and servlet .In jsp I have used data list inside a form .And I want to pass that user input to the servlet.I have posted the code below.
jsp code
<form action="NewServlet1" method="Post" >
<center>
<input type="text" name="website" list="website" placeholder="Enter your website">
<datalist id="website">
<option value="https://www.google.lk/">GOOGLE</option>
<option value="https://www.yahoo.com/">YAHOO</option>
<option value="https://www.hackerrank.com/">HACKER RANK</option>
</datalist><br><br><br>
</center></form>
<div style="width: 400px; height: 400px">
<canvas id="myChart" width="1000" height="1000" ></canvas>
</div>
<center> <div>
<button id="button1" name="button1" onclick="submit()" class="btn btn-primary">submit</button>
</div></center>
<script>
function Test(today, time) {
var ctx = new Chart(document.getElementById("myChart")
, {
type: 'line',
data: {
labels: today,
datasets: [{
data: time,
label: "Web Service 1",
borderColor: "red",
fill: false
}
]
},
options:
{
scales: {xAxes: [{display: true, scaleLabel: {display: true, labelString: 'date and time'}}], yAxes: [{display: true, ticks: {beginAtZero: true, steps: 100, stepValue: 50, max: 6000}}]},
hover: {intersect: false },
title: {display: true, text: 'response time of selected website'},
tooltips: { mode: 'nearest'}
}
});
}
function submit()
{
$.post("NewServlet1",
{
},
function (data)
{
Test(data.today, data.time);
});
}
servlet code
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String website = (String)request.getParameter("website");
But this is not working.Can someone help me to solve this?
First of all you need to submit the form to the servlet which path is mapped to NewServlet1
<form action="NewServlet1" method="Get" >
<center>
<input type="text" name="website" placeholder="Enter your website">
<datalist id="website">
<option value="https://www.google.lk/">GOOGLE</option>
<option value="https://www.yahoo.com/">YAHOO</option>
<option value="https://www.hackerrank.com/">HACKER RANK</option>
</datalist>
</center>
<%
String website= request.getParameter("website"); // it is not needed
request.setAttribute("website",website); // it is not needed
%>
<input type="submit"/> <!--need to add submit button to submit it to the servlet-->
</form>
Now your servlet code is fine which is:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String website = (String)request.getParameter("website");
}
Note : Need to write some value in website text box
Or if you want to get attribute which previously stored in request object then use RequestDispatcher.
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
});
I have a stupid proplem for send the input from a html page to a servlet using ajax.
Practically I create the message java how I learned, but the servlet doesn't read the input value. I insert my code
<div class="col_9">
<h1>Ricerca Dataset</h1>
<div class="form">
<div class="col_9">
<div class="col_12">
<div class="col_5">Cerca:</div>
<div class="col_6">
<input id=query type="text" name="name" />
</div>
</div>
</div>
<div class="col_3">
<button id="cerca" class="large">Cerca</button>
</div>
</div>
</div>
function cercaNormaleFn() {
$("#cerca").click(function(e) {
$("#center").load("ShowResult.jsp", function() {
var oTable = $('#example').dataTable({
"processing" : true,
"ajax" : {
url : context + "/CercaServlet",
dataSrc : "demo",
type : "Post",
data : "query=" + $("#query").val(),
}
});
alert(query)
});
});
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
System.out.println(request.getAttribute("data"));
}
You may need to add the attribute to your dataTable function:
"serverSide": true
as dataTables.net Server-side processing explains:
With server-side processing enabled, all paging, searching, ordering etc actions that DataTables performs are handed off to a server
A demo from dataTables.net post demo
Can anybody tell me how to save data by kendo ui and java servlet. That means i have design html fields like Student ID, Student name and want to save it using kendo ui framework and java servlet and return json formatted data after execute my insert query from java servlet.Please consider i am very new to java.
Here is my html
<div id="PaymentMasterDetailsDiv" >
<ul>
<li>
<label for="User" class="required lbl widthSize15_per">User:</label>
<input type="text" id="txtUser" name="User" class="" maxlength="50" value="123" placeholder="Pleaes Select Payment Id" required validationmessage="Please enter Payment Id" />
</li>
<li>
<label for="Password" class="required lbl widthSize15_per">Password:</label>
<input type="text" id="txtPassword" name="Password" class="" maxlength="50" value="123" placeholder="Pleaes Select Payment Id" required validationmessage="Please enter Payment Id" />
</li>
</ul>
<button id="btnSave" class="k-button" type="button" >Save</button>
</div>
And here is my .js to call my .java
SaveCommonInformation: function () {
var objBranchInfo = 0;
var serviceUrl = "/api/LoginController";
jQuery.ajax({
url: serviceUrl,
// data: jsonParam,
type: "POST",
processData: true,
contentType: "application/json",
dataType: "json",
success: onSuccess,
error: onFailed
});
function onSuccess(jsonData) {
if (jsonData == "Success") {
alert("Success");
}
else if (jsonData == "Common Already Exist") {
alert();
}
else {
alert("Exist");
}
}
function onFailed(error) {
alert("Error");
}
}
and this is my .java
#WebServlet("/LoginController")
public class LoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginController() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
but i can't understand how actually connect to database and insert to database something and also return "Success" or "Common Already Exist" in json formate