Value passed with request.setAttribute() is not available by request.getParameter() - servlets

I give a string variable a value in the normal execution of the code ,but if an exception happen I will give it another value , the problem is that in catch block the value is still the same as i assign first .
Here is my code ,first I assign page value "addUser" inside try block and in catch I give it "ErrorPage" value , I send the value of page within http request to forword method and inside it i print the value of page.
I cause an error in the excution of the code an i want it to go through catch block , and it does , but when it send the page value to the forword function the value of page is "addUser" not "ErrorPage" although i assign it to "ErrorPage" !!
String page = "addUser";
try {
// ...
request.setAttribute("page", page);
forward(request, response);
} catch (SQLException e) {
page = "ErrorPage";
request.setAttribute("page", page);
forward(request, response);
}
and here is the forword function
String page = request.getParameter("page");
System.out.println("page is " + page); // each time it prints addUSer
Can someone help? and thanx in advance.

You're calling request.getParameter() instead of request.getAttribute() to obtain the value. Since you've set it as request attribute, you should also get it as request attribute.
So:
request.setAttribute("foo", foo);
is only available by
Object foo = request.getAttribute("foo"); // NOT getParameter().
The getParameter() is only for HTTP request parameters as you can specify in request URL or in input fields of HTML forms.

In addition to BalusC's point"
In your code you have declared two "String page" variable. This will not compile. I think the parameter that you are passing to the request in the catch must be the "other" page variable. But it is hard to tell since this is not a true example.

Related

Composite C1 - How do I redirect to a 404 within an InlineMethodFunction

I have a Composite site where the URL structure is like so:
site.com/products/1234/product-name
The bold part is the page location. 1234 is the Product ID and then product-name is just a slug.
I register PathInfo and I'm using 1234 to read a SQL Database and return information to show on the site. I'm doing that inside an inline C# function called productDetails which returns an XElement to the XSLT Function.
Sometimes, we will discontinue a product or the ID will not exist in our database. What I'd like to do in those cases is to do one of the following
Return a 404
Redirect to my 404 with a URL
I then want to email out a notice (or at least log the error).
Currently, if the product doesn't exist, I just return an empty <product> element.
I have tried the following code inside the InlineMethodFunction > 'productDetails method, but the Response Object doesn't seem to be available. IDEALLY I want to set the Response Type to 404 instead of redirect. Any ideas?:
public static class InlineMethodFunction
{
public static XElement productDetails( int BulkProductId ) {
ProductContext db = new ProductContext();
var products = db.ProductDetailsByBulkID(BulkProductId).ToList();
if (products.Count < 1)
{
// THIS doesn't work
Response.Redirect("~/404?ProductCode=" + BulkProductId.ToString());
HttpContext.Current.Response.Redirect("~/404?ProductCode=" + BulkProductId.ToString());
// ERROR RETURNED The name 'HttpContext' does not exist in the current context
}
//
// rest of code
//
}
}
As it turns out, I was only able to accomplish this in an External function. Kudos to Pauli Østerø!
For those interested... here's the actual code used:
if(products.Count < 1){
HttpResponse response = HttpContext.Current.Response;
response.StatusCode = 404;
response.Status = "404 Not Found";
//
// Send mail to let someone know
//
}
Rather than redirect, I just set the 404 message and the URL stays intact, but with a 404.

Session Variable value becoming null After write Response.Write("REDIRECT=xxx")

I have one page which handle Payment Gateway Response, PaymentReturn.aspx. In this page i am logging response and storing response into session variable and use this session variable into another page Invoice.aspx which handle invoice page... So in PaymentReturn Page, I have
Session["ResponseOfPayment"] = paymentResonse as PaymentResponse; // PaymentResonse is class
Response.Write("REDIRECT=http://mydomain.com/Invoice.aspx");
and in Invoice.aspx I have,
PaymentResponse paymentResonse = Session["ResponseOfPayment"] as PaymentResponse;
if(paymentResponse!=null)
{
// Generate Invoice
}
But I am getting paymentResonse instance null.. What is going wrong with this?
Use Response.Redirect instead of Response.Write.
Response.Redirect("Invoice.aspx");

Http.Page.Request[" "] not returning correct values

Situation:-
There is a Home.aspx page, which can be opened by a unique user ("userName" variable).
This page has a popup window control name 'alertWindow'.
In the pageLoad event of Home.aspx.cs, Welcome.aspx page is opened in the 'alertWindow' using NavigateUrl property.
The querystring passed to Welcome.aspx page contains a parameter "UserName" and this parameter is set to the logged in user's name ("userName" variable).
Now when the code execution comes to Welcome.aspx.cs page, "Request["UserName"]" is used to get\retrieve the current "userName" paramerter existing in the query string.
Issue:-
When a logged-in user's name has space or other non-usual characters, then "Request["UserName"].ToString()" doesn't retrieve the actual and correct value.
For Ex. if the logged in "userName" = "A&T Telecom", then "Request["UserName"].ToString() retrieves only "A" and nothing else.
But if the userName string is a proper value like "micheal", then "Request["UserName"].ToString() retrieves only "Micheal" correctly
Requirement:-
Please provide a way so that I get the correct value from Request["UserName"] for any kind of "userName" string value.
Home.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (user is valid)
alertWindow.NavigateUrl = "Welcome.aspx?userName=" + currentUser.ToString();
}
Welcome.aspx.cs:-
currentUserName = Request["userName"].ToString();
This is logical because you do not Encode your url. Try this:
alertWindow.NavigateUrl = "Welcome.aspx?userName=" + Server.UrlEncode(currentUser.ToString());
To say few more, they are some special characters that used on the URL, like the
: / # ? & # % + (and the space).
All that characters must be encode to a different format, so the url will not break, the UrlEncode do exactly that.
Two notes.
I select the Server to call the UrlEncode because is not depend from the Request, and you can use it inside a thread, or any function that is not called from the Page.
The Request.QueryString make UrlDecode when you use it. To get the encode url you call the Request.RawUrl
You cannot add white spaces within your url, it needs encoding so :
//uses HttpUtility.UrlEncode internally
Server.UrlEncode("something with spaces");
or
HttpUtility.UrlEncode("something with spaces");

