THis is my first page
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="newjstl.jsp" method="post">
FirstName:<input type="text" name="fname"/><br/>
LastName:<input type="text" name="lname"/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
The second page is
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach var='value' items='${paramValues}'>
First Name:<c:out value="${value.fname}"></c:out><br/>
Last Name:<c:out value="${value.lname}"></c:out>
</c:forEach>
It is throwing an exception org.apache.jasper.JasperException: javax.el.PropertyNotFoundException: The class 'java.util.HashMap$Entry' does not have the property 'fname'.
I don't know why it is not working.
See http://docs.oracle.com/javaee/1.4/tutorial/doc/JSPIntro7.html#wp71044.
paramValues is the map of parameters. It maps parameter names (the keys of the map) to their values (array of String).
You're iterating over this map. The forEach loop thus iterates over the entries of the map, which are of type Map.Entry<String, String[]>. And Map.Entry doesn't have any getFname() method.
What you actually want is
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
First Name:<c:out value="${param.fname}" /><br/>
Last Name:<c:out value="${param.lname}" />
There's no reason to loop, and you simply want to get the single value of a given parameter. That'w what param is for.
JB Nizet has it correctly.
Assume that 'fname' was set to "George", and 'lname' was set to "Smith" in 'first page'.
'paramValues' is a HashMap, so when you use it in 'forEach', what you're getting in 'value' is a Map.Entry, and Map.Entry doesn't have a 'fname' field, so there's no 'getFname' method for JSP to call.
If you insist, 'value' can be used as '${value.key}' and '${value.value}', but that will get you the pairs :
'fname', "George"
'lname', "Smith"
respectively. I doubt that's what you want. The only reason to use a 'forEach' would be if you were expecting multiple answers and needed to iterate through all of them. That's not what's been given as the example.
The following was copied from Implicit Objects, and shows pretty much what I suggest above.
<%-- For every String[] item of paramValues... --%>
<c:forEach var='parameter' items='${paramValues}'>
<ul>
<%-- Show the key, which is the request parameter
name --%>
<li><b><c:out value='${parameter.key}'/></b>:</li>
<%-- Iterate over the values -- a String[] --
associated with this request parameter --%>
<c:forEach var='value' items='${parameter.value}'>
<%-- Show the String value --%>
<c:out value='${value}'/>
</c:forEach>
</ul>
</c:forEach>
To pass parameters to a jsp jstl:
/* JSP PARENT */
<jsp:include page="../../templates/options.jsp">
<jsp:param name="action" value="${myValue}"/>
</jsp:include>
/* JSP CHILD (options.jsp)*/
<div id="optionButtons left">
<span>${param.action}</span>
</div>
Because the fields in your form aren't named the same, you can't use 'forEach' tag. I think this will work!
First Name:${param.fname}
Last Name:${param.lname}
Related
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)
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)
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.
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
Is it possible to get the model, that current view has used for rendering, in the onSubmit() method?
I somehow want to "redirect the model" that was given to the current view from another controller by return
new ModelAndView("searchResults", "model", myModel)
You can make a form reference any attribute and submit to any servlet/controller using something like :
Incldue tags
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
create url var
<c:url var="myURL" value="/ANywhere/whatever" />
define form something like
<form:form name="myForm" id="myForm" action="${myUrl}" method="POST" modelAttribute="yourAttribue">
<form:input path="firstname" />