Is there something like sessions in dart? - session

This may seem like a silly question but I am just starting out with dart and will need to verify user sesions similar to what you might do with PHP with the $_SESSION array...
So I am writing a basic server backend and a frontend and need to authenticate some requests that come in via XMLHttpRequest. The backend sends back JSON based on whether the given frontend is authenticated or not. In some cases, the frontend can update the DOM but only for the user who authenticated.
Not sure if I am explaining this well...
Any advice would be appreciated!!
Thanks!

A session is a high-level functionality that shouldn't be part of any language. You can include session functionality yourself by impelementing something like.
Map<String, int> sessions = {'abcdef12345' : 42}; // exists in e.g. datastore and is managed by an authentication routine
String authenticationToken = 'abcdef12345'; // comes from the request
if(sessions.containsKey(authenticationToken)) {
print('User ${sessions[authenticationToken]} is at least authenticated but might not have the appropriate rights to perform this operation.');
} else {
print('Not authenticated.');
}

Nothing like sessions is built in, but you can check out the recent Google API library for Dart to use oAuth:
Google API Dart Client

The package shelf_auth provides a nice full-automatic solution for session handing with its JwtSessionHandler implementation for shelf
var authMiddleware = authenticate([new RandomAuthenticator()],
new JwtSessionHandler('super app', 'shhh secret', testLookup));

Small example of using session with shelf package.
import 'dart:io' show Cookie;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf_session/cookies_middleware.dart';
import 'package:shelf_session/session_middleware.dart';
import 'package:shelf_static/shelf_static.dart';
void main(List<String> args) async {
final router = Router();
router.get('/', _handleHome);
router.get('/login', _handleLogin);
router.get('/login/', _handleLogin);
router.post('/login', _handleLogin);
router.post('/login/', _handleLogin);
router.get('/logout', _handleLogout);
router.get('/logout/', _handleLogout);
final staticHandler =
createStaticHandler('web', defaultDocument: 'index.html');
final handler = Cascade().add(staticHandler).add(router).handler;
final pipeline = const Pipeline()
.addMiddleware(logRequests())
.addMiddleware(cookiesMiddleware())
.addMiddleware(sessionMiddleware())
.addHandler(handler);
const address = 'localhost';
const port = 8080;
final server = await io.serve(pipeline, address, port);
print('Serving at http://${server.address.host}:${server.port}');
}
const _menu = '''
Home<br />
Log in<br />
Log out<br />''';
Future<Response> _handleHome(Request request) async {
final userManager = UserManager();
final user = userManager.getUser(request);
var body = '$_menu{{message}}<br />{{cookies}}';
if (user == null) {
body = body.replaceAll('{{message}}', 'You are not logged in');
} else {
body = body.replaceAll('{{message}}', 'You are logged in as ${user.name}');
}
final cookies = request.getCookies();
body = body.replaceAll('{{cookies}}',
cookies.entries.map((e) => '${e.key}: ${e.value}').join('<br />'));
request.addCookie(Cookie('foo', 'Foo'));
if (!cookies.containsKey('baz')) {
request.addCookie(Cookie('baz', 'Baz'));
} else {
request.removeCookie(Cookie('baz', ''));
}
return _render(body);
}
Future<Response> _handleLogin(Request request) async {
const html = '''
<form action="" method="post">
<label>Login</label><br />
<input name="login" type="text" /><br />
<label>Password</label><br />
<input name="password" type="password" /><br /><br />
<button>Log in</button>
</form>
''';
if (request.method == 'GET') {
return _render(_menu + html);
}
final body = await request.readAsString();
final queryParameters = Uri(query: body).queryParameters;
final login = queryParameters['login'] ?? ''
..trim();
final password = queryParameters['password'] ?? ''
..trim();
if (login.isEmpty || password.isEmpty) {
return _render(_menu + html);
}
final user = User(login);
final userManager = UserManager();
userManager.setUser(request, user);
return Response.found('/');
}
Future<Response> _handleLogout(Request request) async {
Session.deleteSession(request);
return Response.found('/');
}
Response _render(String body) {
return Response.ok(body, headers: {
'Content-type': 'text/html; charset=UTF-8',
});
}
class User {
final String name;
User(this.name);
}
class UserManager {
User? getUser(Request request) {
final session = Session.getSession(request);
if (session == null) {
return null;
}
final user = session.data['user'];
if (user is User) {
return user;
}
return null;
}
User setUser(Request request, User user) {
var session = Session.getSession(request);
session ??= Session.createSession(request);
session.data['user'] = user;
return user;
}
}

