Trying to Use Captcha in my JSP page as below
<%# page import="net.tanesha.recaptcha.ReCaptcha" %>
<%# page import="net.tanesha.recaptcha.ReCaptchaFactory" %>
<html>
<head>
<title>Sample Application JSP Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" language="javascript" src="ajax.js"></script>
</head>
<body bgcolor=white>
<form action="CaptchaServlet">
<table border="0" cellpadding="10">
<tr>
<td width="10" align="center" height="10">
<img src="SimpleServletPath">
</td>
<td>
<h1>Sample Application JSP Page</h1>
</td>
</tr>
<tr>
<td>
Please Enter your Comments
<p>
<%
ReCaptcha c = ReCaptchaFactory.newReCaptcha
("6LdlHOsSAAAAAM8ypy8W2KXvgMtY2dFsiQT3HVq- ", "6LdlHOsSAAAAACe2WYaGCjU2sc95EZqCI9wLcLXY", false);
out.print(c.createRecaptchaHtml(null, null));
%>
<INPUT TYPE="TEXT" NAME="text1">
<input type="submit" value="submit" />
</p>
</td>
</tr>
</table>
</form>
</body>
</html>
The servlet is as follows
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String remoteAddr = request.getRemoteAddr();
ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
reCaptcha.setPrivateKey("6LdlHOsSAAAAACe2WYaGCjU2sc95EZqCI9wLcLXY");
String challenge = request.getParameter("recaptcha_challenge_field");
String uresponse = request.getParameter("recaptcha_response_field");
ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
PrintWriter out= response.getWriter();
if (reCaptchaResponse.isValid()) {
String user = request.getParameter("user");
out.write("CAPTCHA Validation Success! User "+user+" registered.");
} else {
out.write("CAPTCHA Validation Failed! Try Again.");
}
}
This works good, but the JSP page gets refreshed when submit value is clicked. How can we pass the Captcha values to Servlet using AJAX and return a value that the Capcha is valid or not without refreshing the page.
Here is the strategy.
Have your submit tracked by a javascript method. That method will send the captcha data to the server. and on sucesss or error the javascript will update the dom with the error message sent by the server/Servlet.
Follow this link https://gist.github.com/madan712/4972634.
In the link above it uses another jsp to validate ( working like a servlet) but you can give the url mapping name there in the url:[your_servlet_path]
Related
I have a dynamically generated table of data pulled from a database with individual buttons next to each entry for "update" and "delete". I am looking for a way to save table entry data when clicking the individual button next to the entry. With this data I want to pass it to another JSP to be used to auto populate field values.
User clicks button next to entry on table -> user taken to another form -> data from entry on original table is already populating values in new fields on new JSP to be updated and saved.
Ive been told this is possible without use of JavaScript however I am not against the idea of doing so.
JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<h1>List of all films</h1>
<form action=insert method ="get">
<button>Insert Film</button>
</form>
<form action=delete method ="get">
<button>Delete Film</button>
</form>
<form action=update method ="get">
<button>Update Film</button>
</form>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Year</th>
<th>Director</th>
<th>Stars</th>
<th>Review</th>
</tr>
<c:forEach items="${films}" var="c">
<tr>
<td>${c.id}</td>
<td>${c.title}</td>
<td>${c.year}</td>
<td>${c.director}</td>
<td>${c.stars}</td>
<td>${c.review}</td>
<td><form action=update method="get"><button>Update Film</button></form>
<td><form action=delete method="get"><button>Delete Film</button></form>
</tr>
</c:forEach>
</table>
</body>
</html>
Update Servlet:
#WebServlet("/update")
public class update extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("update.jsp");
rd.include(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String title = request.getParameter("title");
int year = Integer.parseInt(request.getParameter("year"));
String director = request.getParameter("director");
String stars = request.getParameter("stars");
String review = request.getParameter("review");
Film f = new Film (id,title,year,director,stars,review);
FilmDAO dao = new FilmDAO();
try {
dao.updateFilm(f);
}
catch (SQLException e) {
e.printStackTrace();
}
FilmDAO dao1 = new FilmDAO();
ArrayList<Film> allFilms = dao1.getAllFilms();
request.setAttribute("films", allFilms);
RequestDispatcher dispatcher = request.getRequestDispatcher("home.jsp");
dispatcher.include(request, response);
}
}
Update JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert film into database</title>
</head>
<body>
<form action="updateFilms" method ="post">
<label>Insert ID of film to update: <input type="number" name="id"/></label><br/>
<label>Title: <input type="text" name="title"/></label><br/>
<label>Year: <input type="number" name="year"/></label><br/>
<label>Director: <input type="text" name="director"/></label><br/>
<label>Stars: <input type="text" name="stars"/></label><br/>
<label>review: <input type="text" name="review"/></label><br/>
<input type="submit" value="Update film"/>
</form>
</body>
</html>
so i am new to ajax and currently trying to find out how to make ajax call from jsp form and then display it in div. Below is the jsp form which works fine and loads the data in divOrderResultContainer, i want to know how to get the same result by doing ajax call instead of refreshing the page everytime.
Index.jsp
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/view.css" media="all">
<script type="text/javascript" src="JavaScript/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="JavaScript/Calender.js"></script>
</head>
<body>
</div>
<hr>
<div id = "divuserinputContainer">
<table align="center" id="table">
<form name="orderform" action="OrderController" onsubmit="return validateForm()" method="POST"">
<td class="label">Branch Number
<select name="branch" >
<option selected value="0">All Branches</option><option selected value="1">100</option>
</select>
</td>
<td class="label">Service Type
<select class="SelectionBoxes" id="Serviceselect" name="Serviceselect" >
<option selected value="A">All</option>
<option value="D">Delivery</option>
</select>
</td>
<td class="label" >Order Status
<select class="SelectionBoxes" id="Orderstatus" name="Orderstatus">
<option selected value="O">All</option>
<option value="P">Placed</option>
</select>
</td>
<td>
<button class="submit" name="submit" id="submit">Submit</button></td>
</form>
</tbody>
</table>
</div>
<hr>
<div id="divOrderResultContainer">
<table id="ViewOrderResultContainer" border=1>
<thead><tr><th>OrderNumber</th>
<th>ServiceType</th>
<th>OrderStatus</th>
</tr></thead><tbody><c:forEach items="${orders}" var="order"><tr>
<td><c:out value="${order.ordernumber}" /></td>
<td><c:out value="${order.slotservice}" /></td>
<td><c:out value="${order.orderstatus}" /></td>
</tr></c:forEach></tbody></table>
</div>
</body>
</html>
my servlet OrderController.java
#WebServlet(name="OrderServlet",urlPatterns={"/OrderController"})
public class OrderController extends HttpServlet {
private static final long serialVersionUID = 1L;
public OrderController() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Int branchNumber = request.getParameter("branch");
String serviceType = request.getParameter("Serviceselect");
OrderDao dao = new OrderDao();
try {
request.setAttribute("orders",dao.getallorders(branchNumber,serviceType));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
RequestDispatcher view = request.getRequestDispatcher("Index.jsp");
view.forward(request, response);
}
}
Can someone explain to me about how can we do ajax call from jsp form after the user click the submit button or point me to a good examples ? Thanks in advance !!!
Use this for ajax request and response purpose
$(document).ready(function () {
$('#pinServId1').click(function () {
var value= $("inputField Id").val();
var request = $.ajax({
url: "/servletUrl",
method: "POST",
dataType: "text",
data: {userPassword: value}
});
request.done(function (response) {
$('#IdofDivtoDisplayOutput').val(response);
});
request.fail(function (jqXHR, textStatus) {
});});
});
In servlet use,
OutputStream outStream = response.getOutputStream()) {
response.setContentType("text/xml");
outStream.write(stringVariableName.toString().getBytes());//change name
outStream.flush();
This will output the string for ajax response.Place this code in doPost method of servlet.
I am trying to add a message in my jsp after the process is done by hitting the submit button.
function onSubmit() {
alert("Master_Data.xlsx and Consistency_Check_Data.xlsx are located under d:/stage/MasterDataReports");
}
</script>
<body>
<form name="input" action="getMasterData" method="get">
<br />
<br />
<h1 align='center'>Master Data File</h1>
<br />
<br />
<table border="0" align='center'>
<tr>
<td>
<h2>Site Name</h2>
</td>
<td align='left'>
<jsp:useBean id="masterDao" class="master.dao.MasterDataDao"/>
<select name="siteId" id="siteId">
<option value="0">ALL</option>
<c:forEach items="${masterDao.allSites}" var="siteDto">
<option value="${siteDto.id}">${siteDto.name}</option>
</c:forEach>
</select></td>
</tr>
<tr>
<td>
<h2>Division</h2>
</td>
<td align='left'>
<jsp:useBean id="masterDaoUtil" class="master.dao.util.MasterDataConstants"/>
<select name="divisionId" id="divisionId">
<option value="33"><%=MasterDataConstants.DIVISION_TYPE_AUDIT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="31"><%=MasterDataConstants.DIVISION_TYPE_CHANGE_MANAGEMENT_GLOBAL_NAME%></option>
<option value="34"><%=MasterDataConstants.DIVISION_TYPE_DEA_MANAGEMENT_GLOBAL_NAME%></option>
<option value="35"><%=MasterDataConstants.DIVISION_TYPE_EHS_MANAGEMENT_GLOBAL_NAME%></option>
<option value="23"><%=MasterDataConstants.DIVISION_TYPE_EVENT_MANAGEMENT_GLOBAL_NAME%></option>
</select></td>
</tr>
</table>
<br />
<br />
<div style="text-align: center">
**strong text**<input type="submit" value="Submit" OnClick="onSubmit()">
</div>
Right now the submit process will only happen after I clear the alert. Is there a way that I can either pop an alert after the submit process is done or if I can add a message to the jsp page?
Thanks in advance
Sonny
Here is my updated Servlet that is causing error:
package master.service;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
**strong text**import javax.servlet.http.HttpSession;
#SuppressWarnings("serial")
public class MasterDataServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response, HttpSession session)
throws IOException, ServletException {
MasterDataService masterDataService = new MasterDataService();
try {
int siteId = Integer.parseInt(request.getParameter("siteId"));
int divisionId = Integer.parseInt(request.getParameter("divisionId"));
//For master data file
masterDataService.createMasterDataFile(siteId, divisionId,false);
//For consistency checker file
masterDataService.createMasterDataFile(siteId, divisionId,true);
request.getRequestDispatcher("/masterDataQueryScreen.jsp").forward(request, response);
**strong text**session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
**strong text**response.sendRedirect("/masterDataQueryScreen.jsp");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.
In test.jsp
Create a javascript
<script type="text/javascript">
function alertName(){
alert("Form has been submitted");
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
Note:im not sure how to type the code in stackoverflow!.
Edit: I just learned how to
Edit 2:
TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect.
To do that i would highly recommendation to use session!
So what you want to do is in your servlet:
session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
response.sendRedirect(test.jsp);
than in the test.jsp
<%
session.setMaxInactiveInterval(2);
%>
<script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
if (Msg != "null") {
function alertName(){
alert("Form has been submitted");
}
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
So everytime you submit that form a session will be pass on! If session is not null the function will run!
in your servlet
request.setAttribute("submitDone","done");
return mapping.findForward("success");
In your jsp
<c:if test="${not empty submitDone}">
<script>alert("Form submitted");
</script></c:if>
You can also create a new jsp file sayng that form is submited and in your main action file just write its file name
Eg. Your form is submited is in a file succes.jsp
Then your action file will have
Request.sendRedirect("success.jsp")
I have a form in a Registeration.jsp page:
form name="users" method="post" onSubmit="return checkCorrect()"
action="Registeration.jsp">
The Script checkCorrect is written at the start of the page, returns true or false based on information submitted to the form (using getElementById if it matters) and the script definitely works (worked on html page without jsp before)
after the form I have this:
<% if(request.getMethod().equals("POST")){...}
And I need that the jsp part will work ONLY if and after the form is successfully submitted, but somehow the javascript script is not called and don't work and the form is always submitted.
What am I doing wrong?
edits:
there's no redirection in my page, the javascript check function, the form, and the JSP part that procces the form after submitting it are at the same page.
the jsp part is used to send the data from the form to a database.
the function:
function checkCorrect(){
var fullname=document.getElementById("fullname").value;
...
if (response.length==0)
{
return true;
}
else
{
alert ("These problems are found in your form:\n\n"+response);
return false;
}
}
then come the body and the form and then
the jsp part:
<%
if(request.getMethod().equals("POST")){
String fullname=request.getParameter("fullname");
and go on.. } % >
Solution:
check the JavaScript part really good people it doesn't have compiler so even a tiny problem there can screw up the entire project.
<% uname=""+request.getAttribute("username"); %>
This variable will get a value only when you load your page or refresh it.
I guess your page flow is as follows.
You have your first page with form, and onsubmit form will call javascript function as
<form name="users" method="post" onSubmit="returncheckCorrect()" action="Registeration.jsp">
then your javascript will check your answer like :
<script type="text/javascript">
function returncheckCorrect() {
var x = document.getElementsByName("userName")
if (your condition) {
alert("Redirecting");
return true;
} else {
alert("Not Redirecting");
return false;
}
}
// return false; // lol, see why indentation is useful ?
</script>
then (if (your condition == true)) your java script will redirect to a second page where you want to get the value in a scriptlet like
<% uname=""+request.getAttribute("username"); %>
Make sure your code is in this manner.
Following is the code which I tried as you said, its working
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">
function chkme() {
var x = document.getElementById('textfield');
if (x.value == 'sarin') {
alert("success");
} else {
alert("failed");
}
return true;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form id="form1" name="form1" method="post" onsubmit="chkme();"
action="">
<input type="text" name="textfield" id="textfield" /> <input
type="text" name="textfield2" id="textfield2" /> <input
type="submit" name="button" id="button" value="Submit" />
</form>
<%
if (request.getMethod().equals("POST")) {
String textfield = request.getParameter("textfield");
String textfield2 = request.getParameter("textfield2");
%>
<%=textfield%>
<br />
<%=textfield2%>
<%
}
%>
</body>
</html>
I have a registration form in ASP.NET 2.0. I want to save my registration form fields either by clicking on submit button or they should be saved every five seconds.
For example I have three fields in my registration page:
UID
PWD
Name
The user has entered UID and PWD and whilst he is entering Name the previous values should be saved without interruption of user inputs
How would I do this in ASP.NET?
You could do this with a snippet of Javascript & jQuery. Have a function that's fired by a timer that periodically reads the form data you want to save and posts it back to a SaveDraft.aspx page. In this page persists the data somewhere (such as a database).
If the user logs out or their session is lost you can query for this data and pre-populate the form if the data exists.
On your data entry ASPX page:
// Usual ASP.NET page directives go here
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js" ></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:textbox id="username" runat="server" /><br />
<asp:textbox id="password" runat="server" /><br />
<asp:textbox id="realName" runat="server" /><br />
<asp:button id="Submit" onclick="Submit_Click"
usesubmitbehavior="true" runat="server" />
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
// Configure to save every 5 seconds
window.setInterval(saveDraft, 5000);
});
// The magic happens here...
function saveDraft() {
$.ajax({
type: "POST",
url: "SaveDraft.aspx",
data: ({
username: $("#<%=username.ClientID %>").val(),
password: $("#<%=password.ClientID %>").val(),
realName: $("#<%=realName.ClientID %>").val()
}),
success: function (response) {
alert('saved draft');
}
});
}
</script>
</body>
</html>
In your SaveDraft.aspx page:
public partial class SaveDraft : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string username = Request.Form["username"];
string password = Request.Form["password"];
string realName = Request.Form["realName"];
// Save data somewhere at this point
}
}
That should get you started.