Passing a variable from one servlet to another servlet - servlets

How do I pass a variable array from one servlet to another servlet?

If you're passing the current request to another servlet, then just set it as request attribute.
request.setAttribute("array", array);
request.getRequestDispatcher("/servleturl").include(request, response);
It'll be available in another servlet as follows:
Object[] array = (Object[]) request.getAttribute("array");
Or, if you're firing a brand new request to another servlet, then just set it as request parameters.
StringBuilder queryString = new StringBuilder();
for (Object item : array) {
queryString.append("array=").append(URLEncoder.encode(item, "UTF-8")).append("&");
}
response.sendRedirect("/servleturl?" + queryString);
It'll be available in another servlet as follows:
String[] array = request.getParameterValues("array");
Or, if the data is too large to be passed as request parameters (safe max length is 255 ASCII characters), then just store it in session and pass some unique key as parameter isntead.
String arrayID = UUID.randomUUID().toString();
request.getSession().setAttribute(arrayID, array);
response.sendRedirect("/servleturl?arrayID=" + arrayID);
It'll be available in another servlet as follows:
String arrayID = request.getParameter("arrayID");
Object[] array = (Object[]) request.getSession().getAttribute(arrayID);
request.getSession().removeAttribute(arrayID);

Related

Share Session State Between ASP.NET and Classic ASP

Great Article on this subject here: https://searchwindevelopment.techtarget.com/tip/Share-session-state-between-ASP-and-ASPNET-apps
Problem is, I cant get it to work without source code. The code snippets in the article show many errors in Visual Studios. The author, Dennis Hurst is unreachable, as it was written in 2004. Anybody out there have the actual Source code they can post ? Or maybe point me in the right direction ? My goal is to pull Classic ASP object data (Application) into ASP.Net code that shares the same folder. I have read that it might be possible using a COMM Wrapper, but that is way out of my skill level. This sounds like the best solution for my problem. Thank You in advance for your help.
// The constructor for this class takes a reference to the HttpContext and derives the URL it will need to send its requests to
public ASPSessionVar(HttpContext oInContext)
{
oContext = oInContext;
ASPSessionVarASP = "SessionVar.asp";
/* We now build a System.Uri object to derive the correct
URL to send the HTTP request to. oContext.Request.Url
will contain a System.Uri object that represents
this ASPXs URL.
*/
System.Uri oURL = oContext.Request.Url;
ASPSessionVarASP = oURL.Scheme + "://"
+ oURL.Host + ":" + oURL.Port.ToString()
+ ASPSessionVarASP;
}
//-------------------------------------------------------------------------//
// The primary function for this example is called GetSessionVar. It does the majority of the work done by this application,
// This includes creating a WebRequest, sending it off to the ASP page, and returning the response.
// First get the Session Cookie
string ASPCookieName = "";
string ASPCookieValue = "";
if (!GetSessionCookie
(out ASPCookieName, out ASPCookieValue))
{
return "";
}
// Initialize the WebRequest.
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create
(ASPSessionVarASP + "?SessionVar=" + ASPSessionVar);
myRequest.Headers.Add
("Cookie: " + ASPCookieName + "=" + ASPCookieValue);
// Send the request and get a response
HttpWebResponse myResponse =
(HttpWebResponse)myRequest.GetResponse();
Stream receiveStream = myResponse.GetResponseStream();
System.Text.Encoding encode =
System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream =
new StreamReader(receiveStream, encode);
string sResponse = readStream.ReadToEnd();
// Do a bit of cleanup
myResponse.Close();
readStream.Close();
return sResponse;
}
//------------------------------------------------------------------------------------------------------------------------//
// This function simply takes the Request that was passed by the client and extracts the ASP Session cookie from it.
// This function is called by the GetSessionVar function to retrieve the ASPSession cookie.
private bool GetSessionCookie
(out string ASPCookieName, out string ASPCookieValue)
{
int loop1;
HttpCookie myCookie; // Cookie variable
ASPCookieName = "";
ASPCookieValue = "";
// Capture all cookie names into a string array.
String[] CookieArray =
oContext.Request.Cookies.AllKeys;
// Grab individual cookie objects by cookie name.
for (loop1 = 0; loop1 < CookieArray.Length; loop1++)
{
myCookie =
oContext.Request.Cookies[CookieArray[loop1]];
if (myCookie.Name.StartsWith("ASPSESSION"))
{
ASPCookieName = myCookie.Name;
ASPCookieValue = myCookie.Value;
return true;
}
}
return false;
}
//--------------------------------------------------------------------------------------------------------------------------------//
//The ASPX page will instantiate an ASPSessionVar object, passing in the current Context to the construct or.
//The GetSessionVar function is then called, passing in the name of the ASP Session variable that is to be retrieved.
//Create an ASPSessionVar object,
//passing in the current context
SPI.WebUtilities.ASP.ASPSessionVar oASPSessionVar
= new SPI.WebUtilities.ASP.ASPSessionVar(Context);
string sTemp = oASPSessionVar.GetSessionVar("FirstName");
// CLASSIC ASP CODE BELOW !!
//The ASP code for this example was placed in an ASP file called SessionVar.asp.
// It performs two simple tasks. First, it ensures that the request is coming from the server that the ASP page is running on.
// This ensures that the request is valid and coming ONLY from the Web server's IP address.
// The ASP page then returns the session variable it was asked to provide
<%
dim sT
if Request.ServerVariables("REMOTE_ADDR") =
Request.ServerVariables("LOCAL_ADDR") then
sT = Request("SessionVar")
if trim(sT) <> "" then
Response.Write Session(sT)
end if
end if
%>

