The request sent by the client was syntactically incorrect +spring - 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

Related

404 error,not displaying view content in jsp java spring boot

so I have some JSP views in my Spring Boot code, one of them which I have a problem with is showInfo.jsp:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: PC
Date: 02.05.2022
Time: 15:20
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--#elvariable id="banner" type="java.util.List<pl.coderslab.entity.Banners>"--%>
<%--#elvariable id="rent" type="java.util.List<pl.coderslab.entity.Rents>"--%>
<c:forEach var = "banners" items="${banner}">
<table>
<tr>
<th>Street</th>
<th>Price</th>
<th>is Rented</th>
<th>rented from</th>
<th>rented until</th>
</tr>
<tr>
<td>${banners.street}</td>
<td>${banners.price}</td>
<td>${banners.is_rented}</td>
<td>${banners.rents.rented_from}</td>
<td>${banners.rents.rented_until}</td>
</tr>
<td><input type="submit" value="Wstecz"></td>
</table>
</c:forEach>
</body>
</html>
I also have dashboard.jsp:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: PC
Date: 02.05.2022
Time: 15:20
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Dashboard</h1>
<br>
<table>
<tr>
<th>Banners</th>
<th>Localization</th>
</tr>
<%--#elvariable id="banners" type="java.util.List<pl.coderslab.entity.Banners>"--%>
<c:forEach var="banner" items="${banners}">
<tr>
<td>Banner</td>
<td>${banner.street}</td>
<td><a href="http://localhost:8080/dashboard/info/${banner.id}" >Wiecej informacji</a></td>
<td> <a href="http://localhost:8080/dashboard/edit/${banner.id}" >Edytuj </a></td>
<td> <a href="http://localhost:8080/dashboard/delete/${banner.id}" >Usun </a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
The problem is when I click on one of hrefs, it redirects but I have 404 error "Not found". But I have controller to every href, for example showInfo controller:
#RequestMapping(value = "/dashboard/info/{id}", method = RequestMethod.GET)
public String showInfo(Model model, #PathVariable("id") int id){
List<Banners> banners = bannerDao.getBannerById(id);
model.addAttribute("banner", banners);
return "showInfo";
}
#RequestMapping(value = "/dashboard/info/{id}", method = RequestMethod.POST)
public String info(){
return "redirect:/dashboard";
}
I don't know what is problem here. I have #RequestMapping's, all properties and dependencies are included.

how to make group of radio buttons in spring form?