Related

How to do sign out from MSAL authentication.?

I am working on xamarin forms where I am using MSAL for authentication to authenticate. Now I want to sign out the user once he clicks on the sign-out. For sign out, I wrote Below code
foreach (var user in await App.PCA.GetAccountsAsync())
{
await App.PCA.RemoveAsync(user);
}
The above code is executing without any problem but when I again try to log in it is not asking for the password. I am clearing the cookies from the app using dependency service like
created one interface in xamarin forms project
public interface IAuthentication
{
void ClearAllCookies();
}
And in the android project providing the implementation for the interface
public void ClearAllCookies()
{
CookieManager.Instance.RemoveSessionCookie();
CookieManager.Instance.RemoveAllCookie();
}
I am doing Authentication like below
In App.xamal.cs file
public static IPublicClientApplication PCA = null;
public static string ClientID = "xxxxxxxxxxxxxxxxxxxx";
public static string[] Scopes = { "User.Read" };
public App()
{
PCA = PublicClientApplicationBuilder.Create(ClientID)
.WithRedirectUri($"msal{ClientID}://auth")
.Build();
InitializeComponent();
}
//On login button click
AuthenticationResult authResult = null;
IEnumerable<IAccount> accounts = await App.PCA.GetAccountsAsync();
try
{
IAccount firstAccount = accounts.FirstOrDefault();
authResult = await App.PCA.AcquireTokenSilent(App.Scopes, firstAccount)
.ExecuteAsync();
}
catch (MsalUiRequiredException)
{
try
{
authResult = await App.PCA.AcquireTokenInteractive(App.Scopes)
.WithLoginHint(EmailId) //Here I am passing Email Id
.WithParentActivityOrWindow(App.ParentWindow)
.ExecuteAsync();
}
catch (Exception ex2)
{
await DisplayAlert("Acquire token interactive failed. See exception message for details: ", ex2.Message, "Dismiss");
}
}
if (authResult != null)
{
var content = await GetHttpContentWithTokenAsync(authResult.AccessToken);
await Navigation.PushModalAsync(new Dashboard.PartnerDashboard(content));
}
}
After clearing again it is not asking for the password. If I uninstall and reinstall the app also it is not asking for the password. How to resolve this?
Can you try with the below code for clearing accounts in MSAL.
public void ClearAllCookies(string authority)
{
var authContext = new AuthenticationContext(authority);
authContext.TokenCache.Clear();
CookieManager.Instance.RemoveSessionCookie();
CookieManager.Instance.RemoveAllCookie();
}
where authority = "https://login.windows.net/common";
Try below code before authenticate code running, for removing old accounts.
var authContext = new AuthenticationContext(authority);
if(authContext.TokenCache.ReadItems().Any())
{
authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority,false, null);
}

Trapping errors in Aurelias HTTP client

