How to load data of home page in spring mvc - ajax

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).

Related

How to pass model data from one controller to another controller spring

I have my controller-A class like this:
#PostMapping("/otp")
public String otpSubmit(#RequestParam("token") String token, HttpSession session, Model model) throws IOException {
Long enrollment = (Long) session.getAttribute("enrollment");
BaseResponse otpResponse = otpRestClient.validateOTP(enrollment, token);
if(otpResponse.getCode().equals("1020")) {
model.addAttribute("object", otpResponse.getPayload());
return "redirect:/password";
}
model.addAttribute("errorCode", otpResponse.getCode());
model.addAttribute("errorMessage", otpResponse.getMessage());
return "/otp";
}
What I want is simple (I think) pass the model.addAttribute("object", otpResponse.getPayload()); to controller-B class so I can access that data in the other view.
How can I inject this into controller-B class?.
By adding redirectAttributes we can pass model data
Here is the Controller one.
public String controlMapping1(
#ModelAttribute("mapping1Form") final Model model,
final RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("mapping1Form", model);
return "redirect:mapping2";
}
Here is Controller2
public String controlMapping2(
#ModelAttribute("mapping1Form") final Model model) {
model.addAttribute("transformationForm", model);
return "view_name";
}
you can save this "Object o = otpResponse.getPayload()" object in a global variable so later you can access it from any controller.

how to have many objects or models in one form with spring mvc

