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........
Related
I use spring mvc I want to uplaod image to jsp form so I add enctype="multipart/form-data" to the form tag but when i add this, modelAttribute values equals null in the controller
This is my form in jsp page:
<form:form action="saveContact" method="post" modelAttribute="Contacting" id="container" enctype="multipart/form-data">
This is the header of the function in controller:
#RequestMapping(value = "/saveContact", method = RequestMethod.POST)
public ModelAndView saveContact(#ModelAttribute ("Contacting") Contacting Contacting,ModelAndView modelndView,HttpServletRequest request ,HttpServletResponse response
) throws Exception {............}
#ModelAttribute ("Contacting") Contacting Contacting all values are null. and When I erease the enctype="multipart/form-data" from form tag its work well but I cant upload the image
this is the uplaud function:
public void uplaodImages(String url,HttpServletRequest request) {
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(THRESHOLD_SIZE);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uuidValue = "";
FileItem itemFile = null;
try {
// parses the request's content to extract file data
List formItems = upload.parseRequest(request);
Iterator iter = formItems.iterator();
// iterates over form's fields to get UUID Value
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
if (item.getFieldName().equalsIgnoreCase(UUID_STRING)) {
uuidValue = item.getString();
}
}
// processes only fields that are not form fields
if (!item.isFormField()) {
itemFile = item;
}
}
if (itemFile != null) {
// get item inputstream to upload file into s3 aws
BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);
AmazonS3 s3client = new AmazonS3Client(awsCredentials);
try {
ObjectMetadata om = new ObjectMetadata();
om.setContentLength(itemFile.getSize());
om.setContentType("image/png");
String ext = FilenameUtils.getExtension(itemFile.getName());
String keyName = uuidValue + '.' + ext;
// s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME,"99/after/img", itemFile,st om));
// s3client.setObjectAcl(S3_BUCKET_NAME, "99/after/img", CannedAccessControlList.PublicRead);
TransferManager tm = new TransferManager(new ProfileCredentialsProvider());
System.out.println("Hello");
// TransferManager processes all transfers asynchronously,
// so this call will return immediately.
Upload upload1 = tm.upload(
S3_BUCKET_NAME, url, itemFile.getInputStream(),om);
System.out.println("Hello2");
try {
// Or you can block and wait for the upload to finish
upload1.waitForCompletion();
System.out.println("Upload complete.");
} catch (AmazonClientException amazonClientException) {
System.out.println("Unable to upload file, upload was aborted.");
amazonClientException.printStackTrace();
}
} catch (AmazonServiceException ase) {
// LOGGER.error(uuidValue + ":error:" + ase.getMessage());
} catch (AmazonClientException ace) {
//LOGGER.error(uuidValue + ":error:" + ace.getMessage());
}
} else {
//LOGGER.error(uuidValue + ":error:" + "No Upload file");
System.out.println("No Upload file");
}
} catch (Exception ex) {
//LOGGER.error(uuidValue + ":" + ":error: " + ex.getMessage());
System.out.println(ex.getMessage());
}
//LOGGER.info(uuidValue + ":Upload done");
System.out.println("Upload done");
}
#RequestMapping(value = "/form.html", method = RequestMethod.POST)
public String handleFormUpload(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) throws Exception {
}
I am getting dynamic data for Company name select box. Based on those values I need to populate data for Business area select box. For that I am calling a servlet through AJAX.
In the servlet I am getting list of business areas based on company name, but I can't understand how I can pass this list to my JSP code.
I am getting dynamic data for select box like below:
Company Name:
<select id="company_id" onchange="getBusinessArea()">
<option selected="selected">--Select One--</option>
<% for (String txt : new ExtractDao().getCompanies()) {%>
<option><%=txt%></option>
<%}%>
</select>
By using the above company name i need to populate data for below select box:
Business Area :
<select>
<option><option>
</select>
I am calling my servlet using AJAX:
function getBusinessArea() {
var elem = document.getElementById("company_id");
var selectedNode = elem.options[elem.selectedIndex].value;
window.alert(selectedNode);
var xmlhttp;
var companyData = "${pageContext.request.contextPath}/ExtractController?companyName="
+ selectedNode;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
window.alert(companyData);
xmlhttp.open("GET", companyData, true);
xmlhttp.send();
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
My Servlet code:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ExtractService extService = null;
PrintWriter out = response.getWriter();
response.setContentType("text/html");
String companyName = request.getParameter("companyName");
extService = new ExtractService();
List<String> bList = extService.getBusinessAreas(companyName);
}
}
Can anyone help me show how I can populate data for business area select box?
I have an activity that is being swapped out when I raise an intent for another activity. onPause calls saveState() to save work so far:
private void saveState() {
...
...
if (myUri == null) {
// Inserting a new record
*** myUri = getContentResolver().insert(ContentProvider.CONTENT_URI, values);
} else {
// Update an existing record
getContentResolver().update(myUri, values, null, null);
}
}
Before calling getContentResolver(), ContentProvider.CONTENT_URI = 'content://nz.co.bkd.extraTime.contentprovider/times'.
After the call, myUri = 'times/#' where #=row ID. My question is; where is the 'content:...' prefix to the returned uri?
During the call, ContentResolver.java is called and returns CreatedRow uri
ContentResolver.java
....
....
public final Uri insert(Uri url, ContentValues values)
{
IContentProvider provider = acquireProvider(url);
if (provider == null) {
throw new IllegalArgumentException("Unknown URL " + url);
}
try {
long startTime = SystemClock.uptimeMillis();
*** Uri createdRow = provider.insert(url, values);
long durationMillis = SystemClock.uptimeMillis() - startTime;
maybeLogUpdateToEventLog(durationMillis, url, "insert", null /* where */);
return createdRow;
} catch (RemoteException e) {
// Arbitrary and not worth documenting, as Activity
// Manager will kill this process shortly anyway.
return null;
} finally {
releaseProvider(provider);
}
}
At this point, createdRow = 'times/#'.
The record does actually get saved in the Sqlite database.
Do I have to add the uri prefix in my code or should the full uri be returned?
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;
}
}
i am working with spring mvc framework. i have two submit buttons on a page. that are forwarding request to two different controller. how can i use two action on single jsp page .
please suggest.
my controller are as
1.
#RequestMapping(value = "/user/reset", method = RequestMethod.POST)
public String editUser(#ModelAttribute("users") User user,
BindingResult result) {
Integer uid=user.getId();
User resetUser = usersService.findUser(uid);
resetUser.setActive(0);
ResetPasswordLog resetPasswordLog=new ResetPasswordLog();
usersService.addUsers(resetUser);
resetPasswordLogService.setTempHash(uid);
String TEMPHASH= resetPasswordLog.getTempHash();
System.out.println("www.lacas.com/reset?uid="+uid+"&th="+TEMPHASH);
return "redirect:/secure/user/" + uid;
}
2.
#RequestMapping(value = "/user/edit", method = RequestMethod.POST)
public String addUser(#ModelAttribute("users") UserForm userForm,
BindingResult result) {
Map<String, String> map = new LinkedHashMap<String, String>();
User user = usersService.findUser(userForm.getId());
Integer userId = userForm.getId();
User newUser = usersService.findUser(userForm.getEmail());
user.setName(userForm.getName());
if (newUser == null) {
user.setEmail(userForm.getEmail());
user.getRoles().clear();
Integer[] roleIds = userForm.getRoleIds();
for (Integer roleId : roleIds) {
if (roleId != 0) {
Role role = roleService.findRole(roleId);
user.getRoles().add(role);
}
}
usersService.addUsers(user);
return "redirect:/secure/users/index";
} else {
edit_exist_user = true;
return "redirect:/secure/user/" + userId;
}
}
You can by using JavaScript, and changing form's action attribute dynamically. If this is your form:
<form id="myform" action="#" onsubmit="return pickDestination();">
<input type="submit" name="sbmitbtn" value="edit" onclick="document.pressed=this.value"/>
<input type="submit" name="sbmitbtn" value="reset" onclick="document.pressed=this.value"/>
</form>
Then your pickDestination JS function would look like:
function pickDestination()
{
var a = "/user/" + document.pressed;
document.getElementById("myform").action = a;
return true;
}
I'm going to preface this by saying that I'm not very familiar with spring applications, however in many other java based MVC systems I've accomplished this by simply giving my submit buttons a name and parsing off this in the action class by checking the request.
For example find which submit button was used by it's parameter name, call the appropriate methods. The following is an example of a struts based solution I use on occasion. If you can access the servlet request object in your spring controller, you could do something similar.
#Override
public String execute() throws Exception {
try {
// Check the request for a someone clicking the logout submit button
if (found("logout")) {
user.logout(); //invoke the logout method
session.remove("user");
return SUCCESS;
}
// Check the request for a someone clicking the login submit button
if (found("login")) {
user.login();
session.put("user", user);
return "login";
}
// Catch any login exceptions
} catch (Exception e) {
user = null;
addActionError(e.getMessage());
return INPUT;
}
return SUCCESS;
}
// The following method checks for a request paramater based on the key (String)
// provided. If the key is not found or the value for the parameters is empty, it
// returns false;
private boolean found(String param) {
Object temp = request.getParameter(param);
if (temp != null) {
if (temp.toString().isEmpty()) {
return false;
}
return true;
} else {
return false;
}
}