This question is related to the previous one, when I click over an anchor
send email
it calls servlet using json
$("#Email").click(function() {
var option={
"action":"sendEmail"
};
$.getJSON('StudentManagementServlet',option, function(hasEmail) {
if(hasEmail == false){
// //view form to let user enter his email
$("#CommViaEmail").fadeIn("normal");
}
});
});
in servlet I handle the request
if (action != null && action.equals("sendEmail")) {
//open connection to db
con.setAutoCommit(false);
String email = ParentManagement.getParentEmail(con, stdNo);
if (email != null) {
String commResult = createAccountAndSendEmail(con, parentNo, email);
request.setAttribute("result", commResult);
request.setAttribute("incp", "ResultPage");
RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response); //doesn't make forward!!!!!
System.out.println(">>send email DONE!!");
con.commit();
return;
} else {
boolean hasEmail = false;
String json = new Gson().toJson(hasEmail);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
The problem here is if user has an email, then I send an email but request dosn't forward to result page, even the print statement is printed " System.out.println(">>send email DONE!!");" ??
You need to let JS/jQuery do that job. Let the servlet write true as JSON result and in JS do
if (hasEmail) {
window.location = 'index.jsp';
} else {
$("#CommViaEmail").fadeIn("normal"); //view form to let user enter his email
}
Or when you want to control the URL yourself, add the new location to the JSON
Map<String, Object> data = new HashMap<String, Object>();
data.put("hasEmail", true);
data.put("location", "index.jsp");
// ...
with
..., function(data) {
if (data.hasEmail) {
window.location = data.location;
} else {
$("#CommViaEmail").fadeIn("normal"); //view form to let user enter his email
}
}
You are making an AJAX request from the client and are trying to 'forward' that request in the server side.
AJAX requests DONT refresh the page. The hasEmail variable in javascript function will be a string containing the HTML of the index.jsp.
Related
I am trying to get string "Error. Does this link come from email? Or maybe you have used your token already?" as a response if requesty is not correct (excactly such response I get in Postman) or "You have successfully changed your password." if request is ok, but instead of that on my website when I get directly from param of subscribe I get Object object, but when I use function JSON.stringify then I get something like that.
Here is my code:
submitFunc() {
this.data = '';
if (this.uploadForm.invalid) {
console.log('Password validation invalid')
return;
}
console.log('Password validation correct')
const response = this.restapiService.postResetPassword(this.tokenFromUrl, this.uploadForm.controls['password'].value);
response.subscribe(data => { console.log('a '+JSON.stringify(data)); },
error => { console.log('b '+JSON.stringify(error)); });
}
and
public postResetPassword(token: string, password: string): Observable<any> {
const body = {
'token': token,
'password': password
};
const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
return this.http.post<any>('https://jakuwegiel-backend.herokuapp.com/reset_password', body,{headers: headers});
}
and my part of controller in backend
#PostMapping(value = "/reset_password", consumes="application/json")
public String processResetPassword(#RequestBody TokenAndPassword tokenAndPassword) {
try {
User user = userService.getByResetPasswordToken(tokenAndPassword.getToken());
if (user == null) {
return "message";
} else {
userService.updatePassword(user, tokenAndPassword.getPassword());
System.out.println("You have successfully changed your password.");
}
}
catch (Exception ex) {
System.out.println("aaaaaaaaaaaaa " +ex.getMessage());
return "Error. Does this link come from email? Or maybe you have used your token already?";
}
return "You have successfully changed your password.";
}
Is there anything you need more?
You need to console.log(error.error.text). And then you will be able to make this value in your text message.
i have the following pice of code 'anmelden.java':
#WebServlet("/anmelden")
public class anmelden extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String benutzer = request.getParameter("benutzer");
String passwort = request.getParameter("passwort");
try {
PrintWriter out = response.getWriter();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test","admin","*****");
PreparedStatement stmt = con.prepareStatement("SELECT benutzer,passwort,rolle FROM login WHERE benutzer = ? AND passwort = ?");
stmt.setString(1, benutzer);
stmt.setString(2, passwort);
ResultSet rs = stmt.executeQuery();
if(rs.next())
{
HttpSession session = request.getSession();
session.setAttribute("benutzer", rs.getString("benutzer"));
RequestDispatcher dis = request.getRequestDispatcher("mandant.jsp");
dis.forward(request, response);
out.print("1");
}
else
{
out.print("Benutzername und/oder Passwort falsch");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my jsp file 'login.jsp':
$("#anmelden").click(function(){
var benutzer = $("#benutzer").val();
var passwort = $("#passwort").val();
if(benutzer == "" || passwort == "")
{
return;
}
$.ajax({
url:"anmelden",
type:"POST",
data:"benutzer="+benutzer+"&passwort="+passwort
}).success(function(data){
var erfolg = data;
if(erfolg == "1")
{
window.location.href="http://localhost:8080/PSD/mandant.jsp";
}
else
{
$("#ok").text(erfolg);
}
});
});
As u can see i tries to set the name coming from my DB into my session Attribute.
I want to use the Attribute in my 'mandant.jsp' file.
But it dosen't work - all what happens is, that my 'login.jsp' file which makes the ajax call, print the code from 'mandant.jsp' into my div as text.
So it dosen't opend the next page as i want -.-
But if i comment out the HttpSession block then it works fine but then i can't use ,of course,the session Attribute.
So what's wrong or what must i change so that this code works?
Many thanks
This is because this part of the code:
RequestDispatcher dis = request.getRequestDispatcher("mandant.jsp");
dis.forward(request, response);
is generating the HTML from mandant.jsp file using the request object (along with HttpSession and ServletContext) to fulfill any Expression Language and writing this HTML into the response. Just remove these lines and you'll be ok.
You are mixing two types of communication here, from the JSP page you are making an ajax call but from the Servlet you are making a Dispatch redirect.
If you want the login page to be redirected after a a successful login then don't call the Servlet with an ajax call and better do a form submit.
If you rather want to only check credentials on the servlet and redirect from the client then keep the ajax call but avoid the request dispatcher in the servlet and return a success/error code instead. Then capture that code from the ajax response and redirect to a successful page if you want.
I am doing a toy program that asks user to input "username" and "fullname" on an html form, the form will be submitted by AJAX to the following method in Spark framework (see here for Spark:
post("/admin/user/signup", "application/json", (request, response) -> {
String username = request.queryParams("username");
String fullname = request.queryParams("fullname");
System.out.println("username is: " + username +", full name is: " + fullname);
Map<String, Object> registerResults = new HashMap<String, Object>();
registerResults.put("success", "successfully registered " + username);
return new MyMessage("successful registration!");
}, new JsonTransformer());
And the following is my AJAX code that supposedly submits and receives the response from the above post() method:
<script>
$(document).ready(function() {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize(); /* capture the form data*/
$.getJSON('/admin/user/signup', formData, registerResults);
// $.post('/admin/user/signup', formData, registerResults); /* get JSON back from the post method */
});
function registerResults(data) {
$('#registerForm').fadeOut();
$('.starter-template').html(data.message);
} // end of registerResults
}); // end of ready
</script>
However, the AJAX code cannot receive the JSON object, instead the JSON object is simply printed on the web page /admin/user/signup:
{"message":"successful registration!"}
So I am asking for help how to return the JSON object to AJAX request in Spark? thanks
You do realize that you are submitting the form. So instead of the supposed AJAX call the form is being submitted and hence the resulting page ...
So you should stop the form submit propagation by simply adding
event.preventDefault();
OR return false; at the end of the submit handler.
in the form submit handler.
<script>
$(document).ready(function() {
$('#registerForm').submit(function(event) {
event.preventDefault();
var formData = $('#registerForm').serialize(); /* capture the form data*/
$.getJSON('/admin/user/signup', formData, registerResults);
// $.post('/admin/user/signup', formData, registerResults); /* get JSON back from the post method */
});
function registerResults(data) {
$('#registerForm').fadeOut();
$('.starter-template').html(data.message);
} // end of registerResults
}); // end of ready
</script>
Instead of return new MyMessage("successful registration!");
Just pass like this return new MyMessage(registerResults);
now,you are not returning this registerResults map value.
I hope you are using play framework.then it should work
And one more thing,you should deny the form from submitting. so, use
$('#registerForm').submit(function(e) {
e.preventDefault();
// do your stuff here
});
You can not treat json as HTML by using html() function, you need to parse it by parseJson() function from jQuery: http://api.jquery.com/jquery.parsejson/
var obj = jQuery.parseJSON(data);
$('.starter-template').html(obj.message);
my ajax some how looks like this :
function getXMLHttpRequest() {
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
function makeRequest() {
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("POST", "http://abc.com:8080/someservletServlet/", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send(null);
}
function getReadyStateHandler(xmlHttpRequest) {
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
document.getElementById("xml").value = xmlHttpRequest.responseText;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
} but somehow the servlet is not bringing the response it should bring. can you help. what could be the possible error.
Ajax is the way to go.Because if you submit the request, page will refresh whether its same page or different.
If you still want to achieve it using without using ajax and refresh of page is fine with you then see if you have this kind of code in your servlet which is causing to forward it to some other page
String nextJSP = "nextPage.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
If you need to load some data from some other URL you'll need to send an AJAX request (explain where to get data from) and handle the AJAX response (explain what to do with the fetched data). To provide for a browser-compatible solution you'd better use some well-known JS library. For example, you could use jQuery in which case your script could look like:
$.ajax({
url: "servletURL",//servlet URL to post data to
type: "POST",//request type, can be GET
cache: false,//do not cache returned data
data: {id : idOfData},//data to be sent to the server
dataType: "xml"//type of data returned
}).done(function(data) {
//do something with XML data returned from server
});
With this approach you need to call the above JS code, probably wrapped in a JS function, on some JS event, i.e. click, and handle response data, for example, by appending its contents to your text area.
I'm trying to implement asynchronous login to JEE6 webapp using javascript and XMLHttpRequest. I should be able to make an asynchronous call with XMLHttpRequest to /app/j_security_check and parse the response somehow so that I can show the user a dialog with "Login Failed" or "Login success". I am using Glassfish 3.1.1.
Something I tried, but response is always null. I have a login.jsp that holds the login form and the following script:
function submitLogin(formName) {
var urlAction = "/app/j_security_check";
var client;
var dataString;
if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari
client = new XMLHttpRequest();
} else { // IE6, IE5
client = new ActiveXObject("Microsoft.XMLHTTP");
}
client.onreadystatechange = function() {
var response = client.responseText; // this is always null
/* ALERT THE DIALOG HERE ACCORDING TO RESPONSE? */
};
var form = document.forms[formName];
var username = form.elements["j_username"].value;
var password = form.elements["j_password"].value;
dataString = "j_username=" + username + "&j_password=" + password;
client.open("POST", urlAction, true);
client.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
client.send(dataString);
}
So my question is, is this possible and how should implement it?
Edit:
The problem here seems to arise from the redirect Java Security is enforcing after succesful/failed login. It seems to always redirect the page, no matter what I do with javascript. I also tried jQuery's ajax methods with no avail.
I do something similar maybe this will help you :
//Get a XMLHttpRequest object.
//The XMLHttpRequest specification defines an API that provides
//scripted client functionality for transferring data between a client and a server.
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax obj
/*
* Use this method to send data to server using ajax.
* Sent attribute name is : attribute
* Sent attribute value is : attribute:val
*/
function ajaxFunction(attribute,val, url) {
if(xmlhttp) {
var param = attribute+"="+attribute+":"+val;
param +="&tiers_payant="+document.getElementsByName("tiers_payant")[0].value; //Add the value to send here
xmlhttp.open("POST",url,true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(param);
}
}
/**
* When client received response from server,
* set the inner HTML of the page with the one returned by server.
*/
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
// DO what you want with : xmlhttp.responseText;
}
else {
document.getElementById("erreur").innerHTML="Le serveur le répond pas.";
//alert("Error during AJAX call. Please try again"+xmlhttp.status);
}
}
}