Model Not Showing On HTML - spring

I have this end point
public static String x="";
#RequestMapping(value = "/allCheckOut", method = RequestMethod.GET)
public String getAllProducts(Model model, HttpServletRequest request){
String userId = (String) request.getSession().getAttribute("userId");
x = userId;
model.addAttribute("checkouts", checkOutService.findByUserName(x));
model.addAttribute("products", productService.getAllProduct());
model.addAttribute("userid", userId);
System.out.println("Size of all checkouts by "+userId+":"+checkOutService.findByUserName(userId).size());*/
return "products/addtoCart";
}
Why does this not show the model for checkouts? It only shows the model for products and user id
It works whenever I add checkouts, that endpoint loads the page
To display all 3 models on my page

Related

How to redirect from one controller method to another method with model data in spring boot application

In this example I am trying to redirect from handleSaveContact() controller method from contactSuccessMsg() controller method but after transfer I need to display success or update or failure msg to the UI which is only possible if I transfer Model data from 1st method to 2nd.
Could any one please suggest me how I can trasfer model data from one controller method to another controller method.
#GetMapping(value={"/", "/loadForm"})
public String loadContactForm(Model model) {
model.addAttribute("contact", new Contact());
return "index";
}
#PostMapping("/saveContact")
public String handleSaveContact(Contact contact, Model model) {
String msgTxt = null;
if(contact.getContactId()==null) {
msgTxt = "Contact Saved Successfully..!!";
}else {
msgTxt = "Contact Updated Successfully..!!";
}
contact.setIsActive("Y");
boolean isSaved = contactService.saveContact(contact);
if(isSaved) {
model.addAttribute("successMsg", msgTxt);
}else {
model.addAttribute("errorMsg", "Failed To Save Contact..!!");
}
return "redirect:/contactSuccessMsg";
}
/**
* To resolve Double Posting problem, redirecting the post req method to get request.
* #param contact
* #param model
* #return
*/
#GetMapping(value="/contactSuccessMsg")
public String contactSuccessMsg(Model model) {
model.addAttribute("contact", new Contact());
return "index";
}
I used Spring 3.2.3
1.)Added RedirectAttributes redirectAttributes to the method parameter list in controller1.
public String controlMapping1(
#ModelAttribute("mapping1Form") final Object mapping1FormObject,
final BindingResult mapping1BindingResult,
final Model model,
final RedirectAttributes redirectAttributes)
Inside the method added code to add flash attribute to redirectAttributes
redirectAttributes.addFlashAttribute("mapping1Form", mapping1FormObject);
Then, in the second contoller use method parameter annotated with #ModelAttribute to access redirect Attributes :
#ModelAttribute("mapping1Form") final Object mapping1FormObject
Here is the sample code from Controller 1:
#RequestMapping(value = { "/mapping1" }, method = RequestMethod.POST)
public String controlMapping1(
#ModelAttribute("mapping1Form") final Object mapping1FormObject,
final BindingResult mapping1BindingResult,
final Model model,
final RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("mapping1Form", mapping1FormObject);
return "redirect:mapping2";
}
From Contoller 2:
#RequestMapping(value = "/mapping2", method = RequestMethod.GET)
public String controlMapping2(
#ModelAttribute("mapping1Form") final Object mapping1FormObject,
final BindingResult mapping1BindingResult,
final Model model) {
model.addAttribute("transformationForm", mapping1FormObject);
return "new/view";
}

How to load data of home page in spring mvc

