I found a piece of code to use AngularJS with Java Servlet.
The problem is that when I run the application it tell me that the 'AtpPlayers' page it does not exists and, of course, it does not fill my table.
I was trying in JBOSS server and json-simple-1.1.1.jar library.
What is doing wrong?
The servlet is here:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/AtpPlayers")
public class AtpPlayers extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json;charset=UTF-8");
try {
PrintWriter out = response.getWriter();
out.println("[{\"name\": \"Nadal, Rafael (ESP)\", \"email\": \"nadalrafael#gmail.com\", \"rank\": \"1\"},"
+ "{\"name\": \"Djokovic, Novak (SRB)\", \"email\": \"djokovicnovak#gmail.com\", \"rank\": \"2\"},"
+ "{\"name\": \"Federer, Roger (SUI)\", \"email\": \"federerroger#gmail.com\", \"rank\": \"3\"},"
+ "{\"name\": \"Wawrinka, Stan (SUI)\", \"email\": \"wawrinkastan#gmail.com\", \"rank\": \"4\"},"
+ "{\"name\": \"Ferrer, David (ESP)\", \"email\": \"ferrerdavid#gmail.com\", \"rank\": \"5\"}]");
} catch (Exception e) {
System.out.println(e);
}
}
}
The HTML & JS code is that:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
</head>
<body ng-app="ATP_PLAYERS">
<div ng-controller="atpController">
<h5>Loading ATP players from a Servlet</h5>
<table>
<thead>
<tr>
<th>Rank</th>
<th>Name</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in atp">
<td>{{item.rank}}</td>
<td>{{item.name}}</td>
<td>{{item.email}}</td>
</tr>
</tbody>
</table>
</div>
<script language="javascript" type="text/javascript">
angular.module('ATP_PLAYERS', [])
.controller('atpController', function ($scope, $http) {
$http.get('http://localhost:8080/AngularGET/AtpPlayers').then(function (data, status, headers, config) {
$scope.atp = data;
alert('OK');
}, function (data, status, headers, config) {
alert('NU');
});
});
</script>
</body>
</html>
I found the problem:
$http.get('http://localhost:8080/AngularGET/AtpPlayers').then(function (data, status, headers, config) {
$scope.atp = data;
alert('OK');
}, function (data, status, headers, config) {
alert('NU');
});
replaced with:
$http.get('http://localhost:8080/AngularGET/AtpPlayers').then(function (response) {
$scope.atp = response.data;
alert('OK');
}, function (response) {
alert('NU');
});
I don't knows why the guy which write the original code was typed "function (data, status, headers, config)"...
Related
I am sending form data using Jsp through AJAX on Servlet.
reg.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form>
Enter name:<input type="text" id="name" /> <br />
<button onclick="callJqueryAjax()">Save</button>
</form>
<span id="result"></span>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function callJqueryAjax() {
location.reload(false);
var name = $('#name').val();
console.log(name);
$.ajax({
url : 'Save',
method : 'POST',
data : {
name : name,
},
success : function(resultText) {
$("#result").html(resultText);
}
});
}
</script>
</body>
</html>
SaveMe.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Save")
public class SaveMe extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection makeCon;
private Statement stmt;
public void init(ServletConfig config) throws ServletException {
JdbcCon jdbcCon = new JdbcCon();
makeCon = jdbcCon.makeCon();
try {
stmt = makeCon.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
String name = request.getParameter("name");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String sql = "insert into users (name) Values('" + name + "')";
System.out.println(sql);
try {
int result = stmt.executeUpdate(sql);
if (result > 0) {
out.print("Inserted");
} else
out.print("Not Inserted");
} catch (SQLException e) {
}
}
}
I receive the output in ajax but the thing is JSP gets reload by itself and removes the response as well as removes the data from Textbox from which my response gets disappear by itself.
Please provide me the solution and also a better way for writing an ajax call
First of all I didn't understand why you are using "location.reload(false);" in your JSP page before submitting the ajax request.
You could remove it.
In addition a good practice when using ajax request is to specify the "dataType", in your case "html".
Here is an example:
$.ajax( {
type : 'POST',
url : 'SaveMe',
success : function(result) {
$("#result").html(result);
},
dataType : "html"
});
I can not send a simple request to the servlet to jQuery tools. But at the same time if I go through the form, then everything works on hurray. Here is the index.html from which I want to send the user's login. Login.js, in which I form the request itself, SerletStore.java itself servlet. And the structure of the whole project.
login.js
$(document).ready( function(){
$("#login-submit").click(function(){
var data = {
username: $("#user").prop("value")
}
$.ajax({
method: "POST",
url: "http://localhost:8080/ChallengeClient/store",
data: {
username: $("#user").prop("value")
},
success: function(data) {
alert('Success');
},
error: function(xhr, str){
alert('Возникла ошибка: ' + xhr.responseCode);
}
}).done(function() {
alert('Success');
});
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Form</title>
<link rel="stylesheet" href="css/login.css">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400,700">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/login.js"></script>
</head>
<body>
<div id="login">
<form name="form-login">
<span class="fontawesome-user"></span>
<input type="text" id="user" name="username" placeholder="Имя пользователя">
<span class="fontawesome-lock"></span>
<input type="password" id="pass" placeholder="Пароль">
<input type="submit" id="login-submit" value="Вход">
</form>
</div>
</body>
</html>
ServletStore.java
package servlet;
import server.service.HelloWebService;
import server.service.HelloWebServiceImplService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
#WebServlet(name="store", urlPatterns = "/store")
public class ServletStore extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// подключаемся к тегу service в wsdl описании
HelloWebServiceImplService helloService = new HelloWebServiceImplService();
// получив информацию из тега service подключаемся к самому веб-сервису
HelloWebService hello = helloService.getHelloWebServiceImplPort();
// обращаемся к веб-сервису и выводим результат в консоль
/*String error = hello.getHelloString("!! Challenge !!");*/
String error = "";
String username = (String) req.getParameter("username");
if (username.equals("")) {
error = "Не было введено имя пользователя";
}
req.setAttribute("error", "Не было введено имя пользователя");
req.getRequestDispatcher("jsp/loginError.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
I am trying make hello world using ajax and spring, but it not workit, I dont know why.
My servlet is:
import javax.servlet.http.HttpServlet;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class SomeController {
#RequestMapping(value = "/profile", method = RequestMethod.GET)
public #ResponseBody
String processAJAXRequest(
#RequestParam("firstname") String firstname,
#RequestParam("lastname") String lastname) {
String response = "HELLO: " + firstname + " " + lastname;
return response;
}
}
And my page with ajax is:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="windows-1250">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<form id="sampleForm" method="post" action="/profile">
<div>
<input type="text" name="firstname" id="firstname">
</div>
<div>
<input type="text" name="lastname" id="lastname">
</div>
<div>
<button type="submit" name="submit">Submit</button>
</div>
</form>
<script>
$(document).ready(function () {
$('#sampleForm').submit(
function (event) {
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var data = 'firstname='
+ encodeURIComponent(firstname)
+ '&lastname='
+ encodeURIComponent(lastname);
$.ajax({
url: $("#sampleForm").attr("action"),
data: data,
type: "GET",
success: function (response) {
alert(response);
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
});
});
</script>
</body>
</html>
When I try to send form, I am getting error 404. Can you help me? Where is a problem?
Normal servlet extends from HttpServlet working fine.
I'm Trying to Save small record using JSP ajax in technology. The project working procedure is like this.
01. index.jsp : Send data to SaveStudent servlet
02. SaveStudent : Get request form jsp and send it to validation java class
03. Validation : Validate data and Send to DaoImpl java class
04. DaoImpl : Override the method in StudentDAO, Do the save SQL query.
05. StudentDAO : A interface has all the database related methods.
Here is the image of the project.
Given below is index.jsp files source code.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<form action="SaveStudent" method="post">
<label>Enter Name:</label>
<input type="text" name="name" id="txtName"/>
<br/>
<label>Enter City:</label>
<input type="text" name="city" id="txtCity"/>
<br/>
<input type="submit" value="Send" id="btnSave"/>
<div id="response"></div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
var $name = $("#txtName").val();
var $city = $("#txtCity").val();
$.post('SaveStudent', {
name: $name,
city: $city
}, function(responseText) {
if (responseText !== null) {
$('#response').text(responseText);
} else {
alert("Invalid Name");
}
});
});
});
</script>
</body>
Here is SaveStudent java class's source code.
package Control;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Model.Validation;
public class SaveStudent extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String record = "";
try {
Validation val = new Validation();
record = val.validateSave(request, response);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
if (record != null) {
out.write(record);
} else {
out.print("Error Occured..!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
}
Save record is working fine. Database is also updating. But the problem is The "Save Successful" message is appears in servlet page. Not under the jsp page.
Please help me on this. Thank you.
I figure out a way. I put replace "submit" type to "button". Now working perfectly. Thank you for your Time.
*
neglect it
*
I am lerner in JSP and java field. I am stuck in a problem. I hv mentioned my code below.
My JSP code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org /TR/html4/loose.dtd">
<html>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$("#save").click( function ()
{
var arrayxx= new Array(5);
arrayxx[0]=0;
arrayxx[1]=3;
arrayxx[2]=4;
arrayxx[3]=9;
$.get('Save1',{arrayX:arrayxx},function(responseJson)
{
} );
});
});
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<input type="button" id="save" value="save" ></input>
</body>
</html>
My servlet:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Save1 extends HttpServlet {
private static final long serialVersionUID = 1L;
public Save1() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("INSIDE SERVLET");
String [] yourList = request.getParameterValues("arrayX");
System.out.println(request.toString());
System.out.println(yourList[0]);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
I cant able to pass the array from JSP to servlrt.
Please help me with this. When i receive the array, i found that array does not contain any element.
Thanks in advance
As per your requirement I would suggest you to go for ajax like this way
$.ajax(
{
type: "POST",
url: "servlet", //Your full URL goes here
data: { parametername: parametervalue},
success: function(data, textStatus, jqXHR){
//alert(data);
}