Cannot retrieve Session value

I've written a simple code to keep a USerID with the help of session. However I can't get Session value although it's not null. I've done exactly the way microsoft official tutorial says. Here's the code:
The code on the Default.aspx
string regCode = loginBase.getRegCodePerUser(txtLogin.Text);
Session["regCode"] = regCode;
//lblInfo.text=(string)Session["regCode"];When I check it shows the right string.It's OK
Response.Redirect("Selection.aspx");
I do not directly go to that page.I first go to Selection.aspx, then UpdateStages.
And this is the code on the other page(UpdateStages.apsx):
if ((string)Session["connSTR"] == null && (string)Session["user"] == null)
{
Response.Redirect("Default.aspx");
}
else if ((string)Session["regCode"]!=null)
{
regCode=(string)Session["regCode"];
lblInfo.Text = regCode;//Show nothing. Empty.
}
It might very well be that when you set the session variable:
Session["regCode"] = loginBase.getRegCodePerUser(txtLogin.Text);
That the username is not available yet and that is why it's returning an empty string, and I would assume that you are executing this code: lblStatus.Text =loginBase.getRegCodePerUser(txtLogin.Text); on a different page/after the user has logged in and that is why you get the value in the label when you assign it directly.
Put a breakpoint on where you set the Session variable and see if the value is being set.
Otherwise your session settings could be incorrect in your web.config which causes the session values to be cleared before you get to your second page where you are accessing it.

jQuery UI autocomplete is not displaying results fetched via AJAX

I am trying to use the jQuery UI autocomplete feature in my web application. What I have set up is a page called SearchPreload.aspx. This page checks for a value (term) to come in along with another parameter. The page validates the values that are incoming, and then it pulls some data from the database and prints out a javascript array (ex: ["item1","item2"]) on the page. Code:
protected void Page_Load(object sender, EventArgs e)
{
string curVal;
string type ="";
if (Request.QueryString["term"] != null)
{
curVal = Request.QueryString["term"].ToString();
curVal = curVal.ToLower();
if (Request.QueryString["Type"] != null)
type = Request.QueryString["Type"].ToString();
SwitchType(type,curVal);
}
}
public string PreLoadStrings(List<string> PreLoadValues, string curVal)
{
StringBuilder sb = new StringBuilder();
if (PreLoadValues.Any())
{
sb.Append("[\"");
foreach (string str in PreLoadValues)
{
if (!string.IsNullOrEmpty(str))
{
if (str.ToLower().Contains(curVal))
sb.Append(str).Append("\",\"");
}
}
sb.Append("\"];");
Response.Write(sb.ToString());
return sb.ToString();
}
}
The db part is working fine and printing out the correct data on the screen of the page if I navigate to it via browser.
The jQuery ui autocomplete is written as follows:
$(".searchBox").autocomplete({
source: "SearchPreload.aspx?Type=rbChoice",
minLength: 1
});
Now if my understanding is correct, every time I type in the search box, it should act as a keypress and fire my source to limit the data correct? When I through a debug statement in SearchPreload.aspx code behind, it appears that the page is not being hit at all.
If I wrap the autocomplete function in a .keypress function, then I get into the search preload page but still I do not get any results. I just want to show the results under the search box just like the default functionality example on the jQuery website. What am I doing wrong?
autocomplete will NOT display suggestions if the JSON returned by the server is invalid. So copy the following URL (or the returned JSON data) and paste it on JSONLint. See if your JSON is valid.
http://yourwebsite.com/path/to/Searchpreload.aspx?Type=rbChoice&term=Something
PS: I do not see that you're calling the PreLoadStrings function. I hope this is normal.
A couple of things to check.
Make sure that the path to the page is correct. If you are at http://mysite.com/subfolder/PageWithAutoComplete.aspx, and your searchpreload.aspx page is in another directory such as http://mysite.com/anotherFolder/searchpreload.aspx the url that you are using as the source would be incorrect, it would need to be
source: "/anotherFolder/Searchpreload.aspx?Type=rbChoice"
One other thing that you could try is to make the method that you are calling a page method on the searchpreload.aspx page. Typically when working with javascript, I try to use page methods to handle ajax reqeusts and send back it's data. More on page methods can be found here: http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx
HTH.

Resources