Spring MVC : how do I show data from DAO classes - java

I have a DAO java class that has a method called getTableFromDatabase(), it queries the MySQL and return resultTable, a hashmap of data. I want to use this hashmap and print the content in my jsp page using Spring MVC, how should I do this?
I know that I can use JSTL to print a table, my problem is how to pass this table from DAO to jsp page.
Thanks !

In spring mvc you have to return a ModelAndView class and this class will carry corresponding jsp file and parameters will be passed to jsp.
For example
In your controller request handler method you will return an instance of ModelAndView
#RequestMapping(...)
public ModelAndView handle(){
ModelAndView ret = new ModelAndView("view name");
ret.addAttribute("x","value");
}
in your jsp you can access to x via ${x} syntax.
Spring mvc document reference:
public ModelAndView addObject(Object attributeValue) Add an attribute
to the model using parameter name generation. Parameters:
attributeValue - the object to add to the model (never null) See Also:
ModelMap.addAttribute(Object), getModelMap()
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/ModelAndView.html

Related

Data comes repeaitively from databse to JSP on refreshing the page with RequestMethod.GET

I am trying to pass data from DAO to JSP using ModelMap. It works but, when I refresh that page, same data comes repeatedly on every refresh. I want data not to come again and again on refreshing the page. Help me for this issue.
#Autowired
private SelectInfo selectInfo; /* Instance of SelectInfo DAO class injected here, here the method of fetching data from databse is defined and fetched data is passed to GetInfo bean*/
#Autowired
private GetDetail getDetails; /* GetDetail is the bean where the values are stored which are coming from database */
#RequestMapping(value="/selectInfo", method=RequestMethod.GET)
public String registerComplete(ModelMap model,HttpSession session,HttpServletResponse res) {
if(session.getAttribute("user")==null) {
return "redirect:/";
}else {
selectInfo.getInfo(); /*getInfo is the method defined in SelectInfo class which fetch data from database*/
/* the values are adding in modelmap using getter method from GetInfo bean */
model.put("cities", getDetails.getCities());
model.put("theaters", getDetails.getTheaters());
model.put("movies", getDetails.getMovies());
model.put("dates", getDetails.getDates());
model.put("timings", getDetails.getTimings());
return "cities";
}
So you do not want call your db each time when page refreshes? I think you can try caching in that case. Please take a look at example here: https://spring.io/guides/gs/caching/
You can just add annotation on your controller method.
#RequestMapping(value="/selectInfo", method=RequestMethod.GET)
#Cacheable
public String registerComplete(ModelMap model,HttpSession session,HttpServletResponse res) {
//your code goes here
}
If you are passing the data using modelMap means, data will be transferred each time a page load or refreshed. In order to load the data once use ajax and sessionStorage
Create new method in controller class to return data like this
#RequestMapping(value="/cities", method=RequestMethod.GET)
public #ResponseBody Object registerComplete(){
return getDetails.getCities()
}
In javascript check the sessionStorage if its null then load the data using ajax.
$(document).ready(function(){
if(sessionStorage.cities ==null){
$.ajax({
type : 'GET',
url : "/cities",
contentType:'application/json',
data:JSON.stringify(data),
success : function(response) {
sessionStorage.cities =response;
}
});
}
}) ;
By this you can restrict data load on each refresh
Caching is the natural way to avoid unnecessary trips to database. Spring provides support for this using #Cacheable annotation.
If you are using Spring Boot, things are easier for you. Ensure that you have got spring-boot-starter-cache in your dependencies or one of your spring starters depends on spring-boot-starter-cache. Then you can annotate your DAO method like so:
#Component
public class SelectInfo {
...
#Cacheable("dbInfo")
public <returnType> getInfo() {
// Implementation of the method
}
...
}
Putting the Cacheable annotation over the method in your DAO is advised since it is responsible for fetching the actual data that you want to cache.
If you are not using Spring Boot, you'll have to include a Cache Provider and configure a bean for that provider. The details of how to do this can be found in the Spring Caching Docs https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-caching.html#boot-features-caching-provider

Spring MVC Controller misunderstanding

