Proper use of Spring tag library in jsp - spring

If I don't use <% # taglibprefix = "sf" uri = "http://www.springframework.org/tags/form"%>
the application works the same. The User user object is filled with the fields of the form. Is it correct to use this approach?
Is the use of <sf:form method="POST"modelAttribute="user"> more correct?
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Inserisci nuovo utente</title>
</head>
<body>
<h2>Dati utente</h2>
<form action="/SpringMVCFormHibernate/add" method="post">
<label>Cognome</label><br/><input type="text" name="cognome"/><br/>
<label>Nome</label><br/><input type="text" name="nome"/><br/>
<label>Eta</label><br/><input type="text" name="eta"/><br/><br/>
<input type="submit" value="submit"/>
</form>
<p>Visualizza utenti</p>
<sf:label path=""></sf:label>
</body>
</html>
#Controller
public class UtenteController {
#Autowired
UtenteDAO utenteDAO;
#RequestMapping(value="/add",method=RequestMethod.POST)
public String addUtente(#ModelAttribute Utente user){
utenteDAO.inserisciUtente(user);
return "index";
}//addUtente
}//UtenteController

The major use of spring:form tag is formbacking object . If you wish to bind the model attribute object with the view fields , you can go for it .
For simple form objects you can use html forms instead . Also you can make use of spring:form tags error attributes as well.
for ex,
path attribute binds the model field name . so changes made to them are can be easily updated in the server side with your model attribute.
simply they provide dyanamic binding of objects easily . spring does those instead of manual works
A nice example to understand form handling and model attribute usage.

Related

Problem in fetching multipart request in spring

I am trying to learn how to handle multi-part request in controller using spring framework/mvc.
And here I got stuck where i wanted to get 2 things from the user 1) Id and 2) pic (image file).
Therefore I had created a simple form like this.
Name:check.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="finaltest" method="post" enctype='multipart/form-data' >
id: <input type="text" name="id">
Pic: <input type="file" name="pic">
<input type="submit">
</form>
</body>
</html>
Controller file
(one of the method) which is relevant to this jsp page
#RequestMapping(path="/finaltest",method=RequestMethod.POST)
public String handlepic(#RequestParam("id")int id,#RequestBody String name) {
return "showform";
}
The Error i am getting is:
Required int parameter 'id' is not present (by tomcat)
WARNING: Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required int parameter 'id' is not present](by java console)

Image source unknown when url is returned from controller

I am new to Ui design and I am trying to write simple application using JSP and spring boot.
The idea is to get the Google QR code URL in the controller and return to JSP page:
https://chart.googleapis.com/chart?chs=200x200&chld=M%%7C0&cht=qr&chl=otpauth%3A%2F%2Ftotp%2FSpringRegistration%3Atest_user%3Fsecret%3DI2S5OTJXDG5NBWVY%26issuer%3DSpringRegistration
So, my controller looks like as below:
#GetMapping("/confirmRegistration")
public String confirmRegistration(final HttpServletRequest request,
final Model model) {
final User user = userService.getUser(token);
String qrUrl = userService.generateQRUrl(user);
log.info("QR URL: {}", qrUrl);
model.addAttribute("qr_code", qrUrl);
return "redirect:/qrcode";
}
My JSP looks like -
<!DOCTYPE html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
<title>Confirm your account</title>
</head>
<body>
<label>Scan following QR code.</label>
<c:if test="${param.url != null}">
<span> hi there </span>
${param.url}
</c:if>
<c:url value="${qr_code}" />
<img src="${qr_code}" width=256 height=256 />
<br />
<img src="${param.qr[0]}"/>
</body>
</html>
But it is not populating the image. UI page looks like below:
Can someone please help me here?
I think, the issue is related to return statement. You should point a name of your jsp page that the model with image url is forwarded to. But before, you need to define and configure InternalResourceViewResolver
For more info (redirecting / forwarding)

Type [java.lang.String] is not valid for option items

I am trying to bind a list to drop down in JSP. Below is my controller and JSP.
Controller:
#Controller
public class WeatherServiceController {
#Value("#{'${countryList}'.split(',')}")
private List<String> countries;
#ModelAttribute("CountriesList")
private List<String> getCountries(){
System.out.println(countries.size());
return countries;
}
#RequestMapping(value = "/getweather", method=RequestMethod.GET)
public ModelAndView getWeather(){
Place p = new Place();
ModelAndView mav = new ModelAndView();
mav.addObject("place",p);
mav.setViewName("home");
return mav;
}
}
JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Weather Service Client - Home</title>
</head>
<body>
<h2>Welcome to Weather Service</h2>
<form:form modelAttribute="place" action="getWeather">
<table>
<tr>
<td><form:label path="country">Country:</form:label></td>
<td>
<form:select path="country" items="${CountriesList}">
</form:select>
</td>
</tr>
</table>
</form:form>
</body>
</html>
But I am getting error like "Type [java.lang.String] is not valid for option items". Country list is not coming in jsp page. Please help me what I did wrong here.
It is working now.
I have added below line in jsp page.
<%# page isELIgnored="false" %>
I thought by default "isELIgnored" is set to false, so I haven't included earlier. After including this page is binding list result.

