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

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

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.

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.

Spring MVC : Jsp file does not display data from the controller

This is my controller code
#RequestMapping(value="/testMvc")
public String testero(Model model ){
String nameClient="HENOCKE";
Long CodeClient=2L;
String Address="LONDO Street";
System.out.println("****End and outputting to Jsp page: ****");
return "rs";
}
And as you can see i want to display data to my jsp files and this is my jsp file:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="f"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" charset=UTF-8>
<title>Banque </title>
<link rel="stylesheet" type="text/css"
href="<%=request.getContextPath()%>/resources/CSS/style1.css">
</head>
<body>
<h2>Date Loaded from My controller....</h2>
<table>
<tr>
<th>Name : </th> <th><c:out value="${nameClient}"/></th>
</tr>
<tr>
<th>id Client: </th> <th> <c:out value=" ${CodeClient}" /> </th>
</tr>
<tr>
<th>Adress client: </th> <th> <c:out value="${Address}" /></th>
</tr>
</table>
</body>
</html>
How can i output data to my jsp? here rs is the Name of my Jsp file
You need to add the attributes to the model.
String nameClient = "Whatever";
model.addAttribute("nameClient",nameClient);
Read this:
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/mvc.html
You should create ModelAndView object to put values to view:
#RequestMapping(value="/testMvc")
public ModelAndView testero(){
ModelAndView mov = new ModelAndView("rs");
mov.addAttribute("nameClient", "HENOCKE");
mov.addAttribute("CodeClient", 2L);
mov.addAttribute("Address", "LONDO Street");
System.out.println("****End and outputting to Jsp page: ****");
return mov;
}

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