invoking java scriptlet in JSP using HTML - java

I am trying to find a way to invoke a piece of java code within the JSP using HTML form
<form method="get" action="invokeMe()">
<input type="submit" value="click to submit" />
</form>
<%
private void invokeMe(){
out.println("He invoked me. I am happy!");
}
%>
the above code is within the JSP. I want this run the scriptlet upon submit
I know the code looks very bad, but I just want to grasp the concept... and how to go about it.
thanks

You can use Ajax to submit form to servlet and evaluate java code, but stay on the same window.
<form method="get" action="invokeMe()" id="submit">
<input type="submit" value="click to submit" />
</form>
<script>
$(document).ready(function() {
$("#submit").submit(function(event) {
$.ajax({
type : "POST",
url : "your servlet here(for example: DeleteUser)",
data : "id=" + id,
success : function() {
alert("message");
}
});
$('#submit').submit(); // if you want to submit form
});
});
</script>

Sorry,not possible.
Jsp lies on server side and html plays on client side unless without making a request you cannot do this :)

you cannot write a java method in scriptlet. Because at compilation time code in scriptlet becomes part of service method. Hence method within a method is wrong.
How ever you can write java methods within init tag and can call from scriptlet like below code.
<form method="get" action="">
<input type="submit" value="click to submit" />
</form>
<%
invokeMe();
%>
<%!
private void invokeMe(){
out.println("He invoked me. I am happy!");
}
%>

Not possible.
When the form is submitted, it sends a request to the server. You have 2 options:
Have the server perform the desired action when the it receives the request sent by the form
or
Use Javascript to perform the desired action on the client:
<form name="frm1" action="submit" onsubmit="invokeMe()"
...
</form>
<script>
function invokeMe()
{
alert("He invoked me. I am happy!")
}
</script>

You can't do this since JSP rendering happens on server-side and client would never receive the Java code (ie. the invokeMe() function) in the returned HTML. It wouldn't know what to do with Java code at runtime, anyway!
What's more, <form> tag doesn't invoke functions, it sends an HTTP form to the URL specified in action attribute.

Related

Why is this simple jsp program is NOT running?

