Issue in Spring MVC serving static resources - spring

I am running the Spring application with JQuery. But the application is not running. After the JQuery function is called the application is not working. For example please refer the below image, the alert('name') after the $('#name').val(); is not working.
Can any one please tell why it is not working?
I have added the JQuery file in js folder in WebContent.
And for importing the jquery i used the
<script src="/AjaxWithSpringMVC2Annotation/js/jquery.js"></script>
in JSP page.
Here's the full JSP source:
<%# 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>Add Users using ajax</title>
<script src="/AjaxWithSpringMVC2Annotation/js/jquery.js"></script>
<script type="text/javascript">
function doAjaxPost() {
// get the form values
alert('doAjaxPost ');
var name = $('#name').val();
alert('name ');
var education = $('#education').val();
alert('education ');
$.ajax({
type : "POST",
url : "/AjaxWithSpringMVC2Annotation/AddUser.htm",
data : "name=" + name + "&education=" + education,
success : function(response) {
// we have the response
$('#info').html(response);
$('#name').val('');
$('#education').val('');
},
error : function(e) {
alert('Error: ' + e);
}
});
}
</script>
</head>
<body>
<h1>Add Users using Ajax ........</h1>
<table>
<tr>
<td>Enter your name :</td>
<td><input type="text" id="name"><br /></td>
</tr>
<tr>
<td>Education :</td>
<td><input type="text" id="education"><br /></td>
</tr>
<tr>
<td colspan="2"><input type="button" value="Add Users"
onclick="doAjaxPost()"><br /></td>
</tr>
<tr>
<td colspan="2"><div id="info" style="color: green;"></div></td>
</tr>
</table>
<a href="/AjaxWithSpringMVC2Annotation/showUsers.htm">Show All
Users</a>
</body>
</html>

You might want to add a resource handler for the path js/**. See 17.15.6 Configuring Serving of Resources.
#Configuration
#EnableWebMvc
public class SpringConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
}
or in XML:
<mvc:resources mapping="/js/**" location="/js/"/>

Related

Why is the string not added to the property via Model.addObject?

I created #ControllerAdvice to handle BindException:
#ControllerAdvice
class globalControllerAdvice {
#ExceptionHandler(BindException.class)
public ModelAndView handleMyException(HttpServletRequest req, Exception e) {
ModelAndView model = new ModelAndView();
model.addObject("myerror",e.getErrCode());
model.addObject("message",e.getMessage());
model.addObject("exception","bind exception");
model.setViewName("error");
return model;
}
}
And created error.html :
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handing Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
table td{
vertical-align:top;
border:solid 1px #888;
padding:10px;
}
</style>
</head>
<body>
<h1>Error Page</h1>
<table>
<tr>
<td>Error</td>
<td th:text="${myerror}"/>
</tr>
<tr>
<td>Message</td>
<td th:text="${message}"/>
</tr>
<tr>
<td>Exception</td>
<td th:text="${exception}"/>
</tr>
</table>
</body>
</html>
And when executing, when I make a mistake on purpose, the page appears normally,but the properties are not filled in .That is, a table is created, but the text "${myerror}" , "${message}" , "${exception}" are not filled in with e.getErrCode() , e.getMessage() ,
"bind exception". Can anyone tell me what the problem is? thanks

Thymeleaf can't see For-each variable

Here is my Service ( It just gets a list of entities )
#Service
public class ProcedureService {
#Autowired
ProcedureRepository procedureRepository;
public List getProceduresList() {
List<Procedure> procedureList;
procedureList = procedureRepository.findAll();
return procedureList;
}
}
Here is my Controller. It just puts list he gets to view.
#Controller
public class ServicesController {
#Autowired
ProcedureService procedureService;
#GetMapping("/services")
public String getCustomer(Model model) {
List<Procedure> procedures = procedureService.getProceduresList();
model.addAttribute("procedures", procedures);
return "services";
}
}
And here is my real problem. Thyme leaf just doesn't see the entity in a List ( it sees the list though ). Here is my screen and full code of View
<!DOCTYPE html>
<html lang="en">
<head>
<title>SpringMVC + Thymeleaf + Bootstrap 4 Table Example</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Customer Table</h1>
<div class="row col-md-7 table-responsive">
<table id="customerTable" class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Street</th>
<th>Postcode</th>
</tr>
</thead>
<tbody>
<tr th:each="procedure: ${procedures}">
<td th:text="${procedure.}" />
<td th:text="${procedure.getId}" />
</tr>
</tr>
</tbody>
</table>
</div>
</div>
I forgot about html lang="en" xmlns:th="http://www.thymeleaf.org" in html so th wasn't really working.

Request method 'POST' not supported | SPRING BOOT

I'm trying to mount a simple start menu and I get an error in the POST method when I press the submit button.
My controller with the post method called by the submit in html with value "login"
#Controller
#RequestMapping("usuario")
public class UsuarioControlador {
#Autowired
private UsuarioServicio usuarios;
#RequestMapping(method=RequestMethod.GET )
public String index(ModelMap modelMap){
modelMap.put("usuario",new Usuario());
return "usuario/index";
}
//#PostMapping("/login")
#RequestMapping(value="login",method=RequestMethod.POST)
public String login(#ModelAttribute("usuario")Usuario usuario,HttpSession session,ModelMap modelMap){
if(usuarios.findByUserId(usuario.getIdUsuario())!=null){
session.setAttribute("informacion", usuario.getInformacion());
return "usuario/welcome";
}else{
modelMap.put("error", "Usuario no valido");
return "usuario/index";
}
}
}
My index.html with the submit call "login"
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form th:action="#{/usuario/login}"
th:objects="${usuario}" method="post">
<table cellpading="2" cellspacing="2">
<tr>
<td>Usuario</td>
<td><input type="text" th:field="*{idUsuario}" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="login" /></td>
</tr>
</table>
<br/>
<span th:text="${error}"></span>
</form>
</body>
</html>
You have to configure the #RequestMapping tag, to match with the form action /usuario/login, the slash sign its missing.
Replace
#RequestMapping("usuario")
with
#RequestMapping("/usuario")
And Replace
#RequestMapping(value="login",method=RequestMethod.POST)
with
#RequestMapping(value="/login",method=RequestMethod.POST)

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

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;
}

Resources