how set the value in Model inside Spring MVC annotation Controller - spring

#RequestMapping(value = "/excelDataView", method=RequestMethod.GET )
public ModelAndView getExcel(final HttpServletRequest request, final HttpServletResponse response){
log.info("Inside getExcel()");
List<DataValidationResults> dataValidationResults = new ArrayList<DataValidationResults>();
dataValidationResults = dataValidationDelegate.exportData(TaskId);
log.info("dataValidationDelegate.exportData(TaskId) value " + dataValidationDelegate.exportData(TaskId));
request.setAttribute("dataValidationResults", dataValidationResults);
return new ModelAndView(new ExcelDataView(), "dataValidationResultsModel", dataValidationResults);
}

Related

Spring MVC Controller show 404

All i need help
this is my simple controller when i try to hit the url on postman it's
show 404 => response can any one tell me why it's come. i'm using the spring-boot project.
#Controller
#RequestMapping(value = "/rtb")
public class RtbTestController {
#RequestMapping(value = {"/naveen", "/nabeel", "/harsh"}, method = RequestMethod.GET)
public ModelAndView rtbResponseValidator(HttpServletRequest request, HttpServletResponse response) {
HashMap<String, Object> model = new HashMap<String, Object>();
model.put("pakistan", "zindabad");
model.put("indian", "Zindabad");
return new ModelAndView("openRTB", model);
}
}
Try this:
#Controller
#RequestMapping(value = "/rtb")
public class RtbTestController {
#RequestMapping(value = {"/naveen", "/nabeel", "/harsh"}, method = RequestMethod.GET, headers= "Accept=application/json")
public ModelAndView rtbResponseValidator(HttpServletRequest request, HttpServletResponse response) {
HashMap<String, Object> model = new HashMap<String, Object>();
model.put("pakistan", "zindabad");
model.put("indian", "Zindabad");
return new ModelAndView("openRTB", model);
}
}

Spring ModelAndView Attribute is null

I have one simple controller and one interceptor.
Within interceptor in postHandle-method I am checking user.
Problem: My user-model is sometimes null, between controller-handles.
postHandle invoked by home-handle==> User-Model is not null
postHandle invoked by check_user-handle ==> User-model is null
postHandle invoked by redirectToErrorPage-handle ==> User-model is
not null anymore and contains everything, what i've expected by
check_user-PostHandle Invocation.
Here is my controller
#Controller
#SessionAttributes("user")
public class HomeController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Model model, HttpServletRequest request, HttpSession session) {
User user = new User();
return new ModelAndView("login", "user", user);
////now User-Model was saved in the session
}
//now i'am redirectring user in the "check_user"-handle
#RequestMapping(value = "/check_user", method = RequestMethod.POST)
public ModelAndView checkUser(#Valid #ModelAttribute("user") User user, BindingResult bindingResult, Model model,
HttpServletRequest request, RedirectAttributes redirectAttr) {
RedirectView redirectView = null;
ModelAndView mav=null;
try {
if(!bindingResult.hasErrors()){
redirectView = new RedirectView("home");
redirectView.setStatusCode(HttpStatus.FOUND);
redirectAttr.addFlashAttribute("httpStatus", HttpStatus.FOUND);
mav = new ModelAndView(redirectView);
return mav; //at next i entry post-handle from interceptor,
//which says to me, that user-model is null.
}
}
//My interceptor redirects me to this handle.
//After this handle within interceptor method "postHandle", i see, that
//user-object exists
#RequestMapping(value = "/error", method = RequestMethod.GET)
public String redirectToErrorPage(HttpServletRequest request){
return "error";
}
}
And my Interceptor:
public class UserInterceptor extends HandlerInterceptorAdapter {
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
User user = (User) modelAndView.getModel().get("user");
if(user == null || !user.isAdmin()){
response.sendRedirect(request.getContextPath()+"/failed");
}
}
}
While I retrive, which keys my model has, when postHandle was invoked by "check_user", I have only one key "totalTime". Whats going on with my model?
Try modifying your postHandle() as below:
...
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
User user = (User) request.getSession().getAttribute("user");
...

HTTP redirect: 301 (permanent) vs. 302 (temporary) in Spring