I have home page which contains features like city,country,states, user details and some pie charts and diagrams representing the data anlysis of the user.I am new to spring mvc I am in a confusion whether I should load the data of home page in one go or I should have onclick calls which would call to my controllers and load the data.
Example:
MyController Class
public class HomeController {
#Autowired
private EngagaementService engagaementService;
#Autowired
private EmployeeService employeeService;
#Autowired
private CgOfficeDetailsService cgOfficeDetailsService;
#RequestMapping("/")
public ModelAndView handleRequest() {
List<EmployeeInfo> listEmployees = employeeService.listEmployeeInfos();
ModelAndView model = new ModelAndView("index");
model.addObject("emp", listEmployees);
model.addObject("empCount", listEmployees.size());
return model;
}
#GetMapping("/getCity")
public ModelAndView getBU(HttpServletRequest request) {
String country = "India";
List<String> buList = employeeService.getCityName(country);
ModelAndView model = new ModelAndView("index");
model.addObject("buList", buList);
return model;
}
#GetMapping("/getState")
public ModelAndView getState(HttpServletRequest request) {
String country = "UP";
List<String> buList = employeeService.getState(country);
ModelAndView model = new ModelAndView("index");
model.addObject("buList", buList);
return model;
}
#GetMapping("/getUsers")
public ModelAndView getUsers(HttpServletRequest request) {
String country = "UP";
List<String> buList = employeeService.getState(country);
ModelAndView model = new ModelAndView("index");
model.addObject("buList", buList);
return model;
}
It's a question of permissions. I'd like to design my app architecture so that all the data that is accessible with current / particular authorization level (so to speak) is available on demand.
And if so, (I assume that's your case, since I don't see any further authentication in your code) it's only the question of your view design (frontend design).

Receive URL in spring

I try doing confirmation registration from email, on the email I send this code:
String token = UUID.randomUUID().toString(); //for send email
String confirmationUrl = "<a href='" +
"http://localhost:8080/registrationConfirm.html?token="
+ token+"'>Click for end Registration</a>";
helper.setText("message", confirmationUrl.toString());
I receive something like this:
http://localhost:8080/registrationConfirm.html?token=88ab5907-6ab5-40e2-89d5-d6a7e8cea3c2
How I can receive this 88ab5907-6ab5-40e2-89d5-d6a7e8cea3c2 in spring?
I want doing a new controller, he will be check if 88ab5907-6ab5-40e2-89d5-d6a7e8cea3c2 exist in DB, then he activated registration, if no - talk about misstake.
And I do not understand how the conroller will be look, I do so
#RequestMapping(value = "/token", method = RequestMethod.POST)
public #ResponseBody
String getAttr(#PathVariable(value="token") String id,
) {
System.out.println(id);
return id;
}
To complete the comment and hint Ali Dehghani has given (have a look at the answer https://stackoverflow.com/a/17935468/265043):
#RequestMapping(value = "/registrationConfirm", method = RequestMethod.POST)
public #ResponseBody
String getAttr(#RequestParam(value="token") String id) {
System.out.println(id);
return id;
}
Note that I ignored the html suffix in the request mapping annotation. You should read the docs about (default) content negotiation starting at http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-suffix-pattern-match
this another variant
#RequestMapping(value = "/registrationConfirm", method = RequestMethod.POST)
public void getMeThoseParams(HttpServletRequest request){
String goToURL = request.getParameter("token");
System.out.println(goToURL);
}

Mock MVC - Add Request Parameter to test

I am using spring 3.2 mock mvc to test my controller.My code is
#Autowired
private Client client;
#RequestMapping(value = "/user", method = RequestMethod.GET)
public String initUserSearchForm(ModelMap modelMap) {
User user = new User();
modelMap.addAttribute("User", user);
return "user";
}
#RequestMapping(value = "/byName", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public
#ResponseBody
String getUserByName(
#RequestParam("firstName") String firstName,
#RequestParam("lastName") String lastName,
#ModelAttribute("userClientObject") UserClient userClient) {
return client.getUserByName(userClient, firstName, lastName);
}
and I wrote following test:
#Test public void testGetUserByName() throws Exception {
String firstName = "Jack";
String lastName = "s";
this.userClientObject = client.createClient();
mockMvc.perform(get("/byName")
.sessionAttr("userClientObject", this.userClientObject)
.param("firstName", firstName)
.param("lastName", lastName)
).andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$[0].id").exists())
.andExpect(jsonPath("$[0].fn").value("Marge"));
}
what i get is
java.lang.AssertionError: Status expected:<200> but was:<400>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:546)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)
Why this happens? Is it right way to pass the #RequestParam
When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error
public void testGetUserByName() throws Exception {
String firstName = "Jack";
String lastName = "s";
this.userClientObject = client.createClient();
mockMvc.perform(get("/byName")
.sessionAttr("userClientObject", this.userClientObject)
.param("firstName", firstName)
.param("lastName", lastName)
).andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$[0].id").exists())
.andExpect(jsonPath("$[0].fn").value("Marge"));
}
If your problem is org.springframework.web.bind.missingservletrequestparameterexception you have to change your code to
#RequestMapping(value = "/byName", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public
#ResponseBody
String getUserByName(
#RequestParam( value="firstName",required = false) String firstName,
#RequestParam(value="lastName",required = false) String lastName,
#ModelAttribute("userClientObject") UserClient userClient)
{
return client.getUserByName(userClient, firstName, lastName);
}
If anyone came to this question looking for ways to add multiple parameters at the same time (my case), you can use .params with a MultivalueMap instead of adding each .param :
LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");
mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())
#ModelAttribute is a Spring mapping of request parameters to a particular object type. so your parameters might look like userClient.username and userClient.firstName, etc. as MockMvc imitates a request from a browser, you'll need to pass in the parameters that Spring would use from a form to actually build the UserClient object.
(i think of ModelAttribute is kind of helper to construct an object from a bunch of fields that are going to come in from a form, but you may want to do some reading to get a better definition)

create two method for same url pattern with different arguments

I have scenario where one url "serachUser" may come with two different value (request parameter) userId or UserName.
so for this I have created two methods
public String searchUserById(#RequestParam long userID, Model model)
public ModelAndView searchUserByName(#RequestParam String userName)
But i am getting Ambiguous mapping found exception. Can Spring handle this situation?
You can use the params parameter to filter by HTTP parameters. In your case it would be something like:
#RequestMapping(value = "/searchUser", params = "userID")
public String searchUserById(#RequestParam long userID, Model model) {
// ...
}
#RequestMapping(value = "/searchUser", params = "userName")
public ModelAndView searchUserByName(#RequestParam String userName) {
// ...
}
Any way incase of request param null is allowed if you don't pass any value it will be null then you can write your coad like:
#RequestMapping(value = "/searchUser", params = {"userID","userName"})
public String searchUserById(#RequestParam long userID,#RequestParam String
userName,
Model model) {
if(userID != null){
//..
}else{
// ...
}

Resources