Using Cookies for Session Maintenance gives output Hello72EB80AEBFB7831A35879408414F9ABA - java

I am making a small program where user's name will be used all over the pages where he navigates. I have written following code.
JSP file:
<form action="CookieServletOne" method="post">
User Name:<input type="text" name="username">
<input type="submit" value="Go">
</form>
Servlet One (under post method):
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
String username=request.getParameter("username");
pw.println("Welcome " +username);
Cookie ck=new Cookie("un",username);
response.addCookie(ck);
pw.print("<form action='CookieServletTwo'>");
pw.print("<input type='submit' value='go'>");
pw.print("</form>");
pw.close();
Servlet2:
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
Cookie[] ck=request.getCookies();
pw.write("Hello" +ck[0].getValue());
I want to take the value which is written in text box to the Servlet2 by using cookies. But,
At the end it is printing value something like this:
Hello5BD0268F522455DA719130360F74A969
What I am doing wrong here ???
Server: Apache Tomcat.
Jdk: 1.7
Os: lubuntu.
Thanks.

You should be adding below code to your servlet2 to get your desired result.The output which you are getting is JSESSIONID.
Cookie[] ck=request.getCookies();
for(int i=0; i<ck.length; i++) {
if("un".equals(ck[i].getName())) {
pw.write("Hello" +ck[i].getValue());
}
}

Related

Google reCAPTCHA: How to get user response and validate in the server side?