i have to use one form for two modelAttributes : "groupes" which is a list of Groupe and "matieres" is a list of Matiere, i know that one form support only one modelAttribute , i tried two options but both doesn't work,one by using spring bind tag and the other one by wrapping groupes and matieres in one class,
Any ideas how to solve this ?
#RequestMapping(method = RequestMethod.GET)
public ModelAndView showForm() {
ModelAndView mv = new ModelAndView("abs");
mv.addObject("matiere", matiereservice.findAlmatieres());
mv.addObject("groupe", groupeservice.findAllGroupes());
return mv;
}
#RequestMapping( method = RequestMethod.POST)
public String submitForm( #ModelAttribute("groupe") Groupe groupe, #ModelAttribute("matiere") Matiere matiere,
ModelMap map,
BindingResult result
) {
// BindingResult treatment
return "listeleve" ;
}
Instead of sending those attributes separately, simply make a DTO class which contains List fields of both of your Groupe and Matiere classes.
public class ListeleveDTO {
private List<Groupe> groupe;
private List<Matiere> matiere;
public ListeleveDTO(List<Groupe> groupe, List<Matiere> matiere) {
// Assign to fields
}
// getters and setters
}
And set the instance of this class as a model attribute.
#RequestMapping(method = RequestMethod.GET)
public ModelAndView showForm() {
ModelAndView mv = new ModelAndView("abs");
mv.addObject("listeleveDTO", new ListeleveDTO(groupeservice.findAllGroupes(), matiereservice.findAlmatieres());
return mv;
}
#RequestMapping( method = RequestMethod.POST)
public String submitForm( #ModelAttribute("listeleveDTO") ListeleveDTO,
ModelMap map,
BindingResult result
) {
// BindingResult treatment
return "listeleve" ;
}

ModelAndView thread-saftey Spring Boot web app

Is using the ModelAndView in this manner "thread-safe"? The UserToken bean passed on the constructor is session-scoped and proxied, so each user should be accessing their own token, right? Or is using the same ModelAndView for all requests overwriting the UserToken each time for every user, thus possibly causing user A to see user B's token?
#Controller
public class ViewController {
private final UserToken userToken;
private final ModelAndView mav;
#Value("${redirect.url}")
String redirectUrl;
#Autowired
public ViewController(UserToken userToken) {
this.userToken = userToken;
this.mav = new ModelAndView();
}
#RequestMapping("/")
public ModelAndView defaultView() {
return getModelAndView("home");
}
#RequestMapping("/entryPoint")
public ModelAndView accessDenied(#RequestParam(required=false) String token) {
userToken.deserialize(token);
mav.addObject("userToken", userToken);
return getModelAndView("redirect:/");
}
/**
* Handle redirect if the userToken is invalid
* #param viewName The view to map
* #return the ModelAndView
*/
private ModelAndView getModelAndView(String viewName) {
if (userToken.isValid()) {
mav.setViewName(viewName);
} else {
mav.setViewName("redirect:" + redirectUrl);
}
return mav;
}
}
Not even sure how to test for thread-safety in this scenario, so any insight would be appreciated (techniques, tools, etc.).

Spring MVC Using #RequestMapping on controller class with variable

I would like to write whole controller to work with entity.
I would like to declare the id of entity on class level and use it on each method. Here is the controller class:
#Controller
#RequestMapping(value="/job/{j_id}/instance")
public class JobController extends GenericController {
private final String htmlDir = "job/";
#RequestMapping(value="{i_id}/open", method=RequestMethod.GET)
public ModelAndView open(#PathVariable Long instance_id) {
ModelAndView result = new ModelAndView(htmlDir + "instance");
result.addObject("instance_id", instance_id);
Here I would like to use variable j_id from #RequestMapping
return result;
}
}
Can I achive this? Please help. Give me some code snippest please.
Have a try like this
#Controller
#RequestMapping(value="/job/{j_id}/instance")
public class JobController {
private final String htmlDir = "job/";
#RequestMapping(value="{i_id}/open", method=RequestMethod.GET)
public ModelAndView open(#PathVariable(value="j_id") Long instance_id) {
ModelAndView result = new ModelAndView(htmlDir + "instance");
result.addObject("instance_id", instance_id);
System.out.println("Instance Id -------------> " + instance_id);
return result;
}
}
Please notic "#PathVariable(value="j_id")"
To get both variables, you can change that line as following:
#RequestMapping(value="{i_id}/open", method=RequestMethod.GET)
public ModelAndView open(#PathVariable(value="j_id") Long jnstance_id, #PathVariable(value="i_id") Long instance_id) {
.....
}

Influence on performance of using 'private static final' strings in Spring 3 REST controller

I'm working on REST API based on Spring 3 MVC. In each call I'm adding to JSON response two variables: 'description' and 'result'.
For example:
#RequestMapping(value = "entity.htm", method = RequestMethod.GET)
public ModelAndView get() {
ModelAndView mav = new ModelAndView(JSON_VIEW);
mav.addObject("description", "entity list");
mav.addObject("result", someService.getAll());
return mav;
}
Does it make sense for performance of the app to create a pool of private static final strings and use them every time I need?
I mean like this:
#Controller
public class MyController {
private static final String JSON_VIEW = "jsonView";
private static final String VAR_DESCRIPTION = "description";
private static final String VAR_RESULT = "result";
private static final String DESC_CREATED = "entity created";
private static final String DESC_ENTITY_LIST = "entity list";
private static final String DESC_ACCESS_DENIED = "forbidden";
#RequestMapping(value = "entity.htm", method = RequestMethod.PUT)
public ModelAndView put(HttpServletResponse response) {
ModelAndView mav = new ModelAndView(JSON_VIEW);
if (!entityService.someChecking()) {
mav.addObject(VAR_DESCRIPTION, DESC_ACCESS_DENIED);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
} else {
mav.addObject(VAR_DESCRIPTION, DESC_CREATED);
mav.addObject(VAR_RESULT, entityService.save(new Entity()));
response.setStatus(HttpServletResponse.SC_CREATED);
}
return mav;
}
#RequestMapping(value = "entity.htm", method = RequestMethod.GET)
public ModelAndView get(HttpServletResponse response) {
ModelAndView mav = new ModelAndView(JSON_VIEW);
if (!entityService.someChecking()) {
mav.addObject(VAR_DESCRIPTION, DESC_ACCESS_DENIED);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
} else {
mav.addObject(VAR_DESCRIPTION, DESC_ENTITY_LIST);
mav.addObject(VAR_RESULT, entityService.getAll());
}
return mav;
}
// and so on
}
Someone of these statuses I use only once, but DESC_ACCESS_DENIED I use up to 10 times in one REST controller.
Your get is not returning json, it returns a view.
I prefer using an enum instead of static final ints - easier to add functionality later.
Yes, it does make sense. It's a good pratice. It save's you time and effort if you ever need to change this values. It's quite insignificant in terms of memory use or process time, but it's better.
If you intend to use those strings more than once, then it is a good pratice to turn then into static final. But notice your methods aren't returning JSON responses. A JSON response is something like that:
#RequestMapping(value = "/porUF", method = RequestMethod.GET)
public #ResponseBody List<Municipio> municipios(
#RequestParam(value = "uf", required = true) String uf) {
if ( uf.length() != 2) {
return null;
}
return municipioBO.findByUf(uf);
}
The #ResponseBody annotation will transform the List into a JSON object, and the response of a HTTP GET for that is something like that:
[{"codigo":9701,"uf":{"uf":"DF","nome":"DISTRITO FEDERAL"},"nome":"BRASILIA "}]
This is a JSON response.

Resources