How a servlet can read array list through the request header?

I tried to send a url which contains http://192.168.1.xxx:8080/AttendanceTrack/UserGroupController?usersList=arrayList
where usersList is the parameter name of an ArrayList.
In the servlet side, I tried to access as follows
ArrayList usersList = (ArrayList) request.getAttribute("usersList");
But I got only null value.
In my client side, I changed my code as
String json = new Gson().toJson(arrayList);
jsonObject.put("usersList", json);
and appended the parameter name in url and send it to the server side.
In my server side,
String jsonString = request.getParameter("usersList");
Problem is fixed.

Error at `Request.QueryString["ID"]` in asp.net

i have an Insert method which takes an object with 3 fields as parameter and one of the field is SiteID which i already have in 'Querystring["ID"]'
public static void ProcessIT(string Xindex, string Yindex)
{
SiteLogic SL = new SiteLogic();
Site ste = SL.SelectByID(Convert.ToInt32(Request.QueryString["ID"]));
Walkable W = new Walkable();
W.X = Convert.ToInt32(Xindex);
W.Y = Convert.ToInt32(Yindex);
W.SiteID = ste.SiteID;
WalkableLogic wlc = new WalkableLogic();
wlc.Insert(W);
}
}
now when i try to fetch the ID by Request.QueryString["ID"] it shows this error "an object reference is required for the non-static field method or property 'System.web.UI.Page.Request.get'"
Your code being static method, instead, doesn't have access to Request property, since static methods do not have access to instance members.
Use HttpContext.Current.Request.Url instead of Request.Url to make your code more universal.

Error processing response stream. The XML element contains mixed content

I'm calling a stored procedure via WCf-DataService and EF4. Other method works fine but one which return List failed with the exception Error processing response stream. The XML element contains mixed content.
Here is the XML return by the method (call in http)
<GetShowName>
<element>MONT</element>
<element>INTERPEECH 08/2011</element>
<element>POI MOBILIER 09/2011</element>
<element>ASSEMBLE GALE CLUB 41 06/2011</element>
<element>AFTES 10/2011</element>
<element>DIVERS DEVIS 12/2011</element>
<element>DIVERS DEVIS 12/2011</element>
<element>SFTS 2011</element>
<element>COUPE DU MONDE BIATHLON 12/11</element>
<element>CADRE NOIR GENEVE 04/2011</element>
</GetShowName>
And the code is:
private List<T> ListWithFilter<T>(string methodName, string methodParameters)
{
StringBuilder methodParams = new StringBuilder("/" + methodName + "?");
methodParams.Append(methodParameters);
Uri methodUri = new Uri(entities.BaseUri + methodParams.ToString());
List<T> result = entities.Execute<T>(methodUri).ToList(); //Exception here
return result;
}
Any idea?
According to this post the client does not support primitive type materialization as of .NET 4.0. May need to parse the result manually:
Invoking a WebGet throws an exception