Hi All (Especially the Aurelia core team hanging about round here)
I have an aurelia app using the "aurelia-http-client" to make requests to my back end API.
My back end API is a C# based service running on Nancy.
In my front end Iv'e abstracted the http client out to my own network lib as follows:
import { inject } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { HttpClient } from 'aurelia-http-client';
import environment from './environment';
#inject(HttpClient, Router)
export default class httpservice {
private http: HttpClient = null;
private router: Router = null;
private authService: any = null;
private authToken: string = "";
constructor(HttpClient, Router) {
this.http = HttpClient;
this.router = Router;
HttpClient.configure(http => {
http.withBaseUrl(environment.servicebase);
});
}
public setAuthService(authService: any) {
this.authService = authService;
}
public get(url: string, authObject?: any): any {
let myAuth = this.authService ? this.authService : authObject;
let myToken = "";
if (myAuth) {
myToken = myAuth.getAuthToken();
}
let self = this;
let client = this.http
.createRequest(url)
.asGet()
.withHeader("AuthenticationToken", myToken)
.withInterceptor({
responseError(responseError) {
console.log(responseError);
if (responseError.statusCode === 401) {
if (myAuth) {
myAuth.destroySession();
}
}
if (responseError.statusCode === 404) {
self.router.navigateToRoute("missing");
}
return responseError;
}
});
return client;
}
public post(url: string, postData: any, authObject?: any): any {
let myAuth = this.authService ? this.authService : authObject;
let myToken = "";
if (myAuth) {
myToken = myAuth.getAuthToken();
}
let self = this;
let client = this.http
.createRequest(url)
.asPost().withContent(postData)
.withHeader("AuthenticationToken", myToken)
.withInterceptor({
responseError(responseError) {
console.log(responseError);
if (responseError.statusCode === 401) {
if (myAuth) {
myAuth.destroySession();
}
}
if (responseError.statusCode === 404) {
self.router.navigateToRoute("missing");
}
return responseError;
}
});
return client;
}
}
and I then use this in my other modules/classes as follows:
import { Aurelia, inject } from 'aurelia-framework';
import HttpService from './httpservice';
import environment from './environment';
import { EventAggregator } from 'aurelia-event-aggregator';
#inject(EventAggregator, Aurelia, HttpService)
export default class Authservice {
public http: HttpService = null;
public app: Aurelia = null;
public ea: EventAggregator = null;
public authToken: any = null;
private loginUrl: string = "";
private logoutUrl: string = "";
private checkUrl: string = "";
constructor(eventAggregator, aurelia, httpService) {
this.http = httpService;
this.app = aurelia;
this.ea = eventAggregator;
this.loginUrl = "/login";
}
public getAuthToken() {
if (!sessionStorage[environment.tokenname] ||
(sessionStorage[environment.tokenname] == null)) {
return null;
}
return sessionStorage[environment.tokenname];
}
public login(loginName, password) {
let postData = {
loginName: loginName,
password: password
};
let client = this.http.post(this.loginUrl, postData);
client.send()
.then((response) => response.content)
.then((data) => {
if (data.error) {
this.ea.publish("loginMessage", { message: data.errorMessage });
return;
}
if (data.authenticationFailed) {
this.ea.publish("loginMessage", { message: "Invalid user name and/or password supplied." });
return;
}
if (data.accountSuspended) {
this.ea.publish("loginMessage", { message: "Your account has been suspended, please contact support." });
return;
}
sessionStorage[environment.tokenname] = data.token;
sessionStorage["displayedLoginName"] = data.displayName;
location.assign('#/');
this.app.setRoot('app');
})
.catch(() =>
{
debugger;
alert("Something bad happened trying to connect to server.");
});
}
public isAuthenticated() {
// TODO: hook this up to check auth token validity via rest call???
let token = this.getAuthToken();
return token !== null;
}
}
enum LoginStates {
LoginValid = 0,
BadUserNameOrPassword,
AccountSuspended
}
Please note I've stripped some of the code out of the auth library to reduce confusion
In general ALL of this works well. The interceptors get triggered when 401s and 404s occur, and if I add a 500 that get's handled too, so where all good there.
The problem I have is handling communication failures.
As you can see in the login routine, I have a catch following the then.
I expected that if the server couldn't be reached or some other base communications failure occurred, that this catch would trigger rather than the "then" and thus allow me to handle the error, but instead it does not.
What I get instead is this in the console:
Worse still, my login routine doesn't abort, it actually succeeds and allows the logged in page to be shown.
It seems that while the library is making the OPTIONS call (Which is when this error occurs) none of my user code is taken into account.
The OPTIONS call is required for successful pre-flight/ajax requests, so stopping this happening is not an option, and I feel that if the OPTIONS call did not abort, but made it to the POST call,t hat my error handling would then be taken into consideration.
It seems silly to be not able to trap errors like this, especially in today's mobile world where a device may be out of coverage or temporarily offline.
If anyone has any thoughts on how this can be solved, I'd love to hear them.
Update 1
My problem seems to be related to this one:
aurelia-fetch-client - a promise was rejected with a non-error: [object Response]
However, I'm not using "useStandardConfiguration()" which is apparently the cause for that case. I'm also not using the fetch client, however I do note that the API in both clients is practically the same, so I wonder if the underlying code is also similar.
Ok.... so, after a long hard afternoon of head scratching and hair pulling, it turns out, the whole thing is actually linked to a reported issue with the "BlueBird promises library" which is what aurelia uses to manage it's promises.
The link to the issue with BlueBird can be found here:
https://github.com/petkaantonov/bluebird/issues/990
It's not specifically an issue according to the BB dev's but to many folks encountering it, it sure looks like one.
The bottom line is that the library is not designed to throw the errors generated directly by it (As the example on the issue page shows)
The correct way according to the BB team, is to either throw a new error completely, or derive a new instance from the one passed to the promise, and alter the parameters to it before then re-throwing it.
Of course, because of the abstraction in Aurelia, this is not an option for most of us, unless we want to go about changing the http client library code.
Some of the marks for this need to go to "TheBlueFox" for His/Her comments above.
The solution ended up being something like the following:
import { inject } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { HttpClient, Interceptor } from 'aurelia-http-client';
import environment from './environment';
import Debugger = require("_debugger");
#inject(HttpClient, Router)
export default class httpservice {
private http: HttpClient = null;
private router: Router = null;
private authService: any = null;
private authToken: string = "";
private myInterceptors: Interceptor;
constructor(HttpClient, Router) {
this.http = HttpClient;
this.router = Router;
HttpClient.configure(http => {
http.withBaseUrl(environment.servicebase);
http.withInterceptor(new HttpInterceptors());
});
}
public setAuthService(authService: any) {
this.authService = authService;
}
public get(url: string, authObject?: any): any {
let myAuth = this.authService ? this.authService : authObject;
let myToken = "";
if (myAuth) {
myToken = myAuth.getAuthToken();
}
let client = this.http
.createRequest(url)
.asGet()
.withHeader("AuthenticationToken", myToken);
return client;
}
public post(url: string, postData: any, authObject?: any): any {
let myAuth = this.authService ? this.authService : authObject;
let myToken = "";
if (myAuth) {
myToken = myAuth.getAuthToken();
}
let self = this;
let client = this.http
.createRequest(url)
.asPost().withContent(postData)
.withHeader("AuthenticationToken", myToken);
return client;
}
}
class HttpInterceptors implements Interceptor {
responceError(error)
{
if (error.statusCode === 0) {
throw new Error("Could not contact server");
}
if (error.statusCode === 401) {
// do auth handling here
}
if (error.statusCode === 404) {
// do 404 handling here
}
return error;
}
}
The magic is in the HttpInterceptors class attached to the bottom of my HttpService. You should be able to see a check for a status code of 0, and that the actual action performed here is to throw a new error.
It's the action of this new error being thrown that then causes the "catch" in the actual call to the http client to be caught.
If you don't throw at that point, then everything just falls apart and you get the scenario seen in my original question post, throw and you get to catch it and deal with it in user code.
This way of doing things is also apparent in the aurelia-fetch-client too, as that works in a broadly similar way, using the BlueBird promise library.