I am doing a Java (JSP + Servlet) web application (I understand that this question is technology-independent). I hope to use the latest Google reCAPTCHA service.
I am playing with a Google reCAPTCHA example found here:
https://developers.google.com/recaptcha/docs/display#config
<html>
<head>
<title>reCAPTCHA demo: Simple page</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="?" method="POST">
<div class="g-recaptcha" data-sitekey="my_site_key"></div>
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
I am able to see the displayed recaptcha image as follows:
When I check "I'm not a robot", I get the following:
As you can see, there is a Verify button and based on my tests, user response is sent to Google for verification.
How can I get the user response so that I can verify user response in my own backend code (as suggested by Google at https://developers.google.com/recaptcha/docs/verify).
g-recaptcha-response POST parameter when the user submits the form on your site
On the server side, I can, by clicking on the "Submit" button, get user input from parameter "g-recaptcha-response" only when a user is verified successfully with Google first. Otherwise, "g-recaptcha-response" is blank on the server side. This means that I can do server-side verification only after the client-side's verification success. If so, what is the point of doing another verification on the server-side, which is the option provided by Google reCAPTHA?
Do I miss anything?
The cool thing about the new Google Recaptcha is that the validation is now completely encapsulated in the widget. That means, that the widget will take care of asking questions, validating responses all the way till it determines that a user is actually a human, only then you get a g-recaptcha-response value.
But that does not keep your site safe from HTTP client request forgery.
Anyone with HTTP POST knowledge could put random data inside of the g-recaptcha-response form field, and fool your site to make it think that this field was provided by the google widget. So you have to validate this token.
In human speech, it would be like,
Your Server: Hey Google, there's a dude that tells me that he's not a robot. He says that you already verified that he's a human, and he told me to give you this token as proof of that.
Google: Hmm... let me check this token... yes I remember this dude I gave him this token... yeah he's made of flesh and bone let him through.
Your Server: Hey Google, there's another dude that tells me that he's a human. He also gave me a token.
Google: Hmm... it's the same token you gave me last time... I'm pretty sure this guy is trying to fool you. Tell him to get off your site.
Validating the response is really easy. Just make a GET request to
https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address
And replace the response_string with the value that you earlier got by the g-recaptcha-response field.
You will get a JSON Response with a success field.
More information here:
https://developers.google.com/recaptcha/docs/verify
Edit: It's actually a POST, as per documentation here.
A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.
Check the success field for true or false
private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
JsonObject jsonObject = null;
URLConnection connection = null;
InputStream is = null;
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String url = "https://www.google.com/recaptcha/api/siteverify";
try {
String query = String.format("secret=%s&response=%s&remoteip=%s",
URLEncoder.encode(secret, charset),
URLEncoder.encode(response, charset),
URLEncoder.encode(remoteip, charset));
connection = new URL(url + "?" + query).openConnection();
is = connection.getInputStream();
JsonReader rdr = Json.createReader(is);
jsonObject = rdr.readObject();
} catch (IOException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return jsonObject;
}
Hi curious you can validate your google recaptcha at client side also 100% work for me to verify your google recaptcha just see below code
This code at the html body:
<div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
<span id="captcha" style="margin-left:100px;color:red" />
This code put at head section on call get_action(this) method form button:
function get_action(form) {
var v = grecaptcha.getResponse();
if(v.length == 0)
{
document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
return false;
}
if(v.length != 0)
{
document.getElementById('captcha').innerHTML="Captcha completed";
return true;
}
}
Here is complete demo code to understand client side and server side process. you can copy paste it and just replace google site key and google secret key.
<?php
if(!empty($_REQUEST))
{
// echo '<pre>'; print_r($_REQUEST); die('END');
$post = [
'secret' => 'Your Secret key',
'response' => $_REQUEST['g-recaptcha-response'],
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
echo '<pre>'; print_r($server_output); die('ss');
}
?>
<html>
<head>
<title>reCAPTCHA demo: Explicit render for multiple widgets</title>
<script type="text/javascript">
var site_key = 'Your Site key';
var verifyCallback = function(response) {
alert(response);
};
var widgetId1;
var widgetId2;
var onloadCallback = function() {
// Renders the HTML element with id 'example1' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'widgetId1'.
widgetId1 = grecaptcha.render('example1', {
'sitekey' : site_key,
'theme' : 'light'
});
widgetId2 = grecaptcha.render(document.getElementById('example2'), {
'sitekey' : site_key
});
grecaptcha.render('example3', {
'sitekey' : site_key,
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
</head>
<body>
<!-- The g-recaptcha-response string displays in an alert message upon submit. -->
<form action="javascript:alert(grecaptcha.getResponse(widgetId1));">
<div id="example1"></div>
<br>
<input type="submit" value="getResponse">
</form>
<br>
<!-- Resets reCAPTCHA widgetId2 upon submit. -->
<form action="javascript:grecaptcha.reset(widgetId2);">
<div id="example2"></div>
<br>
<input type="submit" value="reset">
</form>
<br>
<!-- POSTs back to the page's URL upon submit with a g-recaptcha-response POST parameter. -->
<form action="?" method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
</body>
</html>

QueryString not reading in Servlet - NullPointer Exception

I have a simple case of calling a servlet with query parameters on a button click. The issue is, in the servlet when I try to read the query parameters, I am getting null.
This is my jsp code snippet.
<form action="http://localhost:8080/ChartsApp/apps/CreateXMLServlet?r=0.7180008697323501&fc=03&fc=04&fc=05">
<input type="submit" title="Submit"/>
</form>
This is my servlet code snippet in the doPost
System.out.println(request.getQueryString());
String[] selectedCodes = (String[]) request.getParameterValues("fc");
if (selectedCodes != null) {
for (int i = 0; i < selectedCodes.length; i++) {
System.out.println("fc[" + i + "] = " + selectedCodes[i]);
}
}
The first sout is printing null, and I am getting nullpointer exception in the subsequent lines. What am I doing wrong?
Add the "post" method in form tag to access the request parameters.
<form method="post" action="http://localhost:8080/ChartsApp/apps/CreateXMLServlet?r=0.7180008697323501&fc=03&fc=04&fc=05">
<input type="submit" title="Submit"/>

How to pass a value from one jsp to another jsp page?

I have two jsp pages: search.jsp and update.jsp.
When I run search.jsp then one value fetches from database and I store that value in a variable called scard. Now, what I want is to use that variable's value in another jsp page. I do not want to use request.getparameter().
Here is my code:
<%
String scard = "";
String id = request.getParameter("id");
try {
String selectStoredProc = "SELECT * FROM Councel WHERE CouncelRegNo ='"+id+"'";
PreparedStatement ps = cn.prepareStatement(selectStoredProc);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
scard = rs.getString(23);
}
rs.close();
rs = null;
} catch (Exception e) {
out.println(e.getLocalizedMessage());
} finally {
}
%>
How can I achieve this?
Using Query parameter
<a href="edit.jsp?userId=${user.id}" />
Using Hidden variable .
<form method="post" action="update.jsp">
...
<input type="hidden" name="userId" value="${user.id}">
you can send Using Session object.
session.setAttribute("userId", userid);
These values will now be available from any jsp as long as your session is still active.
int userid = session.getAttribute("userId");
Use sessions
On your search.jsp
Put your scard in sessions using session.setAttribute("scard","scard")
//the 1st variable is the string name that you will retrieve in ur next page,and the 2nd variable is the its value,i.e the scard value.
And in your next page you retrieve it using session.getAttribute("scard")
UPDATE
<input type="text" value="<%=session.getAttribute("scard")%>"/>
Use below code for passing string from one jsp to another jsp
A.jsp
<% String userid="Banda";%>
<form action="B.jsp" method="post">
<%
session.setAttribute("userId", userid);
%>
<input type="submit"
value="Login">
</form>
B.jsp
<%String userid = session.getAttribute("userId").toString(); %>
Hello<%=userid%>
How can I send data from one JSP page to another JSP page?
One of the best answer which I filtered out from above discussion.
Can be done in three ways:
using request attributes:
Set the value to send in request attribute with a name of your choice as request.setAttribute("send", "valueToSend") and retrieve it on another jsp using request.getAttribute("send");
using session attributes
Similar to above but using session object instead of request.
using application attributes
Same as 1 and 2 above but using application object in place of request and session.
Suppose we want to pass three values(u1,u2,u3) from say 'show.jsp' to another page say 'display.jsp'
Make three hidden text boxes and a button that is click automatically(using javascript).
//Code to written in 'show.jsp'
<body>
<form action="display.jsp" method="post">
<input type="hidden" name="u1" value="<%=u1%>"/>
<input type="hidden" name="u2" value="<%=u2%>" />
<input type="hidden" name="u3" value="<%=u3%>" />
<button type="hidden" id="qq" value="Login" style="display: none;"></button>
</form>
<script type="text/javascript">
document.getElementById("qq").click();
</script>
</body>
// Code to be written in 'display.jsp'
<% String u1 = request.getParameter("u1").toString();
String u2 = request.getParameter("u2").toString();
String u3 = request.getParameter("u3").toString();
%>
If you want to use these variables of servlets in javascript then simply write
<script type="text/javascript">
var a=<%=u1%>;
</script>
Hope it helps :)

Edit and update same textbox

I have a database Table where I can edit a value. I want to update the same, below is the code that I have tried.
The table code is as below
<table border="1px">
<tr>
<td><b>DBID</b></td>
<td><b>Query Raised</b></td>
<td><b>Time Raised</b></td>
<td><b>Query Answered</b></td>
<td><b>Time Answered</b></td>
</tr>
<%
try {
ps = con.prepareStatement("Select DBID, Query_Raised, TR, Query_Answered, TA from Scope1 where TR!='null'");
rs = ps.executeQuery();
while(rs.next()) {
%>
<tr>
<td><%=rs.getString("DBID")%></td>
<td><input type="Text" value="<%=rs.getString("Query_Raised")%>" name="Updat"></td>
<td><%=rs.getString("TR")%> </td>
<td><%=rs.getString("Query_Answered")%></td>
<td><%=rs.getString("TA")%></td>
<td><input type="Submit" value="Update"></td>
</tr>
<%
} // while loop ends here
rs.close();
con.close();
} catch(Exception e) {
out.println(e);
}
%>
</table>
and the update query that is used is:
String a = request.getParameter("Updat");
ps = con.prepareStatement("Update Scope1 Set Query_Raised = '" + a + "'");
int i = ps.executeUpdate();
if(i == 1) {
out.print("Done");
} else{
out.print("Erro");
}
I wanted to know the where condition that I should use to update the data in same page.
Thanks
I understand the first code part in the question is a JSP say update.jsp and the second part it seems is your servlet, say UpdateServlet.
So in your update.jsp on every row you have an <input type="text"> and submit button, but the <form> I think is only one which must be outside the <table>, so here goes my solution (choose any one):
Use multiple <form> tags for each row, like
<form action="whatever_action_you_have_which_calls_the_servlet"
name="form<%=rs.getString("DBID")%>"
id="formID<%=rs.getString("DBID")%>">
// Including name and id so that the different forms remain unique
<tr>
<td><%=rs.getString("DBID")%></td>
<td><input type="Text" value="<%=rs.getString("Query_Raised")%>" name="Updat"></td>
<td><%=rs.getString("TR")%> </td>
<td><%=rs.getString("Query_Answered")%></td>
<td><%=rs.getString("TA")%></td>
<td><input type="Submit" value="Update"></td>
</tr>
</form>
So when you click on submit it would submit the <form> for which the submit button was clicked and would submit only the input which was edited and voila! your servlet code also works fine.
You can have both the blocks of code in the same JSP, then use the <form> code snippet as described in point#1 and the second code snippet would be:
String a = request.getParameter("Updat");
if ( (a is not empty) or (a is not null) ) {
ps = con.prepareStatement("Update Scope1 Set Query_Raised = '" + a + "'");
int i = ps.executeUpdate();
if(i == 1) {
out.print("Done");
} else{
out.print("Error");
}
}
...
<form action="whatever_action_you_have_which_will_call_this_JSP" ...>
<tr> ... your code as in point#1
</tr>
</form>
Use ajax and other javascript DOM manipulative methods to accomplish this as said by Endy.
For this you will need to have JSP (to display) & Servlet (to update the code).
This might be a little more effort but you will learn Ajax and will be a little more close to real world.
By far jQuery ajax is the simplest to use.
Note:
Just for the record, I know you might be practicing but if you are planning to use it in a real project then please read ahead.
It is a bad-practice to use scriptlets in JSP (unless really required and that too if it is for view-level logic and not business or data-level logic) and even worse is to use JDBC code inside a JSP. So it would be really great if you could follow f_puras's advice.
If you are wondering why I should listen to your unsolicited advice then here is some food for thought:
How to avoid scriptlets in JSP
Scriptless JSPs
Why JSP = JDBC is bad
Hope this helps.
You can either use AJAX to post the data to a page that handles the updating, then return the result as a callback, see http://api.jquery.com/jQuery.post/.
Other solution is to forward user back to the page with the form after you have processed the submission.
Third solution is to submit the data to the same page and parse/update it there.

Confused with Java Servlets and HTML

Part of my homework for tomorrow is to search and add entries using Java EE. If the search is not existing, an add item option will show as follow:
Supposedly, when the Stock ID is not existing, It will be transfered to the Add Item Text Field of StockID. But I have no idea how to do it. My code is as follows:
Servlet:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Item item = (Item) request.getAttribute("invenItem");
if (item != null) {
out.println("<html><title>Inventory Item</title>");
out.println("<body><h1>Inventory Item Details:</h1>");
out.println("Stock ID : " + item.getStockID() + "<br/>");
out.println("Name : " + item.getItemName() + "<br/>");
out.println("Unit Price: " + item.getUnitPrice() + "<br/>");
out.println("On Stock : " + item.getOnStock() + "<br/>");
out.println("</body>");
out.println("</html>");
} else {
RequestDispatcher rd = request.getRequestDispatcher("/DataForm.html");
rd.include(request, response);
out.println("Sorry Item not found..");
rd = request.getRequestDispatcher("AddEntry.html");
rd.include(request, response);
}
}
}
HTML:
<html>
<head>
<title>Add Entry</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h2>Add Item:</h2>
Stock ID: <input type ="text" name ="stockId" value="???"> <br> <--how to get it?
Item Name: <input type ="text" name ="name"> <br>
Unit Price: <input type ="text" name ="unitPrice"> <br>
On Stock : <input type ="text" name ="stock"> <br><br>
<input type ="submit" value ="Add Item">
</body>
</html>
You're approaching this the wrong way. HTML belongs in JSP files, not in Servlet classes. Also, EL ${} doesn't run in plain HTML files at all, but in JSP files only. Rename your .html files to .jsp. This way EL like ${param.id} will then also work, even though you still have a XSS attack hole open.
See also:
Our JSP wiki page
Our Servlets wiki page
(please read them, they contains hello world examples which should turn on some lights in your head)
You can't use the expression language (i.e. ${param.id}) in plain HTML files. It'll only be interpreted in JSPs (files with a .jsp extension).

Categories