I get list on my jsp using
<%List selectedArray = (List) session.getAttribute("clist");%>
is [4,5].And I am sending this list to javascript using hidden variable in jsp
<input type='hidden' id="agencycontactid" name="agencycontactid" value="<%=selectedArray%>" />
and i am taking this in javascript var abc=$('#agencycontactid').val(); .
I want to send this abc to servlet using ajax call that is through data.And i want this list in simple array format in servlet.
Please help me.
Thanks
If you wanna pass an actual array (ie. an indexed array) then you can do:
$.post('/url', {'someKeyName': ['value','value']});
You can also build a param string by looping other the data (in my case a multi-select)
$(".choosenItems option").each(function() {
chosenStr = chosenStr + "&chItems=" + $(this).val();
});
so if you create a queryString of
...?name=Fred&name=Joe&name=Sally
then in your servlet you can do
String names[] = request.getParameterValues ("name");
Related
I'm doing a project using jsp pages and servlets.
In my servlet I need to identify which jsp page is doing the request.
How can I do this?
The simplest way to identify the form from which the request come from would be to add a hidden field containing a form identifier. But this is a very uncommon requirement: if you post to same URL, it normally means that the origine of the post does not matter. If it matters (why?), the difference should be in posted data (hence the proposal of a hidden field), or you should post to different URLs. Servlet are not so expensive that you need to limit their number.
I have found a solution.
I set a name to the submit button.
<input type="submit" name="button" value="button1">
and then in the servlet I check with
String r = request.getParameter("button");
Doing that I know from where the request came from
For your servlet, i suppose you are using doGet/doPost to handle request and return response, then in your request from jsp, you can always add a hidden input field to let your servlet know which jsp you come from as follow:
In your jsp:
add a new hidden input textfield:
<input type="hidden" name="jspname" value="jspname" />
In your Servlet:
use getparameter method for doPost or getQueryString() for doGet:
in doPost:
String jspname = request.getParameter("jspname");
By making use of the jspname String, you can easily find out which jsp it is using.
Using hidden input is solution in other answers. But you can do that without hidden input.
String referer = new URI(request.getHeader("referer")).getPath();
referer String gives you full URI. Additionally for getting jsp page name you can use java code.
String[] uriNames = referer.split("/");
String jspPageName = uriNames[uriNames.length-1];
Also with regex you can get jsp page name.
Pattern pattern = Pattern.compile("(\\w+)(\\.)(jsp)");
Matcher matcher = pattern.matcher(mydata);
String jspPageName = "";
while(matcher.find()) {
jspPageName = matcher.group();
}
Following is a form in a resultSet loop. So, there might be multiple forms according to range of results.
/* RESULT SET LOOP STARTED with `i` as iterator running from 1 to 5 */
<form action='Jaga' method='post' >
<input name='input-<%=i%>' />
</form>
/* RESULT SET LOOP ENDED */
So, on form-submission, Jaga Servlet receives information. How do i get to know which 'input-iterator' combination was used from which form.
request.getParameter('here');
What do i fill in-place of 'here' in Jaga Servlet to get correct input box value from correct form?
If you take a look at
https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String)
You can see that it returns a String or null if parameter doesn't exist, so you can simply make a for loop and check for the first not null return . Something like:
for(int i=1;i<=5;i++)
if(request.getParameter("input-"+i)!=null)
// handle stuff
EDIT: For getting the parameter names, try:
PrintWriter out = response.getWriter();
Enumeration<String> parameter = request.getParameterNames();
while(parameter.hasMoreElements())
out.println(parameter.nextElement());
I have an ArrayList of a class Room. I need to send it from a jsp to a servlet.
It seems the only way an html or a jsp can send values to a servlet is via a form, the method I tried was to pass it as a hidden parameter as follows:
<input type="hidden" name="allRooms" value="<%=request.getAttribute("allRooms") %>" />
But in the servlet to which i submit this form I get a compile error "String cannot be converted to List" for the following:
List<Room> allRooms=(List<Room>)request.getParameter("allRooms");
Just converting the parameter to an Object type first and then converting it to a List as shown below gives the same exception but this time as a Runtime Exception:
Object a=(Object)request.getParameter("allRooms");
List<Room> allRooms=(List<Room>)a;
Is there any method to pass the List to the servlet or I will have to set it as a session variable in the JSP ?
Thanks in advance.
Is there any method to pass the List to the servlet or I will have to set it as a session variable in the JSP ?
Use session.That is one best solution.
There is no way to represent an ArrayList in HTML to send via html form. Use session instead.
I think if you pass the following params, and array is formed in servlet side
param[0]=ss , param[1]=ssw
You could do this.
List<String> roomParams =(List<String>)request.getParameter("param");
But to make this.
List<Room> allRooms=(List<Room>)request.getParameter("allRooms");
That I think is not possible, so you should use Session attributes
session.setAttribute("allRooms", new ArrayList<Room>());
I believe you should not be sending the List to Servlet directly and should look out for other options.
How are you generating the ArrayList on the browser page? If it is generated from a multi-select element from UI, then you can access the request parameter values as Array in Servlet.
Shishir
I want to access a model attribute in Javascript. I use the following code:
model.addAttribute("data", responseDTO);
My DTO class:
public class ResponseDTO {
private List<ObjectError> errors;
private Boolean actionPassed;
private String dataRequestName;
// and setter getter for all fields
}
I tried accessing the DTO using:
var data = "${data}";
But it is giving me a string representation of responseDTO instead, i.e com.req.dto.ResponseDTO#115f4ea. I can successfully access a field inside the DTO using:
var data = "${data.actionPassed}";
But this is not working for the errors attribute inside the DTO, as it is a List of ObjectError. How can I get complete responseDTO object in Javascript?
Thanks!
EDIT :
Initially I was using jquery.post
$.post('ajax/test.html', function(data) {
// Here I was able to retrieve every attribute even list of ObjectError.
});
Now I want to remove Ajax and want to convert it into non-ajax approach (because of some unavoidable reasons). So I am doing a normal form submit and want load same form again and trying to load data model attribute in Javascript so that I can keep the rest of the code as it is.
I was wondering if it can be achieved in Javascript as it is doable using Jquery post?
EDIT 2 :
I tried (Thank you #Grant for suggestions)
JSONObject jsonObject =JSONObject.fromObject(responseDTO);
String jsonString = jsonObject.toString();
model.addAttribute("data",jsonString);
and in Javascript
var data = eval('('+ ${dataJson} +')'); // Getting error on this line
alert(data.actionPassed);
But getting error and no alert is displayed
Error :
First of all, there's no way to convert a Java object to a Javascript object directly since they have nothing to do with each other. One is server-side language and the other is client-side language.
So to accomplish this goal, you have to do some convertion. I think you have two options:
Convert ResponseDTO object to JSON string and pass it to jsp and you may get the javascript object directly.
Pass ResponseDTO object to JSP and populate the javascript object as what you are trying now.
For option #1, you should use a library to generate JSON string by the Java object. You can use this one JSON-lib.
e.g:
JSONObject jsonObject = JSONObject.fromObject( responseDTO );
/*
jsonStr is something like below, "errors" represents the List<ObjectError>
I don't know what's in ObjectError, errorName is just an example property.
{
"dataRequestName":"request1",
"actionPassed":true,
"errors":[{"errorName":"error"},{"errorName":"unknown error"}]
}
*/
String jsonStr = jsonObject.toString();
model.addAttribute("dataJson", jsonStr);
/*In JSP, get the corresponding javascript object
by eval the json string directly.*/
<script>
var data = eval('('+'${dataJson}'+')');
</script>
For option #2,
//Pass java object as you do now
model.addAttribute("data",responseDTO);
//In JSP, include jstl taglib to help accessing List.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<script>
var errorArr = [], errorObj;
<c:forEach var="error" items="${data.errors}">
errorObj = { errorName: '${error.errorName}' };
errorArr.push(errorObj);
</c:forEach>
//Populate the corresponding javascript object.
var data = {
dataRequestName: '${data.dataRequestName}',
actionPassed: ${data.actionPassed},
errors: errorArr
};
</script>
As you can see, option #2 is complicated and only useful if the Java object is simple while option #1 is much easier and maintainable.
So I just implemented a similar solution to Grant's first option with a List of objects, but used the Gson library to convert the object to a JSON string, then used JSON.parse() to turn it into a javascript object:
On the server:
List<CustomObject> foo = database.getCustomObjects();
model.addAttribute("foo", new Gson().toJson(foo));
In the page javascript:
var customObjectList = JSON.parse('${foo}');
console.log(customObjectList);
Notice that when I reference the model object foo, that I do so as a string '${foo}'. I believe you are getting your error because you reference it outside of a string. So the correct code would be:
var data = eval('('+ '${dataJson}' +')');
its very simple
in your spring controller
model.addAttribute("attributeName", "attributeValue");
in the script
<script type="text/javascript">
$(window).on('load', function () {
var springAttribute= '${attributeName}';
alert(springAttribute);
</script>
Alright cannot find this anywhere and I was wondering how to grab the values of a text box from a jsp or servlet and display it in another servlet.
Now my issue isn't passing the data and actually displaying it, my issue is that whenever a space is in the value I can only get that first bit of information. For example:
<form method="post" action="Phase1Servlet">
<p>Favorite Place:</p> <input type="text" name="place"></div>
<input id="submit" type="submit" value="Submit">
</form>
Say The user types in "The Mall"
in the Servlet I use:
String place = request.getParameter("place");
Then output the variable place somewhere in my code I only get the word "The"
Do I need to use request.getParameterValues("place"); instead? If so how do I pass the values from servlet to servlet through a hidden field? When I do this:
String [] placeArr = request.getParameterValues("place");
out.println("<input type=\"hidden\" name=\"place\" value="+ placeArr +">");
The hidden field actually stores [Ljava.lang.String;#f61f5c
Do i have to parse this or convert this somehow?
Should be
String placeArr = request.getParameterValue("place");
out.println("<input type=\"hidden\" name=\"place\" value=\""+ placeArr +"\">");
Escape the string in the hidden field
Are you really sure that when you use
String place = request.getParameter("place");
the place variable contains only word before first space? Because it is rather weird situation. If you want to pass a parameter to another servlet(assuming that another servlet is called from this servlet) you can set a request attribute in first servlet and then dispatch that request to another servlet, for example:
request.setAttribute("place", "The mail");
RequestDispatcher dispatcher=getServletContext().getRequestDispatcher( path_to_another_servlet );
dispatcher.forward( request, response );
and then in another servlet ypu can use it as:
String place = request.getAttribute("place");