Why Context.User.Identity.Name is empty from Xamarin?

I can't figure out why when I try to connect from Xamarin Context.User.Indetity.Name is empty. Is there anything special I need to do? I logged in to the server and the user has a connection stablished. After that I use the following code:
var Connection = new HubConnection(Url);
_hub = Connection.CreateHubProxy(hubName);
_hub.On(srvEvent, onData);
await Connection.Start();
But I never get the username. What am I doing wrong?
Here's the code for the server:
var name = Context.User.Identity.Name;
Connections.Add(name, Context.ConnectionId);
return base.OnConnected();
It works when it comes from the web app, not from the xamarin app.
Thanks!
Here is the code I was telling you about.
I'm using an external OAuth2 server for authentication, so I must pass the access token to SignalR somehow, because SignalR uses web sockets for the messages back and forth I can't pass the access token in the header because this is not supported by web sockets.
I'm passing that access token as a query string parameter this way (Javascript client)
$.connection.hub.qs = "access_token=" + mytoken;
Then on my SignalR I added a middleware that takes that query string and adds it to the header as an Authorization header using Bearer Token. This is done this way in my startup class
app.UseAuthQSTokenExtractor();
The code for the middleware is this one
namespace Owin
{
public static class AuthorizationQSTokenExtractorExtension
{
public static void UseAuthQSTokenExtractor(this IAppBuilder app)
{
app.Use<AuthorizationQsTokenExtractorMiddleware>();
}
}
}
namespace Chat.Middleware
{
public class AuthorizationQsTokenExtractorMiddleware : OwinMiddleware
{
public AuthorizationQsTokenExtractorMiddleware(OwinMiddleware next)
: base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
Debug.WriteLine("signalr-auth-middleware");
string bearerToken = context.Request.Query.Get("access_token");
Debug.WriteLine("signar-bearer: " + bearerToken);
if (bearerToken != null)
{
TokenHelper.DecodeAndWrite(bearerToken);
string[] authorization = { "Bearer " + bearerToken };
context.Request.Headers.Add("Authorization", authorization);
}
await Next.Invoke(context);
}
}
My startup class then looks like this
app.UseCors(CorsOptions.AllowAll);
app.UseAuthQSTokenExtractor();
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
app.UseIdentityServerBearerTokenAuthentication(
new IdentityServerBearerTokenAuthenticationOptions
{
Authority = ConfigurationManager.AppSettings["api:idserver"],
RequiredScopes = new[]
{
"chat-hub"
}
});
var hubConfiguration = new HubConfiguration ();
hubConfiguration.EnableDetailedErrors = true;
app.RunSignalR(hubConfiguration);
You can see in the code above where I tell SignalR to use the Oauth2 Server, that code is this one
app.UseIdentityServerBearerTokenAuthentication(
new IdentityServerBearerTokenAuthenticationOptions
{
Authority = ConfigurationManager.AppSettings["api:idserver"],
RequiredScopes = new[]
{
"chat-hub"
}
});
After all this is set up I have access to my Context.User.Identity.Name and if you want to get the others IdentityClaim you can do this
var identity = Context.User.Identity as ClaimsIdentity;
Which I'm using that code above to get the subjectId (userid) like this
public static string[] GetIdentityClaimsIssSub(HubCallerContext Context)
{
var identity = Context.User.Identity as ClaimsIdentity;
if (identity == null)
return null;
var issuerFromIdentity = identity.FindFirst("iss");
var subFromIdentity = identity.FindFirst("sub");
if (issuerFromIdentity == null || subFromIdentity == null)
return null;
return new string[] { issuerFromIdentity.Value, subFromIdentity.Value };
}
I hope it helps

