Generating multiple events in JSP page having more than one button - java

I am a beginner in the JSP World as per I have noticed that, there is one form tag which has action and method attribute. In action tag we must write the URL of the servlet which gets activated after clicking the submit button.
But my problem start here. I am trying to develop a register page.
I have two servlets:
one checks for the availability of existing user,
second register the user.
Does anyone have any idea how to achieve it without a href link or image button?

Move the code that checks for availability of the existing user and register the user to its own service class say UserService. Make the form submit to 2nd servlet which uses UserService to perform both the operations.
You can have two separate forms but not nested forms in HTML. If you want a single form to change its actions (its target URL) depending on which submit is used, the only way you can achieve that is through javascript.

You can do this with your existing approach by registering a Javascript function
<body>
<script type="text/javascript">
function submitType(submitType)
{
if(submitType==0)
document.userForm.action="CheckUserAvailability.do";
else
document.userForm.action="RegisterUser.do";
}
</script>
<form name="userForm" method="post">
--Other elements here
<input type="submit" value="Check User Availabiliy" onClick="submitType(0)"/>
<input type="submit" value="Check User Availabiliy" onClick="submitType(1)"/>
</form>
</body>

Yes You can.. In the action you give the Servlet name. and inside that servlet you can call java methods which are written in other classes.
Which means you can check
1.one checks for the availability of existing user
2.second register the user
Using two java classes(may be according to your choice)
Just call those methods with in the same servlet..Guess you got an idea.

Related

Stripe Checkout Charge using JSF: Form being submitted twice

The form is being submitted twice:
1. On Page Load
2. When user clicks on Checkout's button
I want to avoid the first submission, it is throwing an error because the token returned is null:
com.stripe.exception.InvalidRequestException: Invalid source object: must be a dictionary or a non-empty string. See API docs at https://stripe.com/docs'; request-id: req_DjRbT4rGULYGnB
Following the documentation I added the following code to my XHTML:
<div>
<form submit="#{studentBean.chargeStudent()}" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_xxxxxx"
data-amount="111"
data-name="myApp"
data-description="Example charge"
data-zip-code="true"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto">
</script>
</form>
</div>
Here is my Managed Bean's function:
#Named
#ViewScoped
public class StudentBean implements Serializable {
#EJB
StripeChargeLogic stripeChargeLogic;
public void chargeStudent(){
Map<String,String> requestParams = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
logger.info("charge:" + requestParams.get("stripeToken"));
stripeChargeLogic.chargeStudent(requestParams.get("stripeToken"));
}
}
Can someone please guide me why the form is being submitted twice and how I can prevent the submission during page load Thank you!
You are not doing jsf here, you have plain html, most likely (but mot clear from you post) in an xhtml/facelets file but not JSF.
In your form action you have an EL that, since it all is in no way related to jsf, is called on page load, sort of like what hapens here
The rest of the behaviour is even more 'undefined' because of this. Take a step back and learn the basics of web technology and jsf and then look at your problem again

How to cause a "back button' from a java servlet?

I have a form on page A. It submits some data to a java servlet on servlet B. Servlet B does some error checking. If that checking shows errors I'd like to send the user back to page A via a back button type action (which keeps the data in the form). Is there a way to do this in a Java servlet response? In case it matters, this is in Google AppEngine's Java platform.
No, you can't do that. What you can do though, is send back the HTML markup of the page containing the form, and prepopulate the form with the values submitted by the user:
<input type="text" value="hello" />
displays a text field populated with hello.
Basically all the MVC frameworks allow doing that quite easily.
Use RequestDispacter object and navigate it to first servlet or jsp page with that error

hide passed parameter from jsp to struts2 action class

<s:url action="someAction" var="act">
<s:param name="param1">value1</s:param>
</s:url>
<s:a href="%{act}">Go Action</s:a>
By clicking Go Action link, the address will be www.example.com/someAction?param1=value1
I want to hide passed parameters (param1=value1) like method="POST" in submitting of form. Is there anyway I can do it? Thanks.
No a URL is a GET request. If you want to POST you can do a post request with a form. If you want a button or link to do a post request, best to use JS/jQuery to hide the form and tie the buttons/links click event to submitting the form.
Struts2 has no control over the client side, there it's just HTML, CSS and JS.
As mentioned by JB Nizet, if it is about securing your information see the discussion here: How to send password securely over HTTP?
There is little issue sending most data in a get request (other than a password!) because if it is a form someone can readily see the content of the form, where seeing the parameters in the url is certainly harder.
From a server security stand point you should always assume the client can and will be able to send the worst possible data. That is why the validation framework in struts2 is so easy to use, and unlike primitive web programming systems, type conversion is a huge help. If you have a property that is an int and use that in a query you know it will be an int and not a String. If you need a String better use an Enum to ensure the value is allowed.
To hide passed parameter actually you need to submit the form. You should prevent the default behavior of the click event and replace it with the form event. Do it like in this example
<s:form id="f1" action="someAction">
<s:hidden name="param1" value="value1"/>
<s:url action="someAction" var="act"/>
<s:a id="a1" href="%{act}">Go Action</s:a>
<script type="text/javascript">
$(document).ready(function() {
$("#a1").click(function(event) {
event.preventDefault();
$("#f1").submit();
});
});
</script>
</s:form>

