I have a working code.
#RequestMapping(value = "/test/getData.do", method = RequestMethod.POST)
public String getData(HttpServletRequest request, ModelMap model
,#RequestBody Map reqbody)
throws Exception{
List result = testService.selectData(reqbody);
model.addAttribute("grid", result);
return "jsonview";
}
Now, I want to change above code to below style.
- adding data to response instead of model.
#RequestMapping(value = "/test/getData.do", method = RequestMethod.POST)
public String getData(HttpServletRequest request, HttpServletResponse response
,#RequestBody Map reqbody)
throws Exception{
List result = testService.selectData(reqbody);
//model.addAttribute("grid", result);
//add result to response here...
return "jsonview";
}
Any suggestion??
Thanks in advance.
If you are working with session you can do the next step.
request.getSession().setAtribute("nameVarible","valor")
PD: Excuse me gramatic but I am trying to learn English
Not sure what is your intention is, but you can not set attribute to response object. You can only set attribute in request object. Since you already have a request parameter, change your code as follows:
#RequestMapping(value = "/test/getData.do", method = RequestMethod.POST)
public String getData(HttpServletRequest request, #RequestBody Map reqbody)throws Exception{
List result = testService.selectData(reqbody);
request.setAttribute("grid", result);
return "jsonview";
}
Related
My Controller:
#RequestMapping(value = "/BankEdit", method = RequestMethod.GET) public ModelAndView BankEdit(HttpServletRequest request, HttpServletResponse response,BankBean bankBean)
{
ModelAndView model= null;
model = new ModelAndView("accounts/company/manage_bank_edit");
long bName=Long.parseLong(request.getParameter("bName"));
System.out.println("Banme get "+request.getParameter("bName"));
return model;
}
am getting bName value in get method...I need the same value in post method..getting null value
POst Method:
#RequestMapping(value = "/BankEdit", method = RequestMethod.POST) public ModelAndView BankEditPost(HttpServletRequest request, HttpServletResponse response,BankBean bankBean) throws Exception
{
ModelAndView model= null;
model = new ModelAndView("accounts/company/manage_bank");
long session_id=(Long) request.getSession().getAttribute("sessionId");
long sessionBId=(Long) request.getSession().getAttribute("sessionBId");
System.out.println("B_name==="+request.getParameter("bName"));
long bName=Long.parseLong(request.getParameter("bName"));
bankBean = accDao.editBank(bankBean,sessionBId,session_id,bName);
return model;
}
In post method you try to retrieve parameter value bName. as like get method.
For GET request value will be send as parameter like
~/BankEdit?name1=value1&name2=value2
so request.getParameter("bName") you get that value.
For POST method value send via message body not send in parameter so you got null request.getParameter("bName")) cause you try to extract from parameter request url.
For received POST value you need declare parameter object on method argument and you got the value from message body.
If bName is part of your BankBean then you retrieve from your BankBean.bName object.
If not then declare in your method argument and get your value.
If bName is object of BankBean:
#RequestMapping(value = "/BankEdit", method = RequestMethod.POST)
public ModelAndView BankEditPost(HttpServletRequest request, HttpServletResponse response,BankBean bankBean) throws Exception{
ModelAndView model= null;
model = new ModelAndView("accounts/company/manage_bank");
long session_id=(Long) request.getSession().getAttribute("sessionId");
long sessionBId=(Long) request.getSession().getAttribute("sessionBId");
System.out.println("B_name=== "+bankBean.bName);
long bName=Long.parseLong(bankBean.bName);
bankBean = accDao.editBank(bankBean,sessionBId,session_id,bName);
return model;
}
In other way received string:
#RequestMapping(value = "/BankEdit", method = RequestMethod.POST)
public ModelAndView BankEditPost(HttpServletRequest request, HttpServletResponse response,BankBean bankBean, String stringValue) throws Exception{
ModelAndView model= null;
model = new ModelAndView("accounts/company/manage_bank");
long session_id=(Long) request.getSession().getAttribute("sessionId");
long sessionBId=(Long) request.getSession().getAttribute("sessionBId");
System.out.println("B_name=== "+stringValue);
long bName=Long.parseLong(stringValue);
bankBean = accDao.editBank(bankBean,sessionBId,session_id,bName);
return model;
}
I'm having an issue with RedirectAttributes not saving (i think). This is my code:
#RequestMapping(path = "/job_offers", method = RequestMethod.POST)
public String createJobOffer(#Valid #ModelAttribute("jobOfferForm") JobOfferForm jobOfferForm,
final BindingResult binding, RedirectAttributes attr) {
attr.addFlashAttribute("org.springframework.validation.BindingResult.jobOfferForm", binding);
attr.addFlashAttribute("jobOfferForm", jobOfferForm);
return "redirect:/job_offers";
}
#RequestMapping(path = "/job_offers", method = RequestMethod.GET)
public ModelAndView jobOffers(#RequestParam(required = false, value = "skill_id") final Long skillId,
#ModelAttribute("jobOfferForm") JobOfferForm jobOfferForm, final BindingResult binding) {
ModelAndView mav = new ModelAndView("job_offers/index");
mav.addAllObjects(getJobOffersMap(skillId));
mav.addObject("jobOfferForm", jobOfferForm);
return mav;
}
If I print my binding in the POST method it has the error in it, but when I call the GET method via the redirect the binding comes empty! and Spring doesnt show the error feedback on forms because of that
Any ideas?
Thanks!
Try this:
In your POST
attr.addFlashAttribute("bindignResultForJobOfferForm", binding);
And in GET
if (model.asMap().containsKey("bindignResultForJobOfferForm"))
{
model.addAttribute("errors",
model.asMap().get("bindignResultForJobOfferForm"));
}
I am using Spring to create and download Excel sheet I want to add some variable in model in requestiong mapping method so that I can use in other request maping method
#RequestMapping("/contentUploadDetails/{content_type}/{date}")
public ModelAndView contentUpload(
#PathVariable(value = "content_type") String content_type,
#PathVariable(value = "date") String date) {
List<CountAndValue> ls = contentCountImp
.getuploadedContentCountDatewise(content_type, date);
model.addObject("CountAndValue", ls);
return model;
}
As you can see in above
model.addObject("CountAndValue", ls);
I want to use this model value in my other requestMapping method
#RequestMapping(value = "/ContentUploadExport", method = RequestMethod.GET)
public ModelAndView getExcel() {
return new ModelAndView("CountAndValueExcel", "CountAndValue", CountAndValue);
}
how can I use CountAndValueExcel model object that is set by first method in second method with using session? Can I send model object(which contains list of class object) back from view to controller?
You can save an object into a session:
#RequestMapping("/contentUploadDetails/{content_type}/{date}")
public ModelAndView contentUpload(HttpServletRequest request,
#PathVariable(value = "content_type") String content_type,
#PathVariable(value = "date") String date) {
List<CountAndValue> ls = contentCountImp
.getuploadedContentCountDatewise(content_type, date);
model.addObject("CountAndValue", ls);
request.getSesion().setAttribute("CountAndValue", ls);
return model;
}
And then you retrieve it like this:
#RequestMapping(value = "/ContentUploadExport", method = RequestMethod.GET)
public ModelAndView getExcel(HttpServletRequest request) {
List<CountAndValue> CountAndValue = (List<CountAndValue>) request.getSession().getAttribute("CountAndValue");
return new ModelAndView("CountAndValueExcel", "CountAndValue", CountAndValue);
}
Wrote it from my head, not tested.
In my app,I use springMVC and tomcat,my controller return object,but when something wrong,I only want return some string message with content tye json,so I use response.error, but it not work,the return is a html.
my controller:
#RequestMapping(value = "{id}/{name}" ,method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody UserBean login(#PathVariable String id,#PathVariable("name") String userName,
#RequestHeader(value = "User-Agent") String user_agen,
#CookieValue(required = false) Cookie userId,
HttpServletRequest request,HttpServletResponse response,#RequestBody UserBean entity
) throws IOException {
System.out.println("dsdsd");
System.out.print(userName);
response.setContentType( MediaType.APPLICATION_JSON_VALUE);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "somethind wrong");
return null;
According to the Javadoc for the HttpServletReponse#sendError method:
Sends an error response to the client using the specified status. The
server defaults to creating the response to look like an
HTML-formatted server error page containing the specified message,
setting the content type to "text/html", leaving cookies and other
headers unmodified...
So sendError will generate an HTML error page using the message that you supplied and will override the content type to text/html.
Since the client end is expecting a JSON response, you may be better to manually set the response code and the message yourself using fields on your UserBean - assuming it can support it. That will then be serialized to a JSON response that your clientside Javascript can evaluate.
#RequestMapping(value = "{id}/{name}" ,method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody UserBean login(#PathVariable String id,#PathVariable("name") String userName,
#RequestHeader(value = "User-Agent") String user_agen,
#CookieValue(required = false) Cookie userId,
HttpServletRequest request,HttpServletResponse response,#RequestBody UserBean entity
) throws IOException {
System.out.println("dsdsd");
System.out.print(userName);
response.setContentType( MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
UserBean userBean = new UserBean();
userBean.setError("something wrong"); // For the message
return userBean;
There is also the option of using the Tomcat property org.apache.coyote. USE_CUSTOM_STATUS_MSG_IN_HEADER which will place the message into a custom response header. See this post and the Tomcat docs for more info.
I am trying to test this method.
#Override
public JSON connectResource() throws IOException {
//get the location and credentials for the certificates
System.setProperty("javax.net.ssl.trustStore", "C:/Program Files/Java/jdk1.7.0_40/jre/lib/security/cacerts");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
HttpRequest httpRequest = new HttpGet(url);
System.out.println("hello");
httpRequest.addHeader("Accept", "application/json");
HttpResponse response = httpClient.execute((HttpUriRequest) httpRequest);
System.out.println("hello1");
HttpEntity httpEntity = response.getEntity();
String data = this.getData(httpEntity);
return JSONSerializer.toJSON(data.toString());
}
My set up method is:
#Before
public void setUp() throws Exception{
mockHttpClient = mock(DefaultHttpClient.class);
mockHttpRequest = mock(HttpUriRequest.class);
mockHttpResponse = mock(BasicHttpResponse.class);
mockHttpEntity = mock(HttpEntity.class);
mockInputStream = mock(InputStream.class);
mockInputStreamReader = mock(InputStreamReader.class);
mockBufferedReader = mock(BufferedReader.class);
mockHttpGet = mock(HttpGet.class);
mockHttpRequestBase = mock(HttpRequestBase.class);
//when(mockHttpClient.execute(Mockito.isA(HttpUriRequest.class))).thenReturn(mockHttpResponse);
//when(mockHttpClient.execute(mockHttpRequest)).thenReturn(mockHttpResponse);
//when(mockHttpClient.execute(mockHttpRequestBase)).thenReturn(mockHttpResponse);
//when(mockHttpClient.execute(mockHttpGet)).thenReturn(mockHttpResponse);
when(mockHttpResponse.getEntity()).thenReturn(mockHttpEntity);
when(mockHttpEntity.getContent()).thenReturn(mockInputStream);
PowerMockito.whenNew(InputStreamReader.class)
.withArguments(mockInputStream).thenReturn(mockInputStreamReader);
PowerMockito.whenNew(BufferedReader.class)
.withArguments(mockInputStreamReader).thenReturn(mockBufferedReader);
PowerMockito.when(mockBufferedReader.readLine())
.thenReturn(JSON_STRING)
.thenReturn(null);
PowerMockito.whenNew(HttpGet.class).withArguments(VALID_URL)
.thenReturn(mockHttpGet);
}
And my test case is :
#Test
public void testConnectResource() throws IOException {
when(mockHttpClient.execute(mockHttpGet)).thenReturn(mockHttpResponse);
HttpConnectGithub connHandle = new HttpConnectGithub(VALID_URL);
JSON jsonObject = connHandle.connectResource();
System.out.println(jsonObject);
//assertThat(jsonObject, instanceOf(JSON.class));
}
However, the execution stops at
HttpResponse response = httpClient.execute((HttpUriRequest) httpRequest);
you can see all that I tried in the comments of my set up method.
Does anyone find an issue with anything? I debugged through my test case and all mock objects are properly initialized.
I have tried exchanging HttpUriRequest and HttpRequest, HttpResponse and BasicHttpResponse etc but without much luck.
Please guide on how to tackle this issue.
Part of the problem you're running into is matching the arguments:
#Test
public void testConnectResource() throws IOException {
when(mockHttpClient.execute(mockHttpGet)).thenReturn(mockHttpResponse);
HttpConnectGithub connHandle = new HttpConnectGithub(VALID_URL);
JSON jsonObject = connHandle.connectResource();
System.out.println(jsonObject);
//assertThat(jsonObject, instanceOf(JSON.class));
}
With the line you've specified above
when(mockHttpClient.execute(mockHttpGet)).thenReturn(mockHttpResponse);
The mocking will only trigger when the instance of mockHttpGet you've defined is passed.
Your method under test on the other hand is creating a new HttpGet instance which is not going to be the same as the mockHttpGet instance. You will need to alter the 'when' statement so that you have something like
when(mockHttpClient.execute(Matchers.any(HttpGet.class))).thenReturn(mockHttpResponse);
I'm doing this exclusively from memory so the Matchers.any() may be incorrect, but you should be able to make headway based on what I've given you above.
The problem is with mockHttpClient. It is not able to mock it automatically for some reason. The fix is to pass httpclient as a parameter through some method (constructor in my case)