I am setting some values in request in my action/controller class like this:
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getNativeRequest();
request.setAttribute("testKey", "testValue");
But when I tried to retrieve this from JSP, I am getting null value.
<%
String testKey = ""+request.getAttribute("testKey");
%>
Any idea, please help.
After research I found 2 ways to do this:
1) Using a same modelAttribute in and assign values back and forth
2) setting values into context.getFlowScope().put(KEY,OBJECT);
And retrieving this value (OBJECT) from JSP using ${KEY}.
Related
I have a question here. I use a restful url #RequestMapping("download/{fileName}/{id}/{count}") to receive parameter form JSP.As follows:
#RequestMapping("show/{pageNum}/{pageSize}")
public String showFileByPage(#PathVariable int pageNum,#PathVariable int pageSize){
//do something
}
then, i find that i have to access this HandlerMethod by using the complete url like http://localhost:8080/show/1/2.
Now, i wanna to use an omitted like http://localhost:8080/show to access this page , but it occur an error 404, error description: The requested resource is not available.
Then in this case, how can i correct this error and set default value for pageNum and pageSize like pageNum = 1(default),pageSize = 2(default)
An argument to a Spring MVC method can be declared as RequestBody or RequestParam. Is there a way to say, "Take this value from either the body, if provided, or the URL parameter, if not"? That is, give the user flexibility to pass it either way which is convenient for them.
You can make both variables and check them both for null later on in your code
like this :
#RequestMapping(value = GET_SOMETHING, params = {"page"}, method = RequestMethod.GET)
public
#ResponseBody
JSONObject getPromoByBusinessId(
#PathVariable("businessId") String businessId, #RequestParam("page") int page,
#RequestParam("valid") Boolean valid,
#RequestParam("q") String promoName) throws Exception {}
and then use a series if if-else to react to requests.
I wrote it to work with any of the three params be null or empty, react to all different scenarios.
To make them optional, see :
Spring Web MVC: Use same request mapping for request parameter and path variable
HttpServletRequest interface should help solve this problem
#RequestMapping(value="/getInfo",method=RequestMethod.POST)
#ResponseBody
public String getInfo(HttpServletRequest request) {
String name=request.getParameter("name");
return name;
}
Now, based on request data coming from body or parameter the value will be picked up
C:\Users\sushil
λ curl http://localhost:8080/getInfo?name=sushil-testing-parameter
sushil-testing-parameter
C:\Users\sushil
λ curl -d "name=sushil-testing-requestbody" http://localhost:8080/getInfo
sushil-testing-requestbody
C:\Users\sushil
λ
1)When exactly we need to use HTTPContext (exclusively), please elaborate with an example if possible.
2)What does the following code do
internal string QueryString( string name )
{
if ( HttpContext.Current.Request.QueryString[name] == null )
return string.Empty;
else {
return HttpContext.Current.Request.QueryString[name].ToString();
}
3)Is there any other alternative way where we avoid using HttpContext
Q1:
HttpContext is an object which encapsulates all HTTP-specific information about an individual HTTP request. So, if you need to get any information about receiving HTTP request (for example in order to get the query string parameter values, referral urls, User's IP address etc), you need to use HttpContext object. Further more, this object contains information of current Request, Response, Server, Session, Cache, User and etc.
More information
Usage and examples
Get current session Id: HttpContext.Session.SessionID
Get Timestamp of current request: HttpContext.Timestamp.ToString()
Q2:
In your code sample, you are trying get the value of query string parameter 'name'.
Your dummy request Url looks like - http://www.yourdomain.com/something?name=queryStringValue
QueryString parameter = name
QueryString parameter value = queryStringValue
Hope this helps.
I have a Post method that returns an HttpResponseMessage:
HttpResponseMessage response =
Request.CreateResponse(HttpStatusCode.Created, updatedItemDto);
I'm writing some tests for this and would like to get the updated item from the HttpResponseMessage (particularly the ItemId). I tried inspecting the object and it looks like the object lives in Response.Content, but I don't know how to get it from the Content.
If HttpResponseMessage contain serialized data model of a known class then you can use ReadAsAsync<>() extension method like this
MyObject obj = await response.ReadAsAsync<MyObject>();
And this is the most simple and easy way.
You can inspect the response in the debugger since you mention "it looks like the object lives in Response.Content".
You might need to cast it to something meaningful, like in this response,
Request.CreateResponse(HttpStatusCode.Created, updatedItemDto) as MyObject;
For eg:i use a method in controller class :
public ModelAndView fileupload(HttpServletRequest request, HttpServletResponse response) throws Exception
Within that method i use
Map modelMap = new HashMap();
Then set the value like
modelMap.put(name,request.getParameter("uname"));
Then in modelView object I add the object like
modelView.addAllObjects(modelMap);
Then set the view like
modelView.setViewName("salu.jsp");
then returned modelView object.
It is displaying that jsp page but the value I print in jsp using the scriptlet like
<% String username=request.getAttribute("name");
out.println("name is "+username); %>.
But it is printing the value is null. Tell me how i can get thet Value.
Assuming variable name value in your controller is "name", just use ${name} in your JSP.