how can I pass attribute from sprint to scalate template? - spring

I'm learning scalate template engine. How can I pass an object (for example User) from my controller to template .ssp in my scalate template ?
my controller
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! the client locale is "+ locale.toString());
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
User user = new User("Dawid", "Pacholczyk");
model.addAttribute(user);
return "defaultTemplate";
}

Given the Spring support is implemented using a ViewResolver I guess you can pass parameters to it like this:
val response = new ModelAndView
response.addObject("user", new User)
return response
Have a look at the spring example as well.
Edit:
You need to return a ModelAndView like so:
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Locale locale, Model model) {
...
User user = new User("Dawid", "Pacholczyk");
template = new ModelAndView("defaultTemplate");
template.addObject("user", user);
return template;
}

Related

The input tag not showing in the form spring-mvc-form

So i'm trying to create a from for adding products but when i go to the url the form doesn't show any input tag only the labels
I followed this documentation : https://www.baeldung.com/spring-mvc-form-tutorial
this is the GET method
#RequestMapping(value = "/product", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("products/CreateProduct", "produit", new Produit());
}
and this is the POST method
#RequestMapping(value = "/create-product", method = RequestMethod.POST)
public String submitproduct(#Valid #ModelAttribute("produit")Produit produit,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("productID", produit.getId_produit());
model.addAttribute("productName", produit.getNom_produit());
model.addAttribute("productPrice", produit.getPrix_produit());
model.addAttribute("productDescription", produit.getDescription_produit());
model.addAttribute("productBrand", produit.getMarque_produit());
model.addAttribute("productBarCode", produit.getCodeBarre_produit());
return "products/CreateProduct";
}

Spring: How can I get value from uri?

How can the callbackFacebook function get the value of code from the uri?
uri = http://localhost:8081/callback?code=AQDNm6hezKdTsId5k4oXKNo
#RequestMapping(value = "/callback?{code}", method = RequestMethod.GET)
public String callbackFacebook(Model model, #PathVariable(name = "code") String code) {
System.out.println(code);
return "login";
}
Try this. code is a query parameter judging by your URL, not a path variable. Path variables are a part of the path itself (i.e. if your URL was something like /{code}/callback, then code is a PathVariable).
#RequestMapping(value = "/callback", method = RequestMethod.GET)
public String callbackFacebook(Model model, #RequestParam(value = "code") String code) {
System.out.println(code);
return "login";
}
If your URL is http://localhost:8081/callback?code=AQDNm6hezKdTsId5k4oXKNo then it is case of request parameters so the method will be like below.
#RequestMapping(value = "/callback", method = RequestMethod.GET)
public String callbackFacebook(Model model, #RequestParam(value = "code") String code) {
return "login";
}
If your URL is http://localhost:8081/callback/AQDNm6hezKdTsId5k4oXKNo then then it is case of path variables method will be like below.
#RequestMapping(value = "/callback/{code}", method = RequestMethod.GET)
public String callbackFacebook(Model model, #PathVariable(value = "code") String code) {
return "login";
}
Refer requestparam-vs-pathvariable for better clarity.
I will explain 2 ways.
1-If it is added in the session in somewhere in the project as attribute,You can get it like this :
#RequestMapping(value = "/callback?{code}", method = RequestMethod.GET)
public String callbackFacebook(Model model, #PathVariable(name = "code") String code,HttpServletRequest request) {
String code1 = request.getSession().getAttribute("code").toString();
return "login";
}
example output : AQDNm6hezKdTsId5k4oXKNo
2-You can directly get URL.But then you need to parse URL.Because all URL is coming.
#RequestMapping(value = "/callback?{code}", method = RequestMethod.GET)
public String callbackFacebook(Model model, #PathVariable(name = "code") String code,HttpServletRequest request) {
StringBuffer requestURL = request.getRequestURL();
return "login";
}
example output : http://localhost:8081/callback?code=AQDNm6hezKdTsId5k4oXKNo

#requestparam value = date spring boot

#Controller
#RequestMapping(value="/reservations")
public class ReservationController {
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
#Autowired
private ReservationService reservationService;
#RequestMapping(method = RequestMethod.GET)
public String getReservation(#RequestParam(value="date", required=false) String dateString, Model model){
Date date = null;
if(dateString != null){
try {
date = DATE_FORMAT.parse(dateString);
} catch (ParseException pe) {
date = new Date();
}
}else{
date = new Date();
}
List<RoomReservation> roomReservationList = this.reservationService.getRoomReservationsForDate(date);
model.addAttribute("roomReservations", roomReservationList);
return "reservations";
}
}
I understand that the #RequestParam annotation is used to bind parameter values of query string to the controller method parameters. So for example, http://localhost:8080/reservations?date=2017-01-01. However, where does the value="date" come from? I dont see any value "date" inside my html page.
if you submit a form as method:"GET" (not POST) and form contains a input field named date then submitting this form will hit this handler method.

Share #ModelAttribute between methods

I'm new on spring and I have this controller:
#ModelAttribute("mediaJson")
#Transactional(value=CLIENT_TRANSACTION_MANAGER, readOnly=true)
public String getPlayerMedia(#PathVariable String playerHash, #PathVariable String mediaId) throws ServiceException, JsonProcessingException {
PlayerController playerController = new PlayerController();
playerController = authenticationService.authenticatePlayerHash(playerHash);
PlayerMediaDTO media = playerService.getPlayerMedia(playerController, mediaId, null, null, null);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(media);
return json;
}
#ModelAttribute("attrs")
public ViewAttributes getProxyPath(#ModelAttribute("mediaJson") String jsonString) {
ViewAttributes attr = new ViewAttributes();
attr.setProxy(proxy);
attr.setDescription(jsonString);
return attr;
}
//View
#RequestMapping(value="/index/{playerHash}/{mediaId}", method=RequestMethod.GET)
public String loadMediaJson(#PathVariable String playerHash, #PathVariable String mediaId, ModelMap model) {
return "index";
}
Notice that I'd like to access the mediaJson attribute to the attrs Attribute to populate it. How can I do that?
I've tried here but it seems that it works only if I put a debug breakpoint on the setDescription line ( probably because of sync ).
Can anyone help me with it?

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