Design to fetch DB data and load in jsp while application starting - java

We just started our development using jsp's and spring mvc framework. Looking for a good approach to load data from DB and save all the jsp page data into DB. Here is the brief description:
As there is no login details yet decided, When I start my application, this loads my jsp page which we are working on. This jsp page contains 4 to 5 sections. Each and every section requires some preloaded data which should come from DB.
We need to load and display this data while loading the jsp page itself.
Once the jsp page is loaded with all the pre-populated values from DB, there will be other fields where user enter some data and finally Save this jsp page.
I have around 8 to 9 drop-down lists in jsp which should get loaded from DB. How I can load all this data while loading the page ? Can I load all this data once from db and put it as part of one object and display as part of jsp ?
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView visitHome(HttpServletRequest request,
HttpServletResponse response) throws IOException {
System.out.println("Testing purpose");
return new ModelAndView("first");
}
As we are using Spring MVC framework here, I am redirecting from jsp to controller as above, and then to service then to DAO then to DB. How I can include all the DB loading logic as part of above method ?
Please suggest. Thanks in advance.

You can create some pojos and return pojos with model and view. Assume that you have class SectionData and you want to set some data to it and return it with view.
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView visitHome(HttpServletRequest request,
HttpServletResponse response) throws IOException {
SectionData sectionData = new SectionData();
sectionData.setName("John Citizen");
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("firstSectionData", sectionData);
modelAndView.setViewName("first");
return modelAndView;
}
And then you can bind jsp elements with section data such as
My name is ${firstSectionData.name}
Now the HTML page will show "My name is John Citizen".

Related

How to get variables from one Spring MVC Controller to Another

I m novice to spring mvc. Could you please help me to design below.
I have newly written Controller A which is bind with model attribute “attribA” And new jsp is customerInformation.
Now I have existing Controller B which is bind with model attribute “attribB” and jsp is existing customerSummary which I will modify as per requirement where I want to display contents set by the user on previous jsp in model attribA.
How can I pass content or attributeA from new Controller A in an existing controller Controller B to show on second jsp customerSummary
Thank You
you can do this by using "RedirectAttributes"
#PostMapping("/userWiseNewMenuPermission")
public ModelAndView setUserWiseNewMenuPermission(ModelAndView modelAndView,RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("comfmMassg","Menu Permission Save Successful!");
modelAndView.setViewName("redirect:/userList?page=1");
return modelAndView;
}
in this Post controller redirect to a get controller with a attribute name "comfmMassg" ......
#GetMapping("/userList")
public ModelAndView getMenu(ModelAndView modelAndView,#ModelAttribute("comfmMassg") String masg) {
modelAndView.addObject("masg", masg);
modelAndView.setViewName("userList");
return modelAndView;
}
this example work in spring boot ............

How to Redirect/Forward data from Spring MVC Controller to other page as POST?

I'm working on a project which is a mix Spring MVC and coldfusion, I want to know how to redirect from the SpringMVC Controller to the cfm using a POST request.
I have this mapping defined
#RequestMapping(value = "/preprocess", method = {RequestMethod.GET})
public ModelAndView doPreprocess(HttpServletRequest request, #RequestParam Map<String, String> params, HttpSession session) {
//retrieve some parameters from db and redirect/forward here to "/postprocess.cfm"
}
After retrieve some parameters, I need to redirect/forward those parameter to other endpoint "/postprocess.cfm", this page reads the params from a form, so the request to this page needs to be a POST
Looking forward to your help. Thanks a lot!

Can I configure both HTML and Spring Data REST JSON on the same URI?

