Accepting http session request parameter in jsp page using jquery - java

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.

Related

Grails get url of originating controller

I have a URL say abc.com/somecontroller?someparam=1 which renders a form. Form on submit sends the form params to /ajaxAction
Is there a way I could get this abc.com/somecontroller?someparam=1 (i.e. the form URL?)
I am more interested in getting the someparam value from the URL of the form.
PS: the above URL abc.com/somecontroller?someparam=1 is dynamically generated, so I can not access it otherwise.
And request.forwardURI will give me /ajaxAction (i.e. the URL of the action in form and not the url of the form itself).
EDIT:
I have no control over form as it is also dynamic and user has hundreds of templates to select from. Each template has different no. of fields.
So if I would prefer some other way to get the URL.
Why don't you use javascript in form and add to ajax request array with GET params? (or with the url of the action which generated form)
You can get them from original request f.e. by this script.
While rendering the GSP of your form, you can do like this:
myaction.gsp
<html>
<body>
<!-- Your content -->
<script>
var paramsString = '${params.collect { k, v-> "$k=$v" }.join​​​​​​​​​​​​​​​​​​​​​​("&")​​​ }';
</script>
</body>
</html>
So, when you GSP is rendered, the script tag will have something like this (for a URL abc.com/somecontroller?someparam=1&foo=2:
var paramsString = 'someparam=1&foo=2';
Now, in your AJAX code, you can pass that string as the query arguments:
$.ajax({
url: '/ajaxAction?' + paramsString
/* rest of the AJAX code */
});
Now, in your ajax controller action, you can simply do the params.someparam.
EDIT
Well, I just realized that you don't have to any GSP stuff I mentioned above. Simply do the AJAX call like this:
$.ajax({
url: '/ajaxAction' + location.search
/* rest of the AJAX code */
});
The location.search will give you the direct string: ?someparam=1&foo=2
I ended up using flash to store the someparam
In my controller which is being used to render the form at abc.com/somecontroller?someparam=1 I use flash as this:
flash.put("someparam", params.someparam)
This worked as a quick workaround to the issue. I feel this would work well in situations where I have no control over the gsp.
If anyone finds any issue, please comment otherwise I will mark this as the answer.

Calling part of jsp page from Servlet or Java Class

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);
}
});

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>

Using request.setAttribute in a JSP page

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.

Get user input from textbox on JSP

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.

Categories

Resources