response.sendRedirect() shows error - mysql

I'm writing a simple jsp code for login which retrieves data from mysql. The code is showing error at response.sendRedirect("feedback.jsp");
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%
String user=request.getParameter("username");
String passwrd=request.getParameter("password");
try{
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/feedback", "root", "");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select username,password from users");
while(rs.next())
{
String username=rs.getString(1);
String password=rs.getString(2);
if(user.equals(username) && passwrd.equals(password))
{
response.sendRedirect("feedback.jsp");
}
else
{
out.println("Invalid Credentials");
}
}
}
catch(NumberFormatException e){
System.out.print(e);
e.printStackTrace();
}
%>
The connection to database is working as the else statement of "Invalid Credentials" is working if incorrect username and password combination is entered. The error i'm getting is "Cannot call sendRedirect() after the response has been committed"
Thanks.

if the URL is absolute http://www.google.com , it redirects to
http://www.google.com.
If the URL is not absolute , it redirects
relative to the current URL. If the URL starts with / it redirects
relative to the context root, Else it redirects to the current url
You should return after redirecting.
response.sendRedirect("http://www.google.com");
return;
It does not return automatically after calling sendRedirect().

First of all, Java code connecting to a database should be inside a servlet, and not inside a JSP. JSPs are view components. They should not use scriptlets AT ALL. Their only responsibility should be to generate HTML from attributes stored in the request by a controller, written in Java.
You get this exception because you try to redirect after sending data to the response already. Sending a redirect consists in setting a response header. And the headers are sent before the response body.
Also, your strategy for finding a user is extremely inefficient. You have the user name. So instead of getting all the users from the database and comparing them one by one with the username you have, you should add a where clause to your query:
select username, password from user where username = ?
Read the Java tutorial about prepared statements.
And finally, storing passwords in clear text in the database is a very bad practice. They should be hashed using a strong cryptographic hashing algorithm.

This is usually because you have sent response to the client, and you are changing or trying to send response after it is being sent to the user. Try removing any spaces or output before your redirect statement. In this case I would suggest remove all white-spaces before <% and then try executing your code.

Related

Parsing a page that has to be logged into with jsoup - cant find authentication key?

Right now I'm trying to parse a page behind a login - specifically, my own transcript of grades that must be logged in to access through the university website.
I am following this tutorial - http://joelmin.blogspot.ca/2016/04/how-to-login-to-website-using-jsoup-java_4.html - but the author mentions finding an authentication key, as shown here:
What I wish I saw - note authentication field
However, when I follow the steps, the form data I see looks like this:
What I actually see - no authentication key field
I then tried to adapt the steps by searching for an "It" id and a "execution" id, as they seem to change with every login, but they dont exist.
This is the site I am attempting to automate login to: https://cas.id.ubc.ca/ubc-cas/login
Any help would be appreciated :) I apologize if I'm missing something obvious!
Here is what you can try...
import org.jsoup.Connection;
Connection.Response res = null;
try {
res = Jsoup
.connect("https://cas.id.ubc.ca/ubc-cas/login")
.data("username", "your login id", "password", "your password")
.method(Connection.Method.POST)
.execute();
} catch (IOException e) {
e.printStackTrace();
}
Now save all your cookies and make request to the other page you want.
//Saving Cookies
cookies = res.cookies();
Making request to another page.
try {
Document doc = Jsoup.connect("your-second-page-link").cookies(cookies).get();
}
catch(Exception e){
e.printStackTrace();
}
Ask if further help needed.

Send both JSON response and model in Grails

