I need to get the value that a user has entered in a textbox on a JSP. I used JavaScript to obtain the value, but then I need to access that same variable outside the JavaScript later on in the page.
Here's what I have:
<script type="text/javascript">
var sp;
function setPolicy(){
sp = document.getElementById('policy').value;
if(sp != "")
alert("You entered: " + sp)
else
alert("Would you please enter some text?")
}
</script>
the textbox:
input type="text" id='policy' size="15" tabindex = "1" onblur="setPolicy()"
But I need to access the string entered in this "policy" textbox later on in a scriplet to call a function within my session bean. Is there any way I can pass that variable outside the JavaScript? Or is there another way to do this?
Thanks!
JavaScript execution happens at client side and Scriptlet executes at server side. You are trying to combine the two.
You should submit the form to the same page by passing a param which will have the value entered in the textbox. Your scriptlet should check if the param is present or not. First time coming on this jsp the param will not be present, it will be available only when user enter something in textbox.
May not be the best solution as I don't know the whole context.
I'm not sure you have the lifecycle of a jsp down quite yet. By the time that the javascript is running, all the scriptlets have been evaluated.
By this I mean, one the JSP is rendered, html and javascript are emitted on the response to the browser, and there is no more server to interpret the JSP.
So, you should think of your problem as how do I communicate back to the server, the result of the user action?
Probably by posting a form to an action on the server.
If you are asking how to get hold of text input value in a java session bean, it has nothing to do with your javascript code.
The session bean is server side code. To pass the input value to your session bean, you need to change server side code, a servlet, strut action, webwork action depending on which web framework you use.
Related
I need to call small part of JSP page(like only div load) when a method is invoked? I know we can load whole JSP page from Servlet. Is this possible or any other solution for this?
know we can load whole JSP page from Servlet. Is this possible
Yes it is possible, you forward your request to jsp from servlet and it will render that jsp, here is an exact same example
1) Set some session or request variable equal to some value, say boolean myVar = true.
2) Redirect from your jsp page from your servlet.
3) In the jsp page, check for particular condition for the variable myVar. If condition is fulfilled, using scriptlets or JSTL display only the relevant part of you jsp.
You can use AJAX(Asynchronous Javascript and XML) for this purpose
For example, Suggestions, that appear without any refresh for auto-complete in google search, are using Ajax. JSP code will contain the Ajax code and will send the information to the servlet in form of XmlHttpRequest object and then takes the response from servlet as xmlhttp.responseText. The result can be written at JSP page by using DOM.
To initiate this process, you need to use the onkeyup in input tag like this:
<input type="text" onkeyup="methodName(this.value)"
Learn more about Ajax
To use AJAX with Java, try this
Ajax for Java Web Applications
$('#myDiv').load('serverPage.jsp #server_div_id');
OR
$.ajax({
url: 'serverPage.jsp',
success: function(data) {
data=$(data).find('div#id');
$('#mydiv').html(data);
}
});
I have two different divisions in a JSP page. One contains a menu of links, when clicked the div2 (id-content) loads different pages accordingly. I am doing something like -
<div id="menu">
<ul class="navbar">
<li><a name="login" href="Login.jsp" onclick="changeContent()">Login</a>
</li></div>
and in the script I have something as -
<script language="JavaScript">
function changeContent() {
document.getElementById('content').load('Login.jsp');
}
</script>
I also tried -
document.getElementById('content').innerHTML=
"<jsp:include page="Login.jsp">";
None of the ways worked. Please suggest how should I
Try jquery..
function changeContent() {
$('#content').load('Login.jsp');
}
The solution is to use Ajax, which will asynchronously retrieve your page content that can be pasted in with the innerHTML method. See my answer to a similar question of how an Ajax call works and some introductory links.
As to why your examples in your answer don't work, in the first case there is no load() method on an Element object (unless you've defined one yourself and not shown it). In the second example, as one of the question comments says, there is probably something causing a syntax error in the javascript.
As an FYI, when there is a syntax error in some javascript in a web page, the current expression being parsed and the rest of the <script></script> block will be ignored. Since this is inside a function declaration, that function will never get defined.
For instance, an embedded quote in the included page will end the string for the innerHTML assignment. Then the javascript parser will try to parse the remainder of the HTML causing a syntax error as the HTML will not be valid javascript.
We use jquery. Add a click event handler to the anchor elements. In the click handler call $('#content').load(your_url);. You might want to use the load(url, function() { ...}) version. More info here http://api.jquery.com/load/
Your initial page comes down from the server. It's displayed by the browser. When you click on a link (or a button) in the browser, you want to fill the second div with new HTML. This is is a perfect job for an AJAX request. What the AJAX object in the browser does, is to send a POST (or whatever) string to the server. And then the Ajax object receives the HTML response back from the server. And then you can display that response data which the AJAX object contains, anywhere you want.
In my JSP page I have DIV.
<div id="100">
ALI
</div>
When I click on this DIV...
$("#100").click(function(){
});
...I need to send the value of the id 100, to a servlet, so that the servlet makes some database java codes, and returns for example, either 1 or 0. How can I do that? and is this the proper way?
Using Ajax, you should call your server using a URL similar to this:
http://localhot:8080/youAppContext/yourServer?id=100
Then, in the servler side, you should retrieve the value that will be in the request with the name "id"
There are out there many tool as jQuery that can help you to do the Ajax petition.
Edited
Well, here you can find a very simple Ajax example using jQuery. In the example, instead call a file (test1.txt) you should invoke a URL (as I described above). Of course, you will need to write some JS code to build your URL (where id be a variable). Once task is done in servlet side, you can return whatever, for example: "done" and display or not this information the HTML as it is done in the example.
Take a look to this Web, there are many links that can help you.
get the value using
var value = $("#100").html();
and pass it to servlet using AJAX
I am working in a web application using struts. I am performing some operations in struts action class and using session.setAttribute i am setting result value. My struts action class sends result to jsp page where i am displaying result. I have to display message after loading jsp page, hence i am trying to use jquery. But i am not getting how to handle http sesion request in jquery.
Earlier i was taking one property in sturts-config.xml and setting the value instead of sending http session request parameter. But it doesn't work for me, because every time when i refresh my page it takes initial value from struts-config.xml. i am taking struts property as hidden field in jsp page by writing:
<html:hidden property="propname" styleId="id_propname" name="formname" />
for setting property value null I am writing following code in jquery.
<script type="text/javascript">
$(document).ready(function()
{
alert("some text");
$("#id_propname").val("");
});
</script>
Is there any way where i can directly get the http session request in jquery ? please reply me if you can give some suggestions I thanks to all valuable suggestions in advance.
IMHO there is no simple way to pass your session to the jquery . What you can do is to set the value of some hidden field and declare a global variable on the script and access the value and check for the valid condition if any .
Although its ugly and highly discouraged to use scriptlet inside jsp , this might work :-
<% String sessionVal = session.getAttribute("yourSessionValue").toString() %>
<html type="hidden" id="id_propname" name="propname" value=<%=sessionVal> >
In your jquery :
<script type="text/javascript">
var sessionVal;
$(document).ready(function()
{
sessionVal = $("#id_propname").val();
alert("this is the session value at Script " + sessionVal );
});
</script>
Null check for session is not done.
Or
If you are using tag libraries you can set the session value on form bean and use something like this in jsp :-
<logic:equal name="yourFormBean" property="yourProperty" value="someDefinedValue">
Do your action here
</logic:equal> <br />
Well http Sessions and Requests, in the form of java Objects and related to servlets, live in the server side. JQuery on the other hand will "normally" live in the client side... therefore your problem description is a bit "off".
The parameters you "send" in the httpsession or/and in the httprequest are for the jsp generation where jQuery does not play any part. What then gets sent to the browser is the HTML generated by the jsp engine. This HTML when in the browser can then be used by jQuery.
By the way the framework name is Struts and not Sturts.
Taking in account this information I don't really understand what in fact you want to do.
Is it possible to use request.setAttribute on a JSP page and then on HTML Submit get the same request attribute in the Servlet?
No. Unfortunately the Request object is only available until the page finishes loading - once it's complete, you'll lose all values in it unless they've been stored somewhere.
If you want to persist attributes through requests you need to either:
Have a hidden input in your form, such as <input type="hidden" name="myhiddenvalue" value="<%= request.getParameter("value") %>" />. This will then be available in the servlet as a request parameter.
Put it in the session (see request.getSession() - in a JSP this is available as simply session)
I recommend using the Session as it's easier to manage.
The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which really need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a collection or when users return to a page they previously visited only to find they have values still remaining from a previous visit. A smart program minimizes the scope of variables as much as possible, a bad one uses session too much.
You can do it using pageContext attributes, though:
In the JSP:
<form action="Enter.do">
<button type="SUBMIT" id="btnSubmit" name="btnSubmit">SUBMIT</button>
</form>
<% String s="opportunity";
pageContext.setAttribute("opp", s, PageContext.APPLICATION_SCOPE); %>
In the Servlet (linked to the "Enter.do" url-pattern):
String s=(String) request.getServletContext().getAttribute("opp");
There are other scopes besides APPLICATION_SCOPE like SESSION_SCOPE. APPLICATION_SCOPE is used for ServletContext attributes.
If you want your requests to persists try this:
example: on your JSP or servlet page
request.getSession().setAttribute("SUBFAMILY", subFam);
and on any receiving page use the below lines to retrieve your session and data:
SubFamily subFam = (SubFamily)request.getSession().getAttribute("SUBFAMILY");
Try
request.getSession().setAttribute("SUBFAMILY", subFam);
request.getSession().getAttribute("SUBFAMILY");
Correct me if wrong...I think request does persist between consecutive pages..
Think you traverse from page 1--> page 2-->page 3.
You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".
I mean something like this in page 2 fails:
Where as the same thing has worked in case of page 1 like:
So I think I would need to proceed with either of the two options suggested by Phill.
i think phil is right request option is available till the page load. so if we want to sent value to another page we want to set the in the hidden tag or in side the session if you just need the value only on another page and not more than that then hidden tags are best option if you need that value on more than one page at that time session is the better option than hidden tags.