I am writing a web application with Spring MVC.
Keeping with REST principles, I am wanting to use consistent URIs in my application for the same resources and to use content negotation to select whether to return HTML or JSON. Visiting /people/bob in a browser should show his profile page, and getting it with curl should give me a JSON representation.
However, because of a semantic limitation (bug?) in the RequestMappingHandlerMapping, I can't "fall through" to the generic Spring Data REST mappings if I define any explicit controller, such as an HTML controller, on a matching URI. Besides manually implementing a #RestRepositoryController for every matching HTML controller, is there any other simple way to make Spring MVC content-negotiate between HTML and JSON mappings?
Example mapping that doesn't work:
#BasePathAwareController
class PersonHtmlController {
#GetMapping(path = '/people/{id}', produces = 'text/html')
ModelAndView person(#PathVariable Person id) {
new ModelAndView('person', [person: id])
}
}
This produces the expected HTML output but returns a 406 Not Acceptable when I ask for JSON.
You can go for contentnegotiatingviewresolver. Following is an example.
#RequestMapping(value = "/users", method = RequestMethod.GET)
public ModelAndView userDetails() {
ModelAndView modelAndView = new ModelAndView();
List userDetails = userService.getUserDetails();
modelAndView.addObject("users", userDetails);
modelAndView.setViewName("userDetails");
return modelAndView;
}
So whenever a request comes with /users then html page will be served and when the request comes as /users.json then a JSON response will be generated.
You can configure it in following way by overriding following method by extending WebMvcConfigurerAdapter provided by Spring.
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/jsp/", ".jsp").viewClass(JstlView.class);
registry.enableContentNegotiation(
new MappingJackson2JsonView()
);
}
Hope this helps.
Reference:
contentnegotiating view resolver example

Passing $routeParams from angularjs to spring-MVC controller

This is what I have in my AngularJs controller
.when("/M:topicId", {templateUrl: "Mu", controller: "conMFs"})
app.controller('conMFs',function($scope,$routeParams){
$scope.otherId = $routeParams.topicId;
});
This is my Spring Controller
#RequestMapping(value="/controlerM", method = RequestMethod.GET)
public ModelAndView controlerM(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = null;
session=request.getSession(true);
user = (User) session.getAttribute("user");
List<ends1> ends=(List<ends1>) ifriendlistservice.getends(user.getId(),5);
session.setAttribute("MutualFriends", MutualFriends);
model = new ModelAndView("ends");
return model;
I am able to fetch the topicId from my AngularJS page in AngularJS controller (with $scope.otherId), however I am unable to pass this value to my Spring controller, from where I am redirecting to new page.
How should I do this?
.when("/M:topicId", {templateUrl: "Mu", controller: "conMFs"})
app.controller('conMFs',function($window){
$window.location.reload();
});
Then server app gets topicId from request's url. You also need to have $locationProvider.html5Mode enabled.
How should I do this?
You shouldn't. Angular's off-hour job is to not let server apps to reload the page. The code above is quick-and-dirty, it can be ok only if you're in the middle of Angular integration into existing project, but the time-frame requires you to partially rely on old code base.
If you really need to make a redirect (e.g. to external page), make an AJAX request, put topicId and whatever there, get redirect url in response, redirect with $window.location.href.
I'm barely familiar with Spring, but the above applies to any server-side application.
Thanks estus,
Issue seems to be resolved...
I had created 2 controller in Spring, One for setting parameter through ajax , and other for redirection.

Browser back button getting in to GET method of Spring MVC Controller instead of checking the cache

I am using Spring MVC 2.5. I have get and post methods for all the pages I have.
#RequestMapping(value = "/offer", method = RequestMethod.GET)
public ModelAndView getOffer(ModelMap model, HttpSession session) {
//code
return new ModelAndView(OFFER_SETTING_PAGE, model);
}
#RequestMapping(value = "/offer", method = RequestMethod.POST)
public ModelAndView postOffer(ModelMap model, #ModelAttribute("investorsEligiblitySetting")
//code
return new ModelAndView("redirect:/servlets/ProcessAction/privateplacement/createoffer/additionalinformation");
}
After passing the post method and displaying the next jsp file, when I try to hit the back button , instead of displaying the previous data from the cache (which is what I am looking for) it gets in to the get method of the specified url and causes some problems.
How can I make my application to look for cache first instead of getting in to a get method?
This is an old question, but I found this post that gives some ideas as to how to prevent the browser from resubmitting on the back button. You could also set something in your form when you handle the POST that the GET handler can look at to see if the POST already ran.

Categories