Struts 2: Sending values of form fields from jsp to action class

I know it must be simple, but still I am not able to figure it out.
I have a link on a jsp page.
When this link is clicked I want another tab (of browser) to open up.
The view of this new page is defined by action class, which needs a form field value.
The problem I am facing is that I can not get the values of form fields to the action class without submitting the form. And submitting the form changes the view of the original jsp as well, which defeats the whole purpose of opening a new tab.
So I need a way to get the form field values to action class without resetting the view of original jsp page.
One way I came across was URL re-writing but that would be my last option.
Please suggest something!!
Thanks!!
Firstly I would like to point out that currently possible (to my knowledge anyway) to force a new tab to appear, it is dependent on the users' browser and the settings that they have see here for more infomation.
Now onto your question, since links cannot send form data (on their own) you have 2 options:
You can use a form "submit" button pointing to the URL you want to send the data to and to and add the target="_blank" to the form which will cause a new page to open up when the form is submitted.
You can add a javascript event to your link so that when it is pressed you append the value of the input to the URL and open a new window with that URL.
Personally I would choose the first option.
Here is a simple example of option one which doesn't remove the input value when you submit...
<html>
<body>
<form action="test1.html" method="post" target="_blank">
<input type="text" name="bob" />
<input type="submit" value="Hello"/>
</form>
</body>
</html>
You could do an ajax call, or dynamically build the link url with get parameters in it.

Use Servlets to display the data on same webpage?

I am using a html form like this:
<form action="question" method="get">
where question is a java servlet class which renders the data from the form and display on other page.
What I am trying to do is display this data just below the html form not on other screen.
(Somewhat like the page where we Ask Question in stackoverflow.com where the question you enter is rendered and displayed below.)
So I am trying to do same. Anyone has an idea how to do that?
The simplest way to do it, is to use javascript (client side).
Below is a very crude example on how to do this. This will give you an idea on how to proceed.
create a html page, with two separate text area boxes.
Let the first text area box be the source where you type in the text.
Assign it an id 'source_area'.
<textarea id='source_area'>
</textarea>
Let the second text area box be the destination.
Assign it an id 'destination_area'.
Set this area as "readonly" because you don't want users typing here directly.
<textarea id='destination_area' readonly>
</textarea>
Now when a user types into the first box, we need to capture the particular action.
For this example I will use the "onKeyUp" to capture events when a keyboard key is released.
Now when typing into the source text box, a key on your keyboard is released, it will invoke a javascript function "transferToNextArea()" is invoked.
We will create the javascript function "transferToNextArea()" in
Read more about javascripts here. http://w3schools.com/js/js_events.asp
Complete list of events here. http://w3schools.com/jsref/dom_obj_event.asp
The javascript function will extract text from 'source_area' text box.
It will then assign the same text into 'destination_area'.
function transferToNextArea()
{
//extracting text.
var varSrcText = document.getElementById("source_area").value;
//assigning text to destination.
document.getElementById("destination_area").value=varSrcText
}
Complete html (tested in Google Chrome)
<html>
<body >
Source Box
<textarea id='source_area' onKeyUp="transferToNextArea();">
</textarea>
<br>
Destination Box
<textarea id='destination_area' readonly>
</textarea>
</body>
<script type="text/javascript">
function transferToNextArea()
{
var varSrcText = document.getElementById("source_area").value;
document.getElementById("destination_area").value=varSrcText
}
</script>
</html>
This is just a very basic example. It is not very effecient, but it will give you an idea of how data can be moved around.
Before assigning the text, you could manipulate the text however you want it using javascript.
Stackoverflow formats the text as per the html tags after extracting it. This will require lot more code and more work.
Using a servlet for the above task is overkill.
You would use a servlet, only if you want to do something with the data on the server side.
Example
a) store it in a database before displaying it below.
Read about "ajax" calls to send and recieve data between the server and client.
Ajax will give you the means to send data to the servlet without having to refresh the whole page.
Create a JSP with a form
on submit post the data to some servlet
process request and produce resultant data and set it to request's attribute
forward the request to same jsp
check if the data is not null display under the form
Just let the servlet forward the request to the same JSP page and use JSTL <c:if> to conditionally display the results.
request.setAttribute("questions", questions);
request.getRequestDispatcher("/WEB-INF/questions.jsp").forward(request, response);
with
<c:if test="${not empty questions}">
<h2>There are ${fn:length(questions)} questions.</h2>
<c:forEach items="${questions}" var="question">
<div class="question">${question}</div>
</c:forEach>
</c:if>
See also:
Our servlets wiki page - Contains concrete Hello World examples.

Categories

Resources