How to call a JSP page query? - java

I have two jsp pages. The first one with "Hello World" text message. The second JSP page with "Hello JSP" text message. Now in my third JSP page I have two buttons button1 and button 2. Can someone suggest some code snippet which I can use to call the first JSP page on click of the button 1 and **on click of button 2 , it should call the second JSP page?
On click of the first button only the first jsp page value should be displayed i.e Hello World and on click of the second button only second page value should be displayed i.e Hello JSP.
Kindly suggest the approach to achieve this.
Kind regards

Just put some javascript that sets the window location to the page you want to display as the script of the button
<input type="button"
value="Button 1"
onclick="window.location.assign('HelloWorld.jsp')">
<input type="button"
value="Button 2"
onclick="window.location.assign('HelloWorldJSP.jsp')">
Put the correct addresses in there for your JSP pages. This will cause the browser to reload from the address of the JSP page, and that JSP will 'fill the browser' with its contents.

JavaScript using AJAX
<script>
function loadXMLDoc(page)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",page,true);
xmlhttp.send();
}
</script>
Code For Buttons
<button type=button onclick='loadXMLDoc("page_one.jsp")'>Button 1</button>
<button type=button onclick='loadXMLDoc("page_two.jsp")'>Button 2</button>
And inside body
<div id="myDiv"></div>

It does not make a lot of sense to "call" a JSP page. Are you trying to submit a different set of information based on which button you click (I think so)? And if you submit different information, what do you want to do with the result?
The simplest thing - have two forms that get submitted to different URLs. Clicking on button 1 should submit it to the URL of first JSP, clicking on button 2 should submit it to the URL of the second JSP. Or these could be simple GET links. If the three JSPs, a.jsp, button1.jsp, and button2.jsp are in the same (and accessible through direct web URL) directory , a.jsp could be -
Click for Hello World
Click for Hello JSP
Content of button1.jsp and button2.jsp is trivial.
Keep in mind that in general, you should not be submitting directly to a JSP URL. May I also suggest that you spend some time reading up on how JSP, servlets and HTTP work in general and in conjunction with each other?

Always try your practices to forward via the servlets, and below is one of the implementation. Set both buttons as a submit type.
Use hidden textbox for storing the clicked id/name of button inside of the form.
$("#button1").click(function() {
var buttonId = $("#buttonId").val('button1');
return true;
});
$("#button2").click(function() {
var buttonId = $("#buttonId").val('button2');
return true;
});
Submit the form and get the value of buttonId in your servlet like this,
String clickedButton = request.getParameter("hidden_name");
finally forward the page to whatever you like this,
if(clickedButton.equals("button1")){
// do your stuff
}else if(clickedButton.equals("button2")){
// do your stuff
}

Related

Extracting and processing textarea value form without changing the page

I have a JSP file in which there are two textareas and a submit button all in a form ;
<form action="" method="post">
<textarea name="inConsole" id="in" cols="100" rows="10"> </textarea> <br/>
<input type="submit" name="Send Command"/> <br/>
<textarea name="outConsole" id="out" cols="100" rows="10"></textarea>
</form>
this page is supposed to work like any SQL program. so the user types a command in the first textarea and clicks submit, then the value of textarea will be extracted to a field and a method will take care of the command and return a log (1 row inserted, error:bad syntax etc) which will be displayed in the second textarea.
I know how for example make a login page and send data and redirect user to a new page(new jsp) file if user pass is correct.
what I can't find is how can I do all the things that I said above without going to a new page while using form action.
I have checked other questions that linked the action attribute to a servlet which was confusing for me( the way that a servlet was called). I'm looking forward to use a simple scriptlet for this purpose like the one I used for my login page:
<%
DatabaseLoginTest dbLogTest = new DatabaseLoginTest();
if (dbLogTest.DBLoginChecker(request.getParameter("user"), request.getParameter("pass")) == true){
%>
<p>Login Successful</p>
<% } else { %>
<p>Login Failed</p>
<% } %>
also I'm aware that adding java scripts(not Javascript scripts:) ) to html isn't a good practice(and the reasons for it) but I think this might be easier for a simple program that I'm working on.
p.s: I'm using tomcat and Intellij for developing this web application
and I have made a custom SQL so I only need the code that gives me the textarea value and the one that sets the other one's value
Update: now I know I should use javascript but I don't know how can I send the data extracted by javascript to a java method.
If you want to do this while remaining in the same page, you have to use Javascript. This is because if you want the server to be able to re-render the page, there has to be a page refresh.
You would need to write onClick handler for the submit button and make a Ajax call to your server to a specific URL with the user input. This URL would serve the data needed for the necessary UI changes.
You can use a scriptlet to generate the HTML that would be shown in the webpage but this would only suffice for a simple use-case and it would be a lot simpler if, say, your service returned just the data required to make the UI change and actual UI change is handled by the JS.
Also,I don't think it is a bad practice to embed JS in HTML. Sure, you can optimize this by including a JS source file but that's a separate optimization.

Servlet loads a new page