Flash attributes and ResourceBundleViewResolver

I am facing an issue with the flash attributes which I have not able to retrieve it in the GET phase of POST/redirect/GET scenario. This is only happening when I use the ResourceBundleViewResolver.
view resolver
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="spring-views" /> </bean>
view properties
form.(class)=org.springframework.web.servlet.view.JstlView
form.url=/WEB-INF/pages/form.jsp
home.(class)=org.springframework.web.servlet.view.JstlView
home.url=/WEB-INF/pages/home.jsp
home_redirect.(class)=org.springframework.web.servlet.view.RedirectView
home_redirect.url=home
form.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="register" method="post">
Name: <input type="text" name="name"/> <br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<h2> ${status} </h2>
</body>
</html>
so in this page, home.jsp, the status should contain the value set as the flash attribute.
controller
#Controller
public class WebController {
#RequestMapping(value="/form", method=RequestMethod.GET)
public String showFormPage(){
return "form";
}
#RequestMapping(value="/register", method=RequestMethod.POST)
public ModelAndView login(#RequestParam("name") String name, RedirectAttributes flashMap){
System.out.println("name = " + name);
flashMap.addFlashAttribute("status", "Registered successfully");
//return new RedirectView("home"); -- with this returned its working
return new ModelAndView("home_redirect"); //-- with this returned its not working
//return "redirect:home"; // -- not working
}
#RequestMapping(value="/home")
public String showHomePage(){
return "home";
}
}
on the whole this is the observation made:
if used resource bundle view resolver
return view names as string - not working
return ModelAndView - not working
return RedirectAndView - working
if used internal view resolver
return view names as string - working
2 return modelandview - cannot be used to redirect
return RedirectAndView - working

The request sent by the client was syntactically incorrect +spring

I searched for this problem and as I got it has some problems with naming conflicts, but again I could not find the reason. I would appreciate the helps. following is the line in the .jsp which calls the controller:
<td>
<a href="message/createMessage">
Reply
</a>
<input type="hidden" name="receiver" value="${message.fromUser}">
</td>
${message.fromUser} gets the required property from the model. I am sure it is not the reason for the problem because of other link in this page which works and uses the same model. The controller is as follow:
#Controller
#RequestMapping("/message")
public class MessageController
{
#RequestMapping("createMessage")
public String createMessage(
#RequestParam("receiver") String receiver,
HttpSession session,
Model model)
{
try
{
MessageDAO mDao = new MessageDAO();
Message message = new Message();
String fromUser = (String) session.getAttribute("userName");
message.setFromUser(fromUser);
message.setUserName(receiver);
Message message2 = mDao.create(message);
model.addAttribute(message);
return "newMessage";
}
catch (Exception e)
{
model.addAttribute("message", "Can't create message!");
return "redirect:/"; // ?? should add a dialog box for error
}
}
}
Thank you for your help!
as an attempt to solve the problem and based on the first answer I tried to use url-rewriting. used #PathVariable("receiver") in my controller. still the same problem. I have added the full revised jsp here: error happens when I click reply link for a message.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>welcome ${sessionScope.user.userName}</h1>
<form:form method="POST" action="message/deleteMessage">
<table border="1">
<tr>
<th>Message ID</th>
<th>From User</th>
<th>Message</th>
<th>Date</th>
<th>Reply to User</th>
<th>Delete</th>
</tr>
<c:forEach items="${messages}" var="message" >
<tr>
<td>${message.messageID}</td>
<td>${message.fromUser}</td>
<td>${message.message}</td>
<td>${message.messageDate}</td>
<td>Reply</td>
<td><input type="checkbox" name="delete" value="${message.messageID}"> </td>
</tr>
</c:forEach>
<tr><td colspan="6"><input type="submit" value="Delete selected messages"></td></tr>
</table>
</form:form>
In your "form" you have a plain html hyperlink that doesn't do any form submit(so the value of the hidden field is never being sent.
So you need to declare a <FORM action= 'message/createMessage' > element.
Then you need to either submit the form with AJAX or create a submit button. Another way is to pass receiver value manually by appending the value of the form createMessage?receiver=someValue(I added this as example I don't think it's a recommended way, everything has its pros n' cons anyway).
So there are many ways to pass the parameter.
See http://www.w3.org/TR/html401/interact/forms.html

Resources