I am new with Spark Java. I have made a Library Management System with get and post methods written in Java. I have made an HTML form that takes information of user and creates users which gets stored in a ArrayList of objects in Java. When I call get method to return the list of user objects created via ajax, nothing gets returned. Success nor error gives any output.
But when I simply put the url : http://localhost:4567/users
I get the following output:
[{"id":1,"firstName":"Bhavya","lastName":"Chauhan","age":"22","gender":"F","phone":"1234567890"},
{"id":2,"firstName":"Rashi","lastName":"Chauhan","age":"20","gender":"F","phone":"1233455677"}]
I have attached my html and Spark java code. Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<title>Text Input Control</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<meta charset="utf-8"/>
</head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"></script>
<script>
$(function () {
$("#userGet").click(function(){
alert("Here");
$.ajax({
type: 'GET',
url: 'http://localhost:4567/users',
crossDomain: true,
data: '',
dataType: 'jsonp',
async:false,
success: function(responseData) {
//$("#divid").html(+responseData);
alert("hi");
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
});
</script>
<body>
<h2>Library Management System </h2>
<button>Get Stuff</button>
<form>
<h3>Manage Users </h3>
<input type=button onClick="location='CreateUser.html'" value='Create User'>
<br><br>
<input type=submit id="userGet" value='Get All Users'>
<br><br>
<input type=button onClick="location='UpdateUser.html'" value='Update User'>
<br><br>
</form>
<form action="http://localhost:4567/books" method="GET">
<h3>Manage Books </h3>
<input type=submit value='Get All Books'>
<br><br>
<input type=button onClick="location='FindBookByName.html'" value='Find Book By Name'>
<br><br>
<input type=button onClick="location='AddBook.html'" value='Add Book'>
<br><br>
<input type=button onClick="location='CheckOutBook.html'" value='Check Out Book'>
<br><br>
</form>
<div id="divid"></div>
</body>
</html>
Here is the Java:
import static spark.Spark.*;
public class UserController extends JsonUtil
{
public UserController(final UserService userService)
{
System.out.println("in user controller");
get("/users", (req, res) -> userService.getAllUsers(), json());
get("/books", (req, res) -> userService.getAllBooks(), json());
post("/users", (req, res) -> userService.createUser(req.body()), json());
post("/users/:id", (req, res) -> userService.updateUser(req.body()),json());
post("/books", (req, res) -> userService.addBook(req.body()), json());
post("/books/:name", (req, res) -> userService.findBookByName(req.body()),json());
post("/checkedOut", (req, res) -> userService.checkOutBook(req.body()), json());
}
}
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 am trying to create a comment section using jsp, servlet and ajax. The problem I am facing is that each comment replaces it's previous one instead of showing next to it.
Highly appreciate any kind of help.
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submitBtn').click(function() {
var cmt = $('#cmt').val();
$.ajax({
type : 'POST',
data : {
cmt : cmt,
action : 'EnterMsg'
},
url : 'SubmitComment',
success : function(result) {
$('#view2').text(result);
}
});
});
});
</script>
</head>
<body>
<fieldset>
<legend>Enter Message</legend>
<form>
Ques.<input type="text" id="cmt"> <input type="button"
value="Send" id="submitBtn"><br> <span id="post1"></span>
</form>
</fieldset>
<fieldset>
<legend>View Message</legend>
<form>
<div id='view2'></div>
<br>
</form>
</fieldset>
Try
var html='';
$.ajax({
dataType: "json",
url: "SubmitComment",
error: function () {
alert('error occured');
},
success: function (result) {
for(var key in result) {
var value = result[key];
html+='<div>'+key+':'+value+'</div>'
}
$("#view2").append(html);
}
});
Instead of
success : function(result) {
$('#view2').text(result);
}
Because of you get multiple comments from the ajax respose and you have to iterate each one of them and append to your div tag
I'm unable to perform "delete" from the HTML form. This is my HTML, what's incorrect here? , also included the RESTservice method that performs deletion. I see the POST is getting invoked after every button click. Any inputs or suggestions ?
create_todo.html
<!DOCTYPE html>
<html>
<head>
<title>Form to create a new resource</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script>
document.getElementById("delete").addEventListener("click", function () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8080/com.dcr.jersey.first/rest/todos", true);
xhr.setRequestHeader("Content-Type", "application/xml");
xhr.setRequestHeader("X-HTTP-Method-Override", "DELETE"); //X-HTTP-Method-Override
xhr.send();
},true);
</script>
</head>
<body>
<form id= "myForm" action="../com.dcr.jersey.first/rest/todos" method="post" >
<label for="id">ID</label>
<input name="id" />
<br/>
<label for="summary">Summary</label>
<input name="summary" />
<br/>
Description:
<TEXTAREA NAME="description" COLS=40 ROWS=6></TEXTAREA>
<br/>
<input type="submit" id="submit" value="Submit" /> <br/>
<button id="delete">Delete</button>
</form>
</body>
</html>
REST method for DELETE from form
#DELETE
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void delTodo(#FormParam("id") String id,
#Context HttpServletResponse servletResponse) throws IOException {
Todo c = TodoDao.instance.getModel().remove(id);
if(c==null)
throw new RuntimeException("Delete: Todo with " + id + " not found");
else servletResponse.sendRedirect("../create_todo.html");
}
RESTResourceClient to post and delete which works fine
Form form = new Form();
form.param("id","45");
form.param("summary","Summary for id 45");
response = target.path("rest").path("todos").request().post(Entity.form(form));
System.out.println("\nPost by FORM response code is "+ response.getStatus()+"\n");
response = target.path("rest").path("todos/45").request().delete();
//this is my jsp page, i need autocomplete for text box name=empid.
<div class="topcorner" align="right" >
<form action="search.htm" method="POST">
EmpId : <input type="text" name="empid" id="EmpId">
Start Date :<input type="text" name="stDate" />
End Date :<input type="text" name="enDate" />
<br>
<input type="submit" value="Search" name="submit" ><br>
</form>
//My controller method is below
#RequestMapping(value= "/getEmpid", method = RequestMethod.GET )
public #ResponseBody List<UserAttendance> autoComplete(#RequestParam("term") String empId,
#RequestParam("extra") String extra) {
List<UserAttendance> getEmp = adminService.autoComplete(empId);
return getEmp;
}
//service implementation method is
public List<UserAttendance> autoComplete(String empId) {
List<UserAttendance> getEmpid = adminDao.autoComplete(empId);
for(UserAttendance emp : getEmpid ) {
if(emp.getEmpId().contains(empId)){
getEmpid.add(emp);
}
}
return getEmpid;
}
//Dao implementation method is
#Override
public List<UserAttendance> autoComplete(String empId) {
// TODO Auto-generated method stub
String sql = "SELECT EMP_ID FROM attendance WHERE EMP_ID LIKE '%?%'";
List<UserAttendance> getEmp = getSimpleJdbcTemplate().query(sql,
ParameterizedBeanPropertyRowMapper.newInstance(UserAttendance.class), empId);
return getEmp;
}
i am fresher to java spring. I have searched lot of js but not get proper one.
Can any one help me a good jquery method pls.
This is the one that we use on our project, using ajax it´s pretty good
http://jqueryui.com/autocomplete/
some code example
initializeAutocompleteDepartment = function (componentId) {
$("#" + componentId + "SelectBox").autocomplete({
source: function (request, response) {
$.ajax({
url: 'foo/bla/' + request.term + '.do',
dataType: "json",
success: function (data) {
response(data);
}
});
},
messages: {
noResults: '',
results: function () {
}
},
minLength: 2,
select: function (event, ui) {
updateData(ui.item, componentId);
return false;
}
}).data("ui-autocomplete")._renderItem = function (ul, data) {
return $("<li>")
.append("<a>" + data.name + "</a>")
.appendTo(ul);
};
};
I hope below samples help you
<link rel="stylesheet" href="css/jquery-ui.css"></link>
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript" src="./js/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$("#projectname").autocomplete(
{
source : "BaselineNames?projectname="
+ $("#projectname").val(),
select : function(ui, item) {
$("#projectname").val(item);
}
});
});
</script>
<label for="projectname" class="col-sm-2 control-label">Project
Name</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="projectname"
name="name" placeholder="Project Name Eg : UIIC Android App">
</div>
i am trying to develop a username validation with jsp and ajax but an error apperar like this
POST ://localhost:8080/web_application/deneme.jsp
Show error : 405 (Method Not Allowed)
this is my jsp page what is wrong here
<html>
<body>
<form name="form" id="form">
<input type="text" name="username" id="username">
<br>
<input
type="submit" name="register" value="Sign up">
</form>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script
src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#form").validate({
rules : {
username : {
required:true,
remote : {
url : "deneme.jsp",
async : false,
type : "post",
data : {
username : function() {
return $("#username").val()
}
}
}
}
},
messages : {
username : {
required:"Require Field" ,remote:"already exist"
}
}
});
});
</script>
</body>
</html>
Instead of:
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
http is missing in your javascript file link location.
use the following:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>