Code from a controller:
#Controller
public class HomeController {
#Autowired
private ItemService itemService;
#RequestMapping("/home")
public String showHomePage(Map<String, Object> model) {
model.put("items", itemService.getItems());
return "home";
}
}
And a part of the correspondent home.jsp:
<c:forEach items="${items}" var="item">
${item}
</c:forEach>
In a browser I get elements that are returned from itemService.getItems().
How Spring finds out that model map contains values to be request attributes?
Does the DispatcherServlet copy contents of all parameters of type Map to request attributes?
Yes, Spring MVC copies all the parameters from model to HttpServletRequest object. The reason why Spring people chosen not to use the HttpServeltRequest directly, is due to the requirement that they want to be as independent from the view technologies as possible, so being able to drive the view technologies that don't depend on the HttpServeltRequest
Exposing the model as request parameters is a facet of view, and you'll find the appropriate code if you check out the source of SpringMVC's InternalResourceView which extends from AbstractView that holds the exposeModelAsRequestAttributes method

How do get the list from #ResponseBody in JSP?

I use Spring MVC, I have controller with a method:
#RequestMapping(value = "/listReader", method = RequestMethod.POST)
public #ResponseBody
List<Reader> getListReader(ModelMap model) {
return libraryService.getAllReaders();
}
But I do not know:
How can use list (that I get from method getListReader by #ResponseBody) in JSP?
How can I get list in JSP?
How do to display a list in JSP-page?
How do to get the list from #ResponseBody in JSP?
Give an example, please.
You can't. #ResponseBody is basically telling Spring: take the object I (method) return and use any serializer you have that supports it and write it directly to the body of the HTTP response. There's no JSP involved here.
Instead you should add the list to the model and return the String view name of your JSP.
#RequestMapping(value = "/listReader", method = RequestMethod.POST)
public String getListReader(ModelMap model) {
model.addAttribute("someKey", libraryService.getAllReaders());
return "my-jsp";
}
then you can use EL in the JSP to retrieve it
<h3>${someKey}</h3>
Use JSTL to iterate over it.
#RequestMapping(value = "/listReader", method = RequestMethod.POST)
That defines an Endpoint.
I would suggest using RequestMethod.GET than RequestMethod.POST, since you want something from the server not POSTING something to the server.
On the other Hand, if you want to use that information on a JSP, there are two ways:
1) Some view could consume that information via a http-GET-Request like $.get in jQuery or ajax. After you got the data, you can insert it in your HTML
2) Instead of using ajax you could display it directly on the page.
Then, you have to put your List into a Model, which you can acces on your JSP with Expression Language. Then you have to remove the #ResponseBody and return an according view instead.

Spring MVC URL for the AbstractController

I have a controller that inherits from the org.springframework.web.servlet.mvc.AbstractController class
I have configurated it in this way:
<bean name="/gameServiceController.json" class="xx.xxx.GameController"/>
so can accepts url of this form
http://<hostname>:<port>/<context-path>/gameServiceController.json
but the customer has provided to me the requirement to write URL in this way
http://<hostname>:<port>/<context-path>/createNewGame?parameter=<value>
but I think that is not possible to map this type of URL with my controller. Anyone know the type of configuration that can be used in order to configure this type of URL mapping ?
Otherwise, is legal to ask to change the format of the URL in this way
http://<hostname>:<port>/<context-path>/gameServiceController.json?command=createNewGame&phoneNumber=<phoneNumber>
so I can manage the command parameter in the "handleRequestInternal" method of my custom controller that inherits from the org.springframework.web.servlet.mvc.AbstractController class ??
Don't use the legacy Controller framework, use annotated controllers. There, you can easily use URL templates, something like this:
#Controller
public class GameController{
#RequestMapping(value="/createNewGame?parameter={param}",
method=RequestMethod.GET)
public String createNewGame(#PathVariable String param, Model model) {
// do stuff here
return "viewName";
}
}

Access Model object in a JSP without using the ModelAndView object?

I am using spring mvc with Annotations, see the following snippet
#RequestMapping(value = "/configuration/", method = RequestMethod.GET)
public MyModel viewConfiguration() {
The problem I am having accessing the 'MyModel' class in my JSP.
How can I do this, without using the ModelAndView object?
This shorthand syntax means that MyModel becomes a model attribute named myModel (i.e. class name with the first letter decapitalized).
View name is inferred from the URL.
See also:
15.3.2.3 Supported handler method arguments and return types
15.10.3 The View - RequestToViewNameTranslator
You could set MyModel as a request attribute to be accessed in your JSP. I'm curious, why don't you want to use ModelAndView? After all, it does what you want to do here, which displays the view and provides a container to hold your objects you want to reference in your view.
By the way, if this is an Ajax call, you will need to add #ResponseBody to the API so that your javascript can read the response in the callback function:-
#RequestMapping(value = "/configuration/", method = RequestMethod.GET)
public #ResponseBody MyModel viewConfiguration() {
...
}

Categories

Resources