As we know every jsp program there is a servlet behind the jsp page. I have used a jsp page to make a form (its a very small form), and in the same jsp i used scriptlet tags and made a way to get the inserted form data, and display it using out.print(). but the problem is it when i run it, the form is displayed., but when i submit is, it doesn't recognize the servlet page (error coming as "The requested resource is not available"). i will put the code below., please help me friends to solve this problem. thank you.
i did this in netbeans.
jsp page name is- "hello.jsp"
the servlet page name behind the jsp page is: "hello_jsp.java".
<html>
<head><title>IF...ELSE Example</title></head>
<body>
<form action="hello_jsp" method="post">
<input type="text" name="y"/>
<input type="submit" value="submit"/>
<%
if(request.getParameter("y")!=null) {
String s = request.getParameter("y");
if(s.equals("hello")){
out.print("welcome"+s);
}else{
out.print("not welcome");
}}
%>
</form>
</body>
</html>
My guess is that you need to change
<form action="hello_jsp" method="post">
to
<form action="hello.jsp" method="post">
<!-- ^---- change is here -->
The externally-accesible resource is the jsp, not the servlet. (By default, I'm sure some config-fu could change that.)
Or, of course, if the page is supposed to submit to itself, don't include action at all. The default is to submit to the current page.
<form method="post">

How to manipulate a variable before sending to servlet

I've got a JSP page which contains a textbox, wrapped in a form. This form's action is set to a servlet.
I would like to manipulate the string (from the user's input in the textbox) before it is sent to the servlet, thus basically carrying out a simple request.setParameter call from the JSP to the servlet. Can this be done? If so how can I obtain the textbox's value in the JSP?
<form action="MyServlet" method="post">
<input type="text" name="txtUsername"/><br/>
<input type="submit" value="Submit"/>
</form>
You cannot do this using JSP code.
Remember, a JSP is processed, outputting its contents to the browser; that's where the JSP's request/response cycle ends.
Your options are:
Using JavaScript.
Using a Filter: http://docs.oracle.com/javaee/5/api/javax/servlet/Filter.html
Call a Javascript function on submit e.g. below:
function fnSubmit(){
document.getElementById("txtUsername").value = "new Value";
document.forms[0].submit();
}

Hide <s:param> from the url

In my jsp page, there is link as follows.
<s:url var="editReqDetails" action="editReqDetails">
<s:param name="siteID" value="siteId"/>
</s:url>
when I click on that link, browser URL is
http://localhost:7101/legal/editReqDetails?siteID=99
like above.(The parameter shows in the URL.)
I want to know how to hide above highlighted part(the parameter) from the url.
If you can use javascript you could do this
<s:a href="#" onclick="window.location.href='%{editReqDetails}'">Edit Details</s:a>
This way you "hide" the url from the user. Though I'm not sure what the big problem is. If the user is malicious he can easily look in the source and get the values.
No, you can't use this. You pass parameter with http GET method that is default used in s:url tag and you want to get http POST method behavior. See the usage of struts url and choose one http GET or POST method.
You can do this:
<form id="edit-form" action="editReqDetails" method="POST">
<input type="hidden" name="siteID" value="siteId" />
</form>
Then:
<script type="text/javascript">
$(document).ready(function() {
$("#your-link").click(function(e) {
$("#edit-form").submit();
});
});
</script>

how to handle response contents by AJAX

for me it seems impossible but expecting clarification on it. i am sending a request as follow :
<form action="/name" method="get">
<input type="text" />
<input type="submit" />
</form>
Now action class at server side manipulates & send the response to client, can i handle this response by ajax somehow ??
Yes, but you have to submit it via ajax (XmlHttpRequest) in order to be able to get the response that way.
Using jQuery makes this simple:
$.post("/name", {param:param}, function(data) {
});
In that example you should pass manually each form field as param. In case of bigger forms this is not that good. So you can use serialize():
$.post($("#yourForm").attr("action"),
$("#yourForm").serialize(),
responseHandlerFunction);

java spring and ftl

I defined a modelview object named "buttonpressed" in spring controller file and I need to access that modelview object in ftl(freemarker) file which is being returned as a view from a controller like abcd.java
The abcd.java controller code is as below
if (questionAnswer.getAnswerId() == 1045)
{
modelAndView.addObject("buttonPressed","You have been added in mailing list");
modelAndView.setViewName("enterCode_nextSteps");
}
else
{
modelAndView.addObject("buttonPressed","Not added in the mailing list");
modelAndView.setViewName("enterCode_nextSteps");
}
the below ajax function is working fine currently but I am not sure how to access this object called "buttonpressed" in this ajax function. I have written like the way mentioned below but when i am clicking the submit link its not calling "partner.do" and also throwing error saying #buttonPressed is undefind (but in the script below its working fine and calling "partner.do" and even posting data)
So is that problem coming from javsscript code i mean due to incorrect use of
"buttonPressed" or might be problem from spring controller abcd.java file.
<div class="partnerOptInBox">
<div id="optInContent">
<form name="partnerOptIn">
<h4>Want the Latest</h4>
<p class="pad10Top">${partnerOpt.translation}</p>
<div class="pad10Top">
<input type="radio" name="questionAnswer['${partnerOpt.questionId}']" value="${partnerOpt.getAnswers()[0].answerId}" class="radioButton" /> <label for="questionAnswer['${partnerOpt.questionId}']" class="formLabel pad20Right">Yes</label> <input type="radio" name="questionAnswer['${partnerOpt.questionId}']" class="radioButton" value="${partnerOpt.getAnswers()[1].answerId}" /> <label for="questionAnswer['${partnerOpt.questionId}']" class="formLabel">No</label>
</div>
<div id="optInError" class="formError" style="display:none;">Oops... your request did not go through, please try again.</div>
<div class="pad15Top">
<img src="images/theme/btn_opt_in_submit.gif"/>
</div>
</form>
<script type="text/javascript">
function submitOptIn() {
$('optInError').hide();
dataString = $('#partnerOptIn').serialize();
$.ajax({
data: dataString,
url: "partnerOpt.do",
timeout: 30000,
type: "POST",
success: function(html){
var newHtml = "<h4>Thank you</h4><p>We appreciate your time to respond to our request.</p>";
$('#optInContent').html(newHtml);
},
*/trying this code for sucess is throwing me an error /*
<!-- buttonpressed function-->
success: function(html){
$('#optInContent').html(${buttonPressed});
},
<!-- buttonpressed function-->
error: function(){
$('#optInError').show();
}
});
}
</script>
Assuming the HTML code shown is part of the view in which model from abcd.java is accessible, you need to enclose ${buttonPressed} in quotes when you're invoking $('#optInContent').html() on it because it's a string.
Or if it doesn't work then you can output as javascript variable on the top of the page
and read later using DOM,
var buttonpressed = ${buttonPressed}, but i think above solution will work. But generally this approach works best if you have lot of javascript work in a page and needs backend data
and you don't want to do AJAX calls.

Categories