I'm new to Grails and I'm stuck up with a problem. I want to know if there is a way to send both JSON and view and model through "render" in Grails.
I'm using a jQuery Datatable to display data returned from server which is read from JSON returned by the controller. I also need to display error messages on the same view in case of validation failure in form fields. But I'm able to return either only the JSON or model and view using render. I also tried sending the JSON through model itself but it didn't work.
This is my code:-
def hierarchyBreakInstance = new HierarchyBreak(params);
String json = "{\"sEcho\":\"1\",\"iTotalRecords\":0,\"iTotalDisplayRecords\":0,\"aaData\":[]}";
hierarchyBreakInstance.errors.reject(message(code: 'hierarchyBreak.error.division.blank'));
render(view: "hierarchyBreak", model: [hierarchyBreakInstance: hierarchyBreakInstance]);
//render json;
The gsp code:-
<g:hasErrors bean="${hierarchyBreakInstance}">
<div class="errorMessage" role="alert">
<g:eachError bean="${hierarchyBreakInstance}" var="error">
<g:if test="${error in org.springframework.validation.FieldError}" > data-field-id="${error.field}"</g:if>
<g:message error="${error}"/>
</g:eachError>
</div>
</g:hasErrors>
Could you please let me know if there is a way to do this. Thanks!
You can use like this.
def hierarchyBreakInstance = new HierarchyBreak(params);
String json = "{\"sEcho\":\"1\",\"iTotalRecords\":0,\"iTotalDisplayRecords\":0,\"aaData\":[]}";
hierarchyBreakInstance.errors.reject(message(code: 'hierarchyBreak.error.division.blank'));
render(view: "hierarchyBreak", model: [hierarchyBreakInstance: hierarchyBreakInstance,json:json]);
//render json;
Assuming that you are doing a request with some parameters, and need to return if was succesfull or not, and the data to fill the table with ajax.
I will do on that way, use the statuses of the HTTP to mark if it was a problem with the validation(normally we return 400 Bad Request and the message)
Example :
return ErrorSender.sendBadRequest("error validating field $field with value $value")
And the errorsender has a sendBadRequest method
[response: ['message': message, error: "bad_request", status: 400, cause: []], status: 400]
If the request was OK, you only need to respond the data with something like
return [response: results, status: 200]
In the client side you have to have one function if the request was OK to parse result, and one function if request have some validated data problem, database problem or whatever that caused that the request didnĀ“t return a 200(in the example),there are more status codes, you can check on
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
PD: Initial validation should be done on client side.

ASP.NET Web API: How to do a Post back results with redirection

I got a Web API that performs a function and posts a JSON response back to a calling page.
This is standard Web API behaviour and works beautifully.
Now I want to modify the controller so that in addition to the post back the user is redirected back to the page on the calling web site where the result of the Web API call can be displayed (in JSON).
So basically I want to:
(1) Server side post back the results in JSON to a page and redirect to the same page from the Web API
(2) On the caller's site, I want to display the JSON that was posted back.
How do I do this?
I already tried for many hours ...
e.g.:
using (WebClient client = new WebClient())
{
client.Headers.Add("Content-Type", "text/json");
client.Headers.Add("Accept", "text/json");
try
{
ErrorText = client.UploadString(redirectURL, "POST", JsonConvert.SerializeObject(orderresponse));
Response.Redirect(redirectURL);
}
catch (WebException err)
{
ErrorText = err.Message; //Todo - write to logfile
}
}
Instead of doing the redirect on the server, instruct the client to do it by using the appropriate HTTP status code. For example:
public HttpResponseMessage Post(MyModel model)
{
// handle the post
MyResult result = ...;
// redirect
var response = Request.CreateResponse<MyResult>(HttpStatusCode.Moved, result);
response.Headers.Location = new Uri("http://www.yourdomain.com/redirectURI");
return response;
}

Return JSON from one JSP to another?

Is it possible in one JSP to make a jQuery ajax callback to another JSP and have data returned?
I am trying to make the ajax call to Page2.jsp in the $(document).ready call in Page1.jsp
I am attempting to get JSON returned by "Page2.jsp"
I am running Tomcat locally to test.
I am seeing the JSON printed to the console, but not returned to the original calling method in Page1.jsp
Any ideas?
Page1.jsp
$(document).ready(function(){
$.ajax({
url : 'Page2.jsp',
dataType: 'json',
success : function(json)
{
var obj = jQuery.parseJSON(json);
}
});
});
Page2.jsp
<%#page contentType="application/json; charset=UTF-8"%>
<%#page import="org.json.simple.JSONObject"%>
<%
JSONObject json = new JSONObject();
json.put("amount","55.00");
json.put("tax","1.00");
String jString = JSONObject.toJSONString(json);
PrintWriter out = response.getWriter();
out.println(jString);
out.close();
%>
I tried the code in your question and the jQuery.parseJSON() code throw the following error: "SyntaxError: JSON.parse: unexpected character". On debugging I saw that the servlet code generated by tomcat includes out.write("\r\n"); I suspect that these character are causing the syntax error.
Nevertheless in the javascript I tried accessing the returned object using the dot notation without parsing it and I was able to so as if it were a JSON object. It appears that it is not necessary to parse the returned object.
The only modification I made to the JSP code was to remove the lines PrintWriter out = response.getWriter(); and out.close();

