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

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

Related

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.

How to Send image using org.apache.velocity.VelocityContext for email

MimeMessagePreparator mimeMessagePreparator=new MimeMessagePreparator() {
#Override
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper mimeMessageHelper=new MimeMessageHelper(mimeMessage);
mimeMessageHelper.setTo(requestQuotationPojo.getEmailId().toString());
mimeMessageHelper.setFrom("vikasglobaljapan#gmail.com");
mimeMessageHelper.setText("Your Request Quotation Number"+requestQuotationPojo.getRfqId());
mimeMessageHelper.setSubject("Request Quotation Details");
VelocityContext velocityContext = new VelocityContext();
requestQuotationPojo.setImage(new StringBuffer(application_url.concat(requestQuotationPojo.getImage().toString())));
requestQuotationPojo.setRfqId(new StringBuffer(rfqId));
velocityContext.put("image", requestQuotationPojo.getImage());
velocityContext.put("rfqDetails", requestQuotationPojo);
velocityContext.put("image",application_url.concat(requestQuotationPojo.getImage().toString()));
StringWriter stringWriter = new StringWriter();
velocityEngine.mergeTemplate("com/gjcp/dao/daoImpl/customer/templateName.vm", "UTF-8", velocityContext, stringWriter);
mimeMessageHelper.setText(stringWriter.toString(), true);
}
template.vm
<!doctype html>
<html lang="en">
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<table style="width:100%">
  <tr>
    <th>Product Name</th>
    <th>Quote Number</th>
    <th>Image</th>
<th>Quantity</th>
  </tr>
<tr>
<td>${rfqDetails.productName}</td>
<td> ${rfqDetails.rfqId}</td>
<td><img src="${rfqDetails.image}" border="0" width="50" height="50"></td>
<td>${rfqDetails.quantity}</td>
</tr>
</table>
</body>
</html>
I suppose that your image is a byte array. So you should add image to velocity context as base64 string.
velocityContext.put("image", Base64.encode(requestQuotationPojo.getImage()));
And use this img tag in your template file.
<img src="data:image/jpg;base64,${image}" border="0" width="50" height="50"/>
${websitename} : Write Your website name.
${rfqDetails.image} : your image path.
Like Your image url: http://test.com/folder/abc.png
#set($imgsrc="http://${websitename}/${rfqDetails.image})
<img width="50" src="$imgsrc" border="0" height="50" alt="test">

Search page in spring mvc doesn't work

I Have created simple mvc CRUD. All works fine except search page.
Im getting errorr as follows:
HTTP Status 500 - Request processing failed; nested exception is org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
Controller page is:
#RequestMapping(value="/search")
public ModelAndView search(){
return new ModelAndView("search","command", new Emp());
}
#RequestMapping(value="/jsp/searchemp",method = RequestMethod.POST)
public ModelAndView search1(#ModelAttribute("name") Emp emp){
String name = null;
name = dao.searchname(name);
return new ModelAndView("searchemp","name",name);
}
Search.jsp:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>z
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
label {
text-align: right;
clear: both;
float:left;
margin-right:15px;
}
.box{background-color: #e1e8f0;}
body{background:#f0eceb;}
</style>
</head>
<body>
<div style=" left: 30%; top: 25%; position: absolute;">
<div class="col-sm-12 col-sm-offset-3 box " >
<center> <h1>Add New Employee</h1> </center>
<form method="post" action="jsp/searchemp/" >
<div class="form-group"> <div class="col-xs-7">
<label ><h5>Name :</h5></label>
<input name="name" class="form-control" placeholder="Enter Name of the employee" />
<button type="submit" value="Save" class="btn btn-primary btn-lg">Search</button>
</div></div>
</form>
</div>
</div>
</body>
</head>
Searchemp.jsp:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Employees List</h1>
<table class="table table-hover" border="1" width="70%" cellpadding="2">
<thead>
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</th><th>Edit</th><th>Delete</th></tr></thead>
<tbody><tr>
<td>${String.id}</td>
<td>${String.name}</td>
<td>${emp.salary}</td>
<td>${emp.designation}</td>
<td>Edit</td>
<td>Delete</td>
</tr> </tbody>
</table>
<br/>
Add New Employee
jdbctemplate query:
public String searchname(String name) {
String query = "select * from Emp99 where name=?";
Object[] inputs = new Object[] {name};
String empName = template.queryForObject(query, inputs, String.class);
return empName;
}
Dont know what goes wrong.
help me.
in order for jsp to consume an bean , your controller method should return data,in your jsp you are trying to utilize
{String.id} and {emp.id} which is never passed from the controller method search1.so you need to add your beans to a model and
return the page like this.
#RequestMapping(value="/jsp/searchemp",method = RequestMethod.POST)
public String search1(#ModelAttribute("name") Emp emp,Model model){
model.addAttribute("emp",emp); //passing the model name and the bean ,
//model.addAttribute("name",anotherBean); //you can add many attributes as you wish.
return "searchemp";
}
now inside the searchemp.jsp you can utilize the emp bean like this.
{emp.id}
remove the {String.id} part. inside the searchemp.jsp which will not work.

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

Issue in Spring MVC serving static resources

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/"/>

Resources