Addition in jsp - java

I am trying to add some java variables in html using jsp.
html
.... name="Editbox1" value="<%=a %>" spellcheck="false">
I have 7 boxes. From a to g.
At the end of the code, i have a button that should add these, but it wont.
input type="submit" id="Button1" onclick="<% sum = a+b+c+d+e+f+g; %> "
when this buton does its thing, the answer should be seen in the editbox number 8.

You're mixing things that cannot mix - JSP code runs on the server (it is basically a servlet), while html/js code runs on the client (browser).
When the JSP file is processed on the server, all <% ... %> tags are replaced by their evaluated results, and in the end only the html/js is returned to the client.
For this reason, if you take a look at the source code in your browser, you'll see the onclick handler is defined with an empty string - the JSP code evaluates to nothing.
If you want to summarize values on button click, you'll either have to do it in JavaScript, or send a new request to the server to get the result.

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.

How can i use Javascript variable as argument in java code in JSP? [duplicate]

This question already has answers here:
Assign JavaScript variable to Java Variable in JSP
(7 answers)
Closed 8 years ago.
I want to send code title and price as an argument to the book object but gives illegal start expression error.
function addrecord() {
code = document.getElementById('code').value;
title = document.getElementById('title').value;
price = parseFloat(document.getElementById('price').value);
<% Book book = new Book(%> code <% ,%> title <% , %> price <% );
bookdb.addRecord(book);
%>
document.getElementById("code").value = "";
document.getElementById("title").value = "";
document.getElementById("price").value = "";
}
You are misunderstanding where java and javascript run.
You use <% and %> as if that sends values to the server, which it does not. those tags are used only inside the jsp to start snippets of java code. This only works while you are generating the page. Once your html is at your browser, these tags will not do anything.
Highlighting important keywords, this is not intended as sarcarsm
When you request a jsp page with your browser, the browser opens a network connection to the server. Think of these 2 (browser, server) as living in 2 completely different places.
The server then runs the java code. When it executes, it generates an html page.
This html page is sent back across the network connection to the client (your browser)
Your browser will receive this fully formed html page and use it to create it's view. On this page you can run javascript but the javascript will only run on the client (browser)
To get any variable back to the server again, you will need to either: get or post a form (using a submit inside a form tage, or use JavaScript post request like a form submit) , do an ajax call (http://www.javascriptkit.com/dhtmltutors/ajaxgetpost.shtml) or have the user click a link (a href="...your page").
The easiest way is to do:
<form method="POST" action="your/page/url">
<input type="hidden" name="someName" value="someValue" />
<input type="submit" />
</form>
read some of the links and make sure you keep in mind, your browser and the server are separated, so running javascript in your browser will not reach the server.
See here: Assign JavaScript variable to Java Variable in JSP
As that states, it's really not possible as the JSP executes on the server, and the javascript executes later in the browser.

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

JSP page with dynamic html

I've been trying to write a website in which all navigation is handled by hiding and showing divs. It is my understanding that this method is called Single Page Interface. This has worked for simple designs in the past but my current task is starting to become very troublesome using this method. How would I go about replicating the same behavior but instead of hiding and showing divs I can just have a main container div that is then populated with the desired html from the server?
Example:
<script>
$("#button").onclick(function() {
$("#a").show();
$("#b").hide();
});
</script>
<html>
<body>
<div id="a" style="display:none;">A: SOME HTML</div>
<div id="b" style="display:block;">B: SOME HTML</div>
<button id="button">Change to A</button>
</body>
</html>
(note this is a very rough example of white I'm trying to do)
But I would like the contents of a container div to change from "B" to "A" via some jsp
Could anybody point in the correct direction?
Further Explanation:
Maybe I can clarify a little better. So when the user loads the page they are presented with a section that has a table of all the existing files in a database. The user can select a file from the DB list to rename or copy. If the user wishes to rename a file, for example, they would be presented with a new display (all within the same "Tab") which will have a set of fields populated for the file that they have selected and a set of empty fields in which they can specify the new file name. Currently this changing of displays is handled by showing and hiding divs, but I would like to retrieve the html that I want to display from the server and present it. Basically mimicking the hiding and showing of divs.
As it's not completely clear to me what you're trying to do I'll give you some options:
Replace the content of a element on your page see
Since you're using a JSP, you can use server side logic to display certain fragments
You're using a JSP, use that to render some server side content
Ad 1:
(assuming jQuery) $('body').load('serverSide.html'); see http://api.jquery.com/load/
Ad 2:
<% if ("a".equals(request.getParameter("aOrB"))) { %>
<jsp:include page="/a.jspf">
<% } else { %>
<jsp:include page="/b.jspf">
<% } %}
Ad 3:
<%= request.getAttribute('content') %>
Hope that helps

c:out value behavior

I am relatively new to working with JSPs and I have a feeling I'm overlooking something simple. I have a segment that appends a key onto a URL before sending the user back to where they came from. The key is a string value and when it consists of only numberic values(for example 12345) it works fine, but when it contains non-numerics(for example abcde) it simply appends "#" to the url and stays on the same page.
<core:when test="${dataTransferObject.someBoolean}">
Back to Home
</core:when>
When it's a string the JavaScript will be illegal–it will think you're trying to reference a non-existent JavaScript variable. You will see an error your JavaScript console.
Don't do any JavaScript operations; JSP is evaluated on the server side before the client sees it:
onclick="javascript:location='path/back/to/their/home.request?cachekey=<core:out value="${dataTransferObject.stringVariable}"/>';return false;"
Better yet, use JSP EL:
onclick="javascript:location='path/back/to/their/home.request?cachekey=${dataTransferObject.stringVariable}';return false;"
Also, if this is the JSTL core tag library, the canonical prefix is "c".

Categories