Unable to get right Website response with POST?

I would like to get the response of a website that has results posted by a form. I've tried using WebClient, WebRequests, etc.
Current Code:
using (var client = new WebClient())
{
var buffer = client.UploadValues("https://secure.monroecc.edu/pls/bpr1/bwzkfcls.P_GetCrse", "POST", vals);
return Encoding.UTF8.GetString(buffer, 0, buffer.Count());
}
Also pretty sure that the current code isn't wrong it's just missing something. When I do get the response of the website it's wrong, it's the page where you would fill out the form.
If you try to GET the website it results in this error on the website itself (without posting the variables that go along with it):
VARIABLES IN FORM NOT IN PROCEDURE:
NON-DEFAULT VARIABLES IN PROCEDURE NOT IN FORM: TERM_IN,SEL_SUBJ,SEL_CRSE,SEL_TITLE,BEGIN_HH,BEGIN_MI,BEGIN_AP,SEL_DAY,SEL_PTRM,END_HH,END_MI,END_AP,SEL_CAMP,SEL_SCHD,SEL_SESS,SEL_INSTR,SEL_ATTR,SEL_LEVL,SEL_INSM
DAD name: bpr1
PROCEDURE : bwzkfcls.P_GetCrse
URL : http://secure.monroecc.edu:63500/pls/bpr1/bwzkfcls.P_GetCrse
PARAMETERS :
===========
Here's an image of the request being sent. (Viewing using Chrome)
I know that the website usses oracle PLSQL but again that doesn't seem to help me with retrieving the results of the search.
I posted the form using the following code:
private void Run(string[] args)
{
NameValueCollection vals = new NameValueCollection();
vals.Add("TERM_IN", "");
vals.Add("SEL_SUBJ", "");
vals.Add("SEL_CRSE", "");
vals.Add("SEL_TITLE", "");
vals.Add("BEGIN_HH", "");
vals.Add("BEGIN_MI", "");
vals.Add("BEGIN_AP", "");
vals.Add("SEL_DAY", "");
vals.Add("SEL_PTRM", "");
vals.Add("END_HH", "");
vals.Add("END_MI", "");
vals.Add("END_AP", "");
vals.Add("SEL_CAMP", "");
vals.Add("SEL_SCHD", "");
vals.Add("SEL_SESS", "");
vals.Add("SEL_INSTR", "");
vals.Add("SEL_ATTR", "");
vals.Add("SEL_LEVL", "");
vals.Add("SEL_INSM", "");
using (var client = new WebClient())
{
var buffer = client.UploadValues("https://secure.monroecc.edu/pls/bpr1/bwzkfcls.P_GetCrse", "POST", vals);
Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, buffer.Count()));
//Console.Read();
}
}
It returns a 200 status code and valid html indicating that the form was received properly. However, since none of the values are correct the returned page says that there is a missing form element that must be included (NAME NOT FOUND FOR PIDM: )
The parameter mismatch error you are receiving means that the parameters you are passing in are not the ones that the stored procedure expects. You'll need to get an exact list of the parameters and expected values first, then you can just plug them in and this should work. Unfortunately the page returns a 200 status code so you'll have to parse out somehow whether there was an error or not.
Use a GET request instead of a POST.
You are asking for a page that follows a form to give you a result set when it never actually receives the form variables that would make the result possible.
Your variable vals which should pass the set of variables never does.
VARIABLES IN FORM NOT IN PROCEDURE:
NON-DEFAULT VARIABLES IN PROCEDURE NOT IN FORM: TERM_IN,SEL_SUBJ,SEL_CRSE,SEL_TITLE,BEGIN_HH,BEGIN_MI,BEGIN_AP,SEL_DAY,SEL_PTRM,END_HH,END_MI,END_AP,SEL_CAMP,SEL_SCHD,SEL_SESS,SEL_INSTR,SEL_ATTR,SEL_LEVL,SEL_INSM
This response error says that it never received any of the variables listed. I would trace back in your code to the location were you name and assigned your list of variables to the Collection vals. Check for proper spellings and proper assignment.