i am creating a quiz application where i want to group options in a radio button list after fetching options from database. My code is below so that one option from optionList of Question object is selected seprately.
i want to list group of questions and their options in a single page options with their relative questions .if i select option of one question i should be able to select another option of another question. how do i seprate radio buttons for each questions???
#Controller
public class ApiController {
#Autowired
private QuestionRepository qr;
#Autowired
private OptionRepository or;
#Autowired
private ActivitiesCrudRepository acr;
#RequestMapping("/questions")
public String ShowQuestions(#ModelAttribute("questions") Question question) {
return "questions";
}
#RequestMapping("/save")
public String save(#ModelAttribute("questions") Question question) {
qr.save(question);
return "questions";
}
#RequestMapping("/pq")
public String playQuiz(Model m, #ModelAttribute("questions") Question qsn) {
Iterable<Question> q = qr.findAll();
System.out.println(q);
m.addAttribute("q", q);
return "play-quiz";
}
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page isELIgnored="false"%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form:form action="play" modelAttribute="questions">
<c:forEach var="temp" items="${q}">
${temp.qsn_Name}<br>
<c:forEach var="temp1" items="${temp.options}">
<form:radiobuttons path="options[0].name" value="${temp1.name}"
items="${????????????}" />
<br>
</c:forEach>
<br>
</c:forEach>
<input type="submit" value="submit">
</form:form>
</body>
</html>
When using using the taglib function form:radiobuttons you don't need to iterate over the options you want in the radiobutton group.
You can replace
<c:forEach var="temp1" items="${temp.options}">
<form:radiobuttons path="options[0].name" value="${temp1.name}"
items="${????????????}" />
<br>
</c:forEach>
with
<form:radiobuttons path="options[0].name" items="${temp.options}" />
Be aware of the difference between form:radiobutton which create one single button and form:radiobuttons which creates the whole group.
See f.x. https://www.tutorialspoint.com/springmvc/springmvc_radiobuttons.htm or https://mkyong.com/spring-mvc/spring-mvc-radiobutton-and-radiobuttons-example/for more examples.

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.

spring mvc error 400:The request sent by the client was syntactically incorrect

I have method in controller of spring mvc project :
//download resume
//----------------------------------------------------------------------
//#RequestMapping(value="/download/{fileName}",method=RequestMethod.GET)
#RequestMapping(value="/downlo",method=RequestMethod.GET)
public void downloadPDFResource(HttpServletRequest request,
HttpServletResponse response){
// #PathVariable("fileName") String fileName) {
//If user is not authorized - he should be thrown out from here itself
String fileName="Ente Kadha - Madhavikkutty.pdf";
//Career c=cardao.retrieveProfile(a_id);
//c.setA_id(a_id);
//String fileName=c.getResumeDoc();
System.out.println("filename i got :"+fileName);
//Authorized user will download the file
String dataDirectory = request.getServletContext().getRealPath("/WEB-INF/downloads/");
Path file = Paths.get(dataDirectory, fileName);
if (Files.exists(file)) {
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
try {
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}
else
{
System.out.println("\n\nFile not found!!\n\n");
System.out.println(file);
}
}
This code actually works.The file download is successful When i send request to the above controller,from the below given jsp page :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!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>Hello</title>
</head>
<body>
<center>
<h3 name="fileName">Ente Kadha - Madhavikkutty.pdf</h3>
<h2>Click here to download the file</h2>
</center>
</body>
</html>
But when a request to download goes to the same controller,from a different jsp page,which is given below :
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF8">
<title>Profile</title>
</head>
<body>
<table>
<th><h3>${profile.name}</h3></th>
<tr>
<td>Application Id :</td>
<td>${profile.a_id}</td>
</tr>
<tr>
<td>Name :</td>
<td>${profile.name}</td>
</tr>
<tr>
<td>Address :</td>
<td>${profile.address}</td>
</tr>
<tr>
<td>Email:</td>
<td>${profile.email}</td>
</tr>
<tr>
<td>Phone:</td>
<td>${profile.phone}</td>
</tr>
<tr>
<td>Vacancy id:</td>
<td></td>
</tr>
<tr>
<td>Date Applied :</td>
<td>${profile.dateApplied}</td>
</tr>
<tr>
<td>Resume : ${profile.resumePath}${profile.resumeDoc} </td>
<td>Click here to download the file</td>
</tr>
</table>
</body>
</html>
But now,this gives me an error:
HTTP Status 400 -
type Status report
message
description The request sent by the client was syntactically
incorrect.
Apache Tomcat/8.0.3
I am really confused why this error occurs?!!
The way i request is same,controller method is same,even the file to be downloaded is the same in both cases!!
still the error occurs.Can anyone help me?
pls....
Based on the info posted in your question (and comments) I suppose the following:
In your controller the downloadPDFResource method is listening to the url: /downlo. If your controller has no other #RequestMapping annotation on its class definition, this means that the download URL is accessible from the root of your application, e.g.: localhost:8084/IntelliLabsWeb/downlo. Can you confirm this?
Since you are using relative links in your <a> tags, for the first case the file happens to be in the root of your application hence the <a> tag point to the correct download url: localhost:8084/IntelliLabsWeb/downlo
But, in the second case, your file probably resides inside a subfolder most probably named oneProfile and the relative link of the <a href> tag points to localhost:8084/IntelliLabsWeb/oneProfile/downlo, which is not served from the downloadPDFResource method hence you get an error 400.
Try to change your second link to
Click here to download the file

paramValues not working in JSTL and throwing an exception?

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}

Resources