I want to make a 301 redirect in Spring, So here the piece of code I use
#RequestMapping(value = { "/devices" } , method = RequestMethod.GET)
private String initGetForm(#ModelAttribute("searchForm") final SearchForm searchForm,
BindingResult result,
HttpServletRequest request,
HttpServletResponse response,
Model model, Locale locale) throws Exception {
String newUrl = "/devices/en";
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", newUrl);
response.setHeader("Connection", "close");
return "redirect:" + newUrl;
}
But checking the IE Developer Tools I got this Status 302 Moved Temporarily !
Spring is resetting your response headers when it handles the redirection since you are returning a logical view name with a special redirect prefix.If you want to manually set the headers handle the response yourself without using Spring view resolution. Change your code as follows
#RequestMapping(value = { "/devices" } , method = RequestMethod.GET)
private void initGetForm(#ModelAttribute("searchForm") final SearchForm searchForm,
BindingResult result,
HttpServletRequest request,
HttpServletResponse response,
Model model, Locale locale) throws Exception {
String newUrl = request.getContextPath() + "/devices/en";
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", newUrl);
response.setHeader("Connection", "close");
}
You can use RedirectView with TEMPORARY_REDIRECT status.
#RequestMapping(value = { "/devices" } , method = RequestMethod.GET)
private ModelAndView initGetForm(#ModelAttribute("searchForm") final SearchForm searchForm,
BindingResult result,
HttpServletRequest request,
HttpServletResponse response,
Model model, Locale locale) throws Exception {
....
RedirectView redirectView = new RedirectView(url);
redirectView.setStatusCode(HttpStatus.TEMPORARY_REDIRECT);
return new ModelAndView(redirectView);
}

Trying to pass objects to controller(Spring MVC)

I am trying to test my controller. Spring populates my Profile object but it is empty. I can set the email before the call bu it still is null. How to jag pass a Profile in a proper way?
private MockHttpServletRequest request;
private MockHttpServletResponse response;
#Autowired
private RequestMappingHandlerAdapter handlerAdapter;
#Autowired
private RequestMappingHandlerMapping handlerMapping;
#Before
public void setUp() throws Exception {
this.request = new MockHttpServletRequest();
request.setContentType("application/json");
this.response = new MockHttpServletResponse();
}
#Test
public void testPost() {
request.setMethod("POST");
request.setRequestURI("/user/"); // replace test with any value
final ModelAndView mav;
Object handler;
try {
Profile p = ProfileUtil.getProfile();
p.setEmail("test#mail.com");
request.setAttribute("profile", p);
System.out.println("before calling the email is " + p.getEmail());
handler = handlerMapping.getHandler(request).getHandler();
mav = handlerAdapter.handle(request, response, handler);
Assert.assertEquals(200, response.getStatus());
// Assert other conditions.
} catch (Exception e) {
}
}
This is the controller
#RequestMapping(value = "/", method = RequestMethod.POST)
public View postUser(ModelMap data, #Valid Profile profile, BindingResult bindingResult) {
System.out.println("The email is " + profile.getEmail());
}
Try using following signature for the controller function postUser.
public View postUser(ModelMap data, #ModelAttribute("profile") #Valid Profile profile, BindingResult bindingResult)
Hope this helps you. Cheers.

Render ModelAndView manually?

I need to render ModelAndView in my controller manually in order to put it inside JSON object. If I pass the whole ModelAndView object into to JSON I get " no serializer found for class javassistlazyinitializer" exception because jackson can't work properly with LAZY-objects.
Thank you
public class JSONView implements View {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(JSONView.class);
private String contentType = "application/json";
public void render(Map map, HttpServletRequest request, HttpServletResponse response)
throws Exception {
if(logger.isDebugEnabled()) {
logger.debug("render(Map, HttpServletRequest, HttpServletResponse) - start");
}
JSONObject jsonObject = new JSONObject(map);
PrintWriter writer = response.getWriter();
writer.write(jsonObject.toString());
if(logger.isDebugEnabled()) {
logger.debug("render(Map, HttpServletRequest, HttpServletResponse) - end");
}
}
public String getContentType() {
return contentType;
}
}
ModelAndView returnModelAndView = new ModelAndView(new JSONView(), model);

Resources