I am trying to get data from back end server in angular. I have a java servlet which fetches data from database based on html input field and returns the response.
<!DOCTYPE html>
<html ng-app="myApp" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script>
"use strict";
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.cityArray = ["hyderabad", "secunderabad", "delhi", "mumbai"];
$scope.submit = function ($event) {
if ($scope.myForm.$invalid) {
// Or some other update
$scope.myForm.$submitted = true;
$event.preventDefault();
}
};
});
app.directive('uniqueUsername', function ($http) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
element.bind('blur', function (e) {
ngModel.$setValidity('unique', true);
$http.post('CheckUserName.do', element.val()).success(function (data) {
if (data) {
ngModel.$setValidity('unique', false);
}
});
});
}
};
});
</script>
</head>
<body ng-controller="MainCtrl">
<h2 class="text-muted">Registration form</h2>
<div>
<form name="myForm" action="RegistrationServlet.do" method="POST" novalidate>
First name:<input type="text" class="form-control input-sm" name="uname" ng-pattern="/^[a-zA-Z]{3,20}/" ng-model="uname" unique-username="" placeholder="First Name" required/>
<span style="color:red" ng-show="myForm.uname.$error.pattern">First name cannot be less than 3 letters with no digits</span>
<span style="color:red" class="error" ng-if="myForm.$submitted && myForm.uname.$error.required">Please fill field above<br></span><br/>
<span style="color:red" class="hide-while-in-focus" ng-show="myForm.uname.$error.unique">Username already exist<br/></span>
<button class="form-control btn btn-success" type="submit" ng-click="submit($event)">Submit</button>
</form>
</div>
</body>
</html>
The problem is request.getparameter("uname") is always returning null. Right now I can see in the chrome console that angularjs is able to communicate with the servlet but the response is null as username passed is being null.
Here's the java servlet code:
public class CheckUserName extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
String username = req.getParameter("uname");
System.out.println(username);
try {
Connection con = OracleDBConnection.getConnection();
String selectQuery = "select FIRSTNAME from registration";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(selectQuery);
while (rs.next()) {
String firstName = rs.getString("FIRSTNAME");
if (username.equalsIgnoreCase(firstName)) {
resp.getWriter().write("username already exist");
req.setAttribute("errMsg", "username already exist");
RequestDispatcher rd2 = req.getRequestDispatcher("/index4.jsp");
rd2.forward(req, resp);
} else {
resp.getWriter().write("username available");
// req.setAttribute("errMsg", "");
// resp.sendRedirect("EmailConfirmation.jsp");
}
}
} catch (Exception e) {
System.out.println("DB related Error");
e.printStackTrace();
}
}
}
$http.post() method expects an object and not string. Try changing your code to:
$http.post('CheckUserName.do', {
data: "uname=" + element.val()
}).success(function (data) {
if (data) {
ngModel.$setValidity('unique', false);
}
});
You haven't specify a request parameter name in post method call:
$http.post('CheckUserName.do', element.val()).success
You need to change above line to :
$http.post('CheckUserName.do',{uname:element.val()}).success
Try this,
$http.post(url, {
"uname": value
}).
success(function(data, status, headers, config) {
//success
}).
error(function(data, status, headers, config) {
//error
});
The input you are passing to the service should be like this.
Related
I have the following code which validates a Sign up form. I have two methods which validate if "Password" and "Confirm password" are the same and sends an error message if not and also checkEmail() which checks the DB if the email already exists. When I don't include the checkEmail() method the other one works fine (even the error message). But when I include the checkEmail() it gives an error message of NullPointerException. I believe it has to do with the incorporation of the checkEmail() method in my code but I am not sure where to put it. I would be grateful if anyone could help me.
//SERVLET doPost METHOD
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession s = request.getSession();
UserInfo ud = new UserInfo();
ud.createTable();
UserBean u = new UserBean();
ServletContext ctx = s.getServletContext();
u.setEmail(request.getParameter("email"));
u.setName(request.getParameter("name"));
u.setLname(request.getParameter("sname"));
u.setPassword(request.getParameter("password"));
s.setAttribute("User", u);
String e = u.getEmail();
String p1 = u.getPassword();
String p2 = request.getParameter("password2");
if(User.confirmPassword(p1, p2) && !User.checkEmail(e)) {
//Save data to DB
u = (User)s.getAttribute("User");
s.invalidate();
ud.insert(u);
forwardTo(ctx, request, response, "/Somepage.jsp");
} else {
if(User.checkEmail(e)) {
request.setAttribute("name",request.getParameter("name"));
request.setAttribute("sname",request.getParameter("sname"));
request.setAttribute("email",request.getParameter("email"));
request.setAttribute("pass", request.getParameter("password"));
request.setAttribute("pass2", request.getParameter("password2"));
request.setAttribute("errorMessage", "Email already exists!");
request.getRequestDispatcher("/SignUp.jsp").forward(request, response);
}
if(!User.confirmPassword(p1, p2)) {
request.setAttribute("name",request.getParameter("name"));
request.setAttribute("sname",request.getParameter("sname"));
request.setAttribute("email",request.getParameter("email"));
request.setAttribute("pass", request.getParameter("password"));
request.setAttribute("pass2", request.getParameter("password2"));
request.setAttribute("errorMessage", "Passwords do not match!");
request.getRequestDispatcher("/SignUp.jsp").forward(request, response);
}
}
}
//SIGN UP FORM
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User Registration</title>
</head>
<body>
<form action = "UserServ" method ="POST">
<h5 >Enter the details below to Sign Up</h5><br>
Name: <input type="text" name="name" required placeholder="Firstname" value="${name}"><br>
Surname: <input type="text" name="sname" required placeholder="Surname" value="${sname}"><br>
Email: <input type="text" value="${email}" name="email" placeholder="Email"><br>
Password:
<input type="password" value="${pass}" name="password" placeholder="Password" required><br>
Confirm password:
<input type="password" name="password2" value="${pass2}" placeholder="Confirm password" required><br>
<div style="color: #FF0000;">${errorMessage}</div><br>
<input type="submit" value="Sign Up">
</form>
</body>
</html>
</body>
</html>
//METHODS
public static boolean confirmPassword(String p1, String p2){
boolean status = false;
if(p1.equals(p2)) {
status =true;
}
return status;
}
public static boolean checkEmail(String email) {
boolean check = false;
PreparedStatement pst = null;
ResultSet rs = null;
try(Connection conn= ConnectionConfiguration.getConnection()){
pst = conn.prepareStatement("SELECT * FROM users WHERE email=?;");
pst.setString(1, email);
check = rs.next();
} catch (SQLException e) {
e.printStackTrace();
}
return check;
}
}
The ResultSet is never calculated as the prepared statement is never executed. This results in the NPE while executing rs.next().
Add sth like this after setting the email:
rs = preparedStatement.executeQuery();
This will execute the prepared statement with the given parameters and return the ResultSet you're looking for.
BTW:
Please consider using rs.isBeforeFirst() instead of rs.next() for checking if there is any result. In your case it will work, because you're not reading any row, but if, you'll need to reset the cursor as rs.next() moves the cursor to the next row if present.
I am writing for this problem several times as I am not finding a solution and I really need it today before 12 o'clock. I am want to display a table with data taken from database in AngularJS for front-end and jersey RESTful services for back-end. All i got when I run my project in browser is a blank table. I really really need anyone of you to help me with my code.
list_main.js
var myApp = angular.module('mainApp', []);
myApp.controller('BooksController', ['$scope', '$http', function($scope, $http) {
$scope.bookList = null;
$scope.resMsg = null;
$scope.showBookList = function() {
var urlGetUsers = 'http://localhost:8080/BookCommerce/webapi/list';
var responEC = $http.get(urlGetUsers, {cache: true, transformResponse: function(data, headersGetter) {
try {
var jsonObject = JSON.parse(data);
keepGoing = true;
return jsonObject;
}
catch (e) {
console.log(e);
$scope.resMsg = "Error. Cannot Retrieve Data";
}
return {};
}});//end ajax
responEC.success(function(bookList, status, headers, config) {
$scope.bookList = bookList;
if ($scope.bookList == null || $scope.bookList.length == 0) {
$scope.resMsg = "No Data";
}
});
};
$scope.showBookList();
}]);
index2.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List Of Books</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="js/list_main.js"></script>
</head>
<body>
<div class="row" data-ng-controller="BooksController" data-ng-app="myApp" data-ng-init="showBookList()" style="margin: 10px;">
<div class="col-md-7">
<div class="panel panel-primary">
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="exampleone">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="book in bookList">
<td>{{book.book_id}}</td>
<td>{{book.book_title}}</td>
<td>{{book.book_author}}</td>
<td>{{book.book_description}}</td>
<td>{{book.book_price}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
ListDAO.java
public class ListDAO {
public List<Book> findAll() {
List<Book> list = new ArrayList<Book>();
Connection c = null;
String sql = "SELECT * FROM book";
try {
c = ConnectionHelper.getConnection();
Statement s = c.createStatement();
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
list.add(processRow(rs));
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
ConnectionHelper.close(c);
}
return list;
}
protected Book processRow(ResultSet rs) throws SQLException {
Book book = new Book();
book.setBook_id(rs.getInt("book_id"));
book.setBook_title(rs.getString("book_title"));
book.setBook_author(rs.getString("book_author"));
book.setBook_description(rs.getString("book_description"));
book.setBook_price(rs.getInt("book_price"));
return book;
}
}
ListResource.java
#Path("/list")
public class ListResource {
ListDAO dao=new ListDAO();
#GET
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Book> findAll() {
System.out.println("findAll");
return dao.findAll();
}
}
Please HELP me! Thank you!
//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 have a simple index.html file:
<!DOCTYPE HTML><html lang="de-DE">
<head>
<title>DISPO Truck Star</title>
<meta http-equiv="CONTENT-TYPE" content="text/html" charset="UTF-8">
<link rel="stylesheet" href="jquery.mobile-1.3.2.css"/>
<meta name="viewport" content="width=device-width, initial-scale=1 user-scalable=no"/>
<script src="jquery-1.9.1.min.js"></script>
<script src="jquery.mobile-1.3.2.js"></script>
<!-- weitere Scripts -->
<script src="js/main.js"></script>
<!-- Einstellungen zur Definition als WebApp -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
</head>
<body>
<div data-role="page" id="anmeldeBildschirm">
<div data-role="header" data-position="fixed">DISPO</div>
<div data-role="content" id="anmeldeBildschrimInhalt">
<div data-role="fieldcontain">
<label for="FahrerAuswahl" class="select">Fahrer:</label>
<select name="FahrerAuswahl" id="FahrerAuswahl"></select> <!-- Die Auswahl wird hier mit JavaScript dynamisch hinzugefügt -->
</div>
<div data-role="fieldcontain" id="PINLabel">
<label for="password">PIN:</label>
<input type="password" name="password" id="password" value="" data-clear-btn="true" />
</div>
<div data-role="fieldcontain">
<label for="AufliegerAuswahl" class="select">Auflieger:</label>
<select name="AufliegerAuswahl" id="AufliegerAuswahl"></select> <!-- Die Auswahl wird hier mit JavaScript dynamisch hinzugefügt -->
</div>
<div data-role="footer" id="anmeldeBildschirmFooter" data-position="fixed" data-tap-toggle="false">
<div data-role="navbar">
<ul>
<li>Zum Start</li>
<li>PIN ändern</li>
<li><a data-role="button" id="zuDenTourenButton" onclick="vergleicheFahrer()" data-icon="arrow-r">Touren</a></li>
</ul>
</div>
</div>
</div>
</div>
In the textfield "password" I type the password, which should be compared with the one stored in the database after a click on the button "Touren". The button click fires an event, after that the following function is called:
function vergleicheFahrer(){
var pinCode = $('#password').val();
$.ajax({
type: 'GET',
url: rootURL + '/' + pinCode, // var rootURL = "http://localhost:8080/DISPOTruckStar-Backend/rest/api";
dataType: "json",
success: function(data){
alert("Very wonderful! You received following data:" + data);
retrieveTourContent();
},
error: function(){
alert("Fehler in der Methode vergleicheFahrer()");
}
});}
The request goes through and a success function is called, but the Eclipse console says that com.microsoft.sqlserver.jdbc.SQLServerDriver was not found. Here the code for handling the "GET" request:
#Path("/api")
public class RestResource {
FahrerTruckModellDAO fahrerTruckModellDAO = new FahrerTruckModellDAO();
#GET #Path("{PinCode}")
#Produces({MediaType.APPLICATION_JSON})
public String getFahrerByPinCode(#PathParam("PinCode") String pinCode)
{
return FahrerTruckModellDAO.getFahrerByPinCode(pinCode);
}
}
The DAO Object code:
public class FahrerTruckModellDAO {
/*public static void main(String[] args) {
getFahrerByPinCode("1402");
}*/
public static String getFahrerByPinCode(String pinCode)
{
String query = "SELECT * from dbo.tDriver WHERE PinCode = ?";
Connection connection = null;
try
{
connection = Database.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, pinCode);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next())
{
String resultvalue = resultSet.getString(2);
return resultvalue;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
and finally the code of the "getConnection()" method:
public static Connection getConnection() throws Exception{
try
{
String url = "jdbc:sqlserver://MINPKRT_270913\\SQLEXPRESS;databaseName=TRUCK_DB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection(url);
return connection;
}
catch(Exception ex)
{
ex.printStackTrace();
return null;
}
}
After ajax request I get the exception I mentioned above, BUT after launching the commented code of the main method in the DAO class I get the desired connection and the driver is found. I also added the path to the .jar file of the jdbc driver for the MS SQL Server 2008 in both the classpath and path variables. I suppose it is either the wrong URL I specify ("localhost/...") or the function within the ajax call needs more time to establish the needed connection.
I want to read in a textbox a name and I want to pass-it to the next form, and it would be a problem that the form doesn't reset to show only the second form, "basic.jsp". Is there any command to reset the form? Now it shows me the content of basic.jsp mixed up with the index.jsp (request of the name)...
-HelloWorld.java:
package javapapers.sample.ajax;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorld extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws java.io.IOException, ServletException {
res.setContentType("text/html");
res.getWriter().write("Hey!");
String textNume = req.getParameter("userInput");
req.setAttribute("nume",textNume);
RequestDispatcher requestDispatcher = req.getRequestDispatcher("basic.jsp");
requestDispatcher.forward(req,res);
}
}
- index.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" language="javascript" src="ajax.js"></script>
</head>
<body>
<BR>Please enter your name:<input type='text' id='userInput'/>
<div id="hello"><button type="button" onclick="makeRequest()">Adauga</button></div>
<div id="ttt"><input type="text"></input></div>
<p>Welcome to the site <b id='boldStuff'>dude</b> </p>
</script>
</body>
</html>
- ajax.js:
function getXMLHttpRequest() {
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
//AJAX call starts with this function
function makeRequest() {
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("POST", "helloWorld.do", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var userInputValue = document.getElementById('userInput').value;
xmlHttpRequest.send("userInput=" + userInputValue);
}
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
var userInput = document.getElementById("userInput").value;
document.getElementById("hello").innerHTML = xmlHttpRequest.responseText; //"hey" def.in java!
document.getElementById("ttt").innerHTML = userInput;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
- basic.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<HTML>
<HEAD>
<TITLE>Elemente de identificare</TITLE>
</HEAD>
<BODY>
<H1>Elemente de identificare</H1>
Domnule <%= request.getAttribute("nume") %> alegeti elementele de identificare:<br>
Felul notificarii<br>
<select name="fel_notif">
<option value="Prima notificare">Prima notificare</option>
<%--<option value="Monday" selected>Monday</option>--%>
</select><br>
Mailul dvs <br><textarea rows="1" cols="30" name="mail"></textarea><br>
Caracterizare <br><textarea rows="3" cols="30" name="caract"></textarea><br>
Circumstante <br><textarea rows="3" cols="30" name="circ"></textarea><br>
Masuri de atenuare <br><textarea rows="3" cols="30" name="masuri"></textarea><br>
Cod notificare: <input type="text" name="cod" value="scot din BD" readonly><br>
<INPUT TYPE="SUBMIT" value="Trimite">
<%--<script type="text/javascript" language="javascript" src="ajax.js"></script>
<div id="pdf"><button type="button" onclick="makeRequest()">Creaza PDF</button></div>--%>
</BODY>
</HTML>
Your not sending userInput to the server. You have to add it to the request to be able to receive it in the servlet. Now you're just doing xmlHttpRequest.send(null). Instead, send the parameter string representing the data from your input. Something like:
xmlHttpRequest.send("userInput=" + userInputValue);