Change Single URL query string value

I have an ASP.NET page which takes a number of parameters in the query string:
search.aspx?q=123&source=WebSearch
This would display the first page of search results. Now within the rendering of that page, I want to display a set of links that allow the user to jump to different pages within the search results. I can do this simply by append &page=1 or &page=2 etc.
Where it gets complicated is that I want to preserve the input query string from the original page for every parameter except the one that I'm trying to change. There may be other parameters in the url used by other components and the value I'm trying to replace may or may not already be defined:
search.aspx?q=123&source=WebSearch&page=1&Theme=Blue
In this case to generate a link to the next page of results, I want to change page=1 to page=2 while leaving the rest of the query string unchanged.
Is there a builtin way to do this, or do I need to do all of the string parsing/recombining manually?
You can't modify the QueryString directly as it is readonly. You will need to get the values, modify them, then put them back together. Try this:
var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set("page", "2");
string url = Request.Url.AbsolutePath;
string updatedQueryString = "?" + nameValues.ToString();
Response.Redirect(url + updatedQueryString);
The ParseQueryString method returns a NameValueCollection (actually it really returns a HttpValueCollection which encodes the results, as I mention in an answer to another question). You can then use the Set method to update a value. You can also use the Add method to add a new one, or Remove to remove a value. Finally, calling ToString() on the name NameValueCollection returns the name value pairs in a name1=value1&name2=value2 querystring ready format. Once you have that append it to the URL and redirect.
Alternately, you can add a new key, or modify an existing one, using the indexer:
nameValues["temp"] = "hello!"; // add "temp" if it didn't exist
nameValues["temp"] = "hello, world!"; // overwrite "temp"
nameValues.Remove("temp"); // can't remove via indexer
You may need to add a using System.Collections.Specialized; to make use of the NameValueCollection class.
You can do this without all the overhead of redirection (which is not inconsiderable). My personal preference is to work with a NameValueCollection which a querystring really is, but using reflection:
// reflect to readonly property
PropertyInfo isReadOnly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
// make collection editable
isReadOnly.SetValue(this.Request.QueryString, false, null);
// remove
this.Request.QueryString.Remove("foo");
// modify
this.Request.QueryString.Set("bar", "123");
// make collection readonly again
isReadOnly.SetValue(this.Request.QueryString, true, null);
Using this QueryStringBuilder helper class, you can grab the current QueryString and call the Add method to change an existing key/value pair...
//before: "?id=123&page=1&sessionId=ABC"
string newQueryString = QueryString.Current.Add("page", "2");
//after: "?id=123&page=2&sessionId=ABC"
Use the URIBuilder Specifically the link textQuery property
I believe that does what you need.
This is pretty arbitrary, in .NET Core at least. And it all boils down to asp-all-route-data
Consider the following trivial example (taken from the "paginator" view model I use in virtually every project):
public class SomeViewModel
{
public Dictionary<string, string> NextPageLink(IQueryCollection query)
{
/*
* NOTE: how you derive the "2" is fully up to you
*/
return ParseQueryCollection(query, "page", "2");
}
Dictionary<string, string> ParseQueryCollection(IQueryCollection query, string replacementKey, string replacementValue)
{
var dict = new Dictionary<string, string>()
{
{ replacementKey, replacementValue }
};
foreach (var q in query)
{
if (!string.Equals(q.Key, replacementKey, StringComparison.OrdinalIgnoreCase))
{
dict.Add(q.Key, q.Value);
}
}
return dict;
}
}
Then to use in your view, simply pass the method the current request query collection from Context.Request:
<a asp-all-route-data="#Model.NextPageLink(Context.Request.Query)">Next</a>

Resources