Connect to Server using xamarin forms

I'm developing Xamarin Cross platform application. I'm trying to connect to server (http://test.net/login/clientlogin), I need to send these fields (password = "xyz"; platform = iphone; (useremail) = "test#test.com";) along with the request. So that server will check these parameters and returns XML. But we don't know how to add these fields to the request.
When i open the above string url (http://*****/login/clientlogin) i am getting login screen, with in that we have username, password and platform text fields.
Thanks in advance!!!..
This should get you started presuming you are adding the values as headers in the request:
public class TestClient
{
HttpClient client;
public TestClient(){
this.client = new HttpClient ();
}
public void AddHeadersAndGet(){
client.DefaultRequestHeaders.Add ("username", "whatevertheusernameis");
this.GetAsync<WhateverObjectTypeYouAreReceiving> ("theurloftheservice");
}
public async Task<T> GetAsync<T>(string address){
HttpResponseMessage response = null;
response = await client.GetAsync (address);
if (response.IsSuccessStatusCode) {
try {
var responseString = await response.Content.ReadAsStringAsync ();
return new T (Serializer.DeserializeObject<T> (responseString),
response.StatusCode);
} catch (Exception ex) {
}
} else {
}
}
}
The key line for you is:
client.DefaultRequestHeaders.Add ("username", "whatevertheusernameis");

Connect database using Ajax?

I want to use Ajax for UserId validation, Can anyone help me out in connecting database?
Here is my JSP page .
enter code here
<script type="text/javascript">
/*
* creates a new XMLHttpRequest object which is the backbone of AJAX,
* or returns false if the browser doesn't support it
*/
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 c=document.getElementById("userid").value;
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("POST", "../userid", true);
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form- urlencoded");
xmlHttpRequest.send("requestType=ajax&userid="+c);
}
/*
* Returns a function that waits for the state change in XMLHttpRequest
*/
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned
// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
document.getElementById("print").innerHTML = xmlHttpRequest.responseText;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
<form action="<%=application.getContextPath() %>/Login" method="post" name="myForm">
<table>
<tr>
<td>UserId</td>
<td><input type="text" name="userid" id="userid" onblur="makeRequest()" > </td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" > </td>
</tr>
<tr><td></td>
<td><input type="submit" name="submit" value="Submit"></td>
<td><input type="hidden" name="requestType" value="Login"> </td>
</tr>
</table>
</form>
</script>
Please help me out for this. I require user id validation. If correct userid then it should display name, else display error msg.
To validate user:
Create a service/dao class with a method that interacts with database and returns boolean type.
create a Servlet and implement doPost() and use created service/dao class.
Finally, return true if user found, otherwise false in response.
In javascript display the message or error based on response from server.
for example:
create UserService class that will be look like:
public class UserService {
public Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");//register database driver
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "****", "*****");
}
/**
* Checks a User id is exists in database using given user id<br/>
* <b>Note:</b> this method closes Connection and PreparedStatement you have passed as parameter
* #param pStatement A PreparedStatement instance with query to fetch result
* #return a true if user id found in database, else false returned.
*/
public boolean isUserExists(final String userId) {
if(userId==null || userId.isEmpty())
return false;
//declare required fields
Connection connection = null;
ResultSet rSet = null;
PreparedStatement pstmt = null;
boolean isExists = false; //set userId exists false initially
try{
connection = getConnection(); //get a connection to intract with database.
//create a PrepareStatement instance to fetch user id from database
pstmt = connection.prepareStatement("SELECT login FROM users WHERE login=?");
pstmt.setString(1, userId); // set user id which you want to retrieve from DB.
rSet = pstmt.executeQuery(); //execute the query
if(rSet.next()){ //check if you got any
System.out.printf("User id %s found",rSet.getString(1));
isExists = true; //user id exists, set true
}
}catch(SQLException e){
e.printStackTrace();
}finally{
//close all like: Connection, ResultSet and PreparedStatement etc
try { if (rSet != null) rSet.close(); } catch (Exception e) {};
try { if (pstmt != null) pstmt.close(); } catch (Exception e) {};
try { if (connection != null) connection.close(); } catch (Exception e) {};
}
return isExists;
}
}
and the Servlet will look like:
#WebServlet("/validateUserIdByAjax")
public class ValidateUserIdByAjax extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserService userService = new UserService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost() invoked..");
// Set response content type
response.setContentType("text/html");
// Set encoding
response.setCharacterEncoding("UTF-8");
//get user entered id
String userId = request.getParameter("userid");
//return userid status
response.getWriter().print(userService.isUserExists(userId));
}
}
Then, check response from server and show message in javascript like:
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned
// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
var $print = document.getElementById("print");
var res = xmlHttpRequest.responseText;
console.log('user status: '+res);
if(res=="true"){
$print.innerHTML = '<span style="color:red;">user id exists!</span>';
}else{
$print.innerHTML = '<span style="color:green;">user id available!</span>';
}
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
that's it.
Note:
your AJAX POST url should match your Servlet url-patteren, in my case validateUserIdByAjax is the servlet url-pattern so AJAX url will look like:
xmlHttpRequest.open("POST", "validateUserIdByAjax", true);.
and Database driver class should be available in CLASSPATH, in my case i have used mySql so mysql-connector-java.jar is added to CLASSPATH.
In your question not have any element by id print, So please add to see the message while using above example,
like: <span id="print"></span>
make a jsp page with database connectivity that will be requested for output.....
in your ajax request send user_id and in jsp page get userid and check it from database ...if available then send true to ajax otherwise false.....
or in ajax response get message result from jsp page...make condition to handle this........

Resources