multiple dispatcher is requiered - servlets

did we need multiple request-dispatcher to send multiple value to the same page
I have written this.
String name=rs.getString("itemname");
String code=rs.getString("itemcode");
String lpr=rs.getString("lastpurchase");
String ur=rs.getString("unitrate");
String pq=rs.getString("pquantity");
String cpq=rs.getString("costpquan");
ServletContext context= getServletContext();
RequestDispatcher rd=context.getRequestDispatcher("/index.jsp")
rd.forward(request,response);
I need to send all these variables to a same page.

No, you don't need multiple dispatchers. You simply need to store each value in a separate request attribute. A better option would be to create an object (Item, for example) containing all these values, and to store this object in a single request attribute.
Item item = new Item(name, code, lpr, ur, pq, cpq);
request.setAttribute("item", item);
rd.forward(request,response);
You should also use much better names for your variables.

Related

Url.OriginalString vs Url.AbsoluteUri

What is the difference between HttpContext.Current.Request.Url.OriginalString and HttpContext.Current.Request.Url.AbsoluteUri?
I need to get the URL in the page load, but confused about the both.
Depending on the url, you could get the same result. It depends how exact you want it to be, if you want all fragments, and how you want to use it.
The following is for Uri but I think it applies to Url too (a url is a uri, essentially).
AbsoluteUri
The AbsoluteUri property includes the entire URI stored in the Uri instance, including all fragments and query strings.
This
Uri baseUri= new Uri("http://www.contoso.com");
Uri myUri = new Uri(baseUri,"catalog/shownew.htm?date=today");
Console.WriteLine(myUri.AbsoluteUri);
will return
http://www.contoso.com/catalog/shownew.htm?date=today
https://msdn.microsoft.com/en-us/library/system.uri.absoluteuri(v=vs.110).aspx
Uri.OriginalString
Gets the original URI string that was passed to the Uri constructor.
The following example creates a new Uri instance from a string. It illustrates the difference between the value returned from OriginalString, which returns the string that was passed to the constructor, and from a call to ToString, which returns the canonical form of the string.
// Create a new Uri from a string address.
Uri uriAddress = new Uri("HTTP://www.ConToso.com:80//thick%20and%20thin.htm");
// Write the new Uri to the console and note the difference in the two values.
// ToString() gives the canonical version. OriginalString gives the orginal
// string that was passed to the constructor.
// The following outputs "http://www.contoso.com/thick and thin.htm".
Console.WriteLine(uriAddress.ToString());
// The following outputs "HTTP://www.ConToso.com:80//thick%20and%20thin.htm".
Console.WriteLine(uriAddress.OriginalString);
https://msdn.microsoft.com/en-us/library/system.uri.originalstring(v=vs.110).aspx

Disassemble links into entities in Spring Hateoas

maybe another one stumbled upon this topic and found a nice solution. Using the HATEOAS REST approach with help of Spring HATEOAS project works pretty well for link building to resources. But in the end, to map flattened resources back to an entity object tree, I need to disassemble my link and query the persistence backend. Example given, I have an entity Item, referencing ItemType (Many-to-one). Natural key of item is the composite of ItemType foreign key and Item code itself. The URL I map in ItemController using the link builder is
#RequestMapping("/catalog/items/{itemTypeCode}_{itemCode}")
Now a unique link for an item is e.g. http://www.sample.com/catalog/items/p_abc123
To invert this link I do some very ugly string work:
#Override
public Item fromLink(Link link) {
Assert.notNull(link);
String baseLink = linkTo(ColorTypeController.class).toString() + "/";
String itemTypeAndItemPart = link.getHref().replace(baseLink, "");
int indexOfSplit = itemTypeAndItemPart.indexOf('_');
ItemType itemType = new ItemType();
itemType.setCode(itemTypeAndItemPart.substring(0, indexOfSplit));
Item item = new Item();
item.setItemType(itemType);
item.setCode(itemTypeAndItemPart.substring(indexOfSplit + 1));
return item;
}
And all the time I am wondering, If there isn't a much nicer and more flexible approach (beware of any query string part, that will break the code) to do this inverse mapping. I actually do not want to call another MVC controller from within a controller but it would be nice, to somehow utilize the dispatcher servlet disassembly functions to deconstruct the URL into something more handy to work with. Any helpful hints for me? Thx alot :)
You can use a UriTemplate. Its match method returns a map of variables and their values that have been extracted from the URI. For example:
UriTemplate uriTemplate = new UriTemplate("/catalog/items/{itemTypeCode}_{itemCode}");
Map<String, String> variables = uriTemplate.match("http://www.sample.com/catalog/items/p_abc123");
String itemTypeCode = variables.get("itemTypeCode"); // "p"
String itemCode = variables.get("itemCode"); // "abc123"

how to pass multiple key/value pairs in a single variable using query string?

I have one requirement like passing multiple values in the query string in a single variable.
Id=(refine_1=cgid=womens&refine_2=c_refinementColor=Black&refine_3=price=(0..500))
Is it possible to accept value like above sample from the query string?if yes,please tel me how to achieve this?
You should URL encode it:
?id=(refine_1%3Dcgid%3Dwomens%26refine_2%3Dc_refinementColor%3DBlack%26refine_3%3Dprice%3D(0..500))
Now assuming that your controller action takes an id parameter:
public ActionResult SomeAction(string id)
{
...
}
the value of this parameter inside the action will be (refine_1=cgid=womens&refine_2=c_refinementColor=Black&refine_3=price=(0..500)).
You could bring this even a step further and write a custom model binder that will parse this value and bind it to a view model containing those properties that your controller action could take as parameter instead of a id string parameter.

asp.net WebAPI list in Get request

I understand in Web API Get request, we can pass the list of inputs in query string like
Products?id=1&id=2&id=3
so the Get action method in ProductsController will be
Get([FromURI] int[] id)
{
}
My question now is, if the list of inputs to the Get call is much more (assume 1000), what is the recommended approach?
Comma separated values in query string will be some help. But that won't help in my case.Is there any other way to pass these inputs other than in query string?

asp.net return data in Page_Load

If a query string param exists in my page request I want to query the database on the server in the Page_Load and then return the result to the client. I can do the query string param check and query the DB but how do I return the data to the page and on the javascript side how do I access that data?
Ideally I would return JSON of an object structure and it would be returning an array of them.
Yes, returning JSON would be the best option. I'm not sure how you query your database (Do you use LINQ or ADO.NET DataTables, etc)
If you don't have custom object of type you want to send, I recommend you create one. Then you should get an array of them.
Example:
public class Person {
string Name { get; set; }
int Age { get; set; }
}
Person[] pArr = new Person[5];
Then you can use a third party library like this to create an string representaion of that array in JSON.
string json = JsonConvert.SerializeObject(product);
Then you write that json string to the Response object so its sent down to the client, by overriding the Render method of the page.
// Don't expect this code to work as it is, but take this as a guidance
Response.Clear();
Response.Write(json);
Response.Close();
on the client side use jQuery library send a request to page, and process the JSON response for you.
$.getJSON('url', function(data) {
//process data
});
Here is my suggestion if you don't want to use an AJAX request for this:
Use the objects as you would normally do in the page_load, and convert it to a JSON string as explained above.
Then use ClientScriptManager to create an JavaScript variable on the client side when it loaded.
ClientScript.RegisterClientScriptBlock(typeof(Page), "unique_key", "var myObjectList = " + json, true);
After this when the page loads you will have an variable named "myObjectList" with the list of objects without having to make a different AJAX call.
You can directly refer that variable in your javascript and do necessary processing.
Hope this helps.

Resources