I have the following problem:
I have two servlets, one returns a navigation. There are categories and subcategories that the servlet gets through the DAO. I use the following script to get the servlets result on the right position:
$(document).ready(function() {
$('#navigation').load('Navigation');
$('#content').load('Content');
});
Below my navigation div, I have a content div. As you can see, i am loading the content-servlet. In my navigation; i have the following elements:
<li><a><form action='Content' method='get'><button type='submit'>"
+ k2.getKName() + "</button><input type='hidden' name='category' value='"+ k2.getKategorieNr() + "'/></form></a></li>
Now when I click on a subcategory, the button will call the content servlet. The problem is, that it loads a new page without the navigation. So I can only see the code that the servlet returns in a new page.
How can I get the result of the content servlet inside my previous page as it already works for my navigation servlet?
When you load your page initially, $("#navigation").load("Navigation") makes an AJAX request to your Navigation servlet and pastes the HTML response from the servlet back into an element like <div id="navigation">.
When you click your button in the form, you are making a top-level full page request to the same servlet, and the response content will replace the whole browser window, not paste it into the page like you are getting with jQuery load.
The easiest way to address this may be with the jQuery ajaxForm plugin:
http://malsup.com/jquery/form/
where you would do something in your ready callback like
$(document).ready(function() {
$('#navigation').load('Navigation');
$('#content').load('Content');
$('#formId').ajaxForm({target: '#content'});
});
Of course you need to add an ID to your form element so you can easily find it with jQuery.
See
jQuery ajax - change jQuery target value with form submit

access javascript variable value in jsp

I want to pass a javascript variable to my servlet, where I need to use it.
In javascript, the variable count returns the rows of my table and I can show count in the jsp, using $('#counter').html(count); , but I cannot pass count's value to my servlet. I tried document.getElementById("hiddenField").value=count; but it doesn't work.
Javascript
<script>
var count = 3;
$(function() {
$('#counter').html(count);
$('#addButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
});
$('#deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
});
});
document.getElementById("hiddenField").value=count; // ???
</script>
JSP
Count: <span id="counter"></span> <%-- it works --%>
<form method="post" action="newteamsubmit">
...
<input type="hidden" id="hiddenField" name ="countRows" />
<input type="submit" name ="button1" value=" Submit " />
<input type="submit" name = "button1" value=" Cancel " />
</form>
Servlet
String cr = request.getParameter("countRows"); //I' ve tried also to convert it
// to int, but that's not my problem, since I cannot pass the value as a start
I've spent many hours, trying to figure out how I can access a javascript variable in jsp, but I haven't found any solution.
Thanks in advance.
The count is computed each time the add button or the delete button are clicked. But you only set the hidden field value once, when the page is loaded (and its value is thus hard-coded to 3).
You must set it, as you're doing for the #counter element, in your click handlers:
$('#addButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
$('#deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
Also note that you're repeating exactly the same code in two click handlers here. You should do that only once, for the two buttons:
$('#addButton, #deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
or even, since you're using jQuery:
$('#addButton, #deleteButton').bind('click', function() {
count = $("#dataTable tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
document.getElementById('hiddenField').value is not set because it is outside your document.ready. Put it inside your click handler.
Make sure of 2 things -
There is only one element with id "hiddenField" on your page.
Make sure that the following code
document.getElementById("hiddenField").value=count;
is after in the page.
Just make sure that js sets the hiddenField after the element has been loaded.
3. check for any JS errors using Javascript console.
Rest it looks good
The main issue here is that you are trying to access from the server, a variable that only exists at the client. To access that variable you have to send it from the client to the server using AJAX to trigger some form of API in the backend. REST, SOAP or XML-RPC are common technologies used for this sort of thing. The server side code is used for generating the UI and providing it with data from a database or such. Commonly the UI is generated only once, and then the client calls the server asking for more data in response to user actions, like clicking a button.
Imagine a table filled with information about books: title, author, publish date etc. This table can get quite large, and traditionally this table will be split up over several pages and possibly a dynamic filter. To save bandwidth and increase the user experience by not loading the entire page from scratch you can use AJAX to ask the server for just the relevant data. Doing so the page updates dynamically and smoothly for the user.
In your case, you can use this technique to update the server every time the user clicks the button.
If however you are really just looking to update a hidden field in a form with a value as the user performs actions, and the server wont do anything with it except show it you can just use javascript.
Remember also that the request variable contains the data you post to the server when you submit the form. The servlet will get the data after the client has posted it, which is after the JSP has generated the page. The sequence of the code execution is JSP -> Javascript -> Servlet.
Hope this helps!
You can use this way:
document.forms[0].countRows.value = counter
Hope this will help you

How to call a Java method in a different part of a JSP page

Let's say I have an input button.
<input type="button" value="click here />
Then there's other HTML and Java codes.
.
.
.
.
.
Then there's a div tag.
<div>
</div>
and inside this div I want to execute these codes, but Only when I click on that button.
<% `int i = 0;
while(i<3) {
%> <div> I love you </div>
<% i++;} %>`
Java code is executed on the server. Events like clicks happen on the user's browser. So a click cannot call java code directly.
You need to:
either code the filling of the div in pure javascript,
or make an ajax call when the button is clicked, to retrieve the
content of the div from the server.
Probably Onclick event you can set the value of a hidden parameter and in div check for parameter value in script-let using if else but again java code will be executed on server and hence it will be new request to same Action otherwise use Ajax to populate data in div from sever.
you need to use ajax and servlet to acheive this.
servlet would send the code in response.
The success part of ajax would add the returned string to the div.
You would need to assign an id to div.
The ajax syntax would be
$.ajax({
url:"../servletname",
type:"POST",
data:{},
success:function(response){
$("#divid").html(response);
}
});
You need to call the servlet in the jsp using onClick function.

How to go from one JSP page to other by clicking submit button?

I want to jump from one JSP page to other JSP page by clicking submit button. How to do that in easy way?
use <form action="page2.jsp">
or submit to a servlet using <form action="targetServlet">, and then:
redirect to page2, using response.sendRedirect("page2.jsp")
or forward to page2, using request.getRequestDispatcher("page2.jsp").forward()

Categories