String is null on Thymeleaf page after adding to model - spring-boot

My controller:
#Controller
public class IndexController {
#RequestMapping(value = "/index")
public String index(Model model) {
model.addAttribute("message", "Hello World!");
return "index";
}
}
My page:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset = "ISO-8859-1" />
<link href = "css/styles.css" rel = "stylesheet"/>
<title>Spring Boot Application</title>
</head>
<body>
<h4>Spring boot.</h4>
<p th:utext="${message}"></p>
</body>
</html>
Upon loading and rendering, this HTML appears; how do I get the message to appear?
<!DOCTYPE html>
<html>
<head>
<meta charset = "ISO-8859-1" />
<link href = "css/styles.css" rel = "stylesheet"/>
<title>Spring Boot Application</title>
</head>
<body>
<h4>Spring boot.</h4>
<p></p>
</body>
</html>

Ensure you have imported the thymeleaf dependency into your project.
Use th:text="${message}"

Method in IndexController is never being called, because this:
#RequestMapping(value = "/index")
Should be this:
#RequestMapping(value = "/")

Related

Whyt Jquery ajax post does'nt work with HtmlUnit

i am using htmlunit with spring test in order to test all ihm interface from my web application. It works fine with html form (post and get) and with ajax get but i have a problem with ajax post request.
The controller don't received the request. If i replace post by get the junit test case works fine.
this the html view
<html lang="fr" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Html Unit</title>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
function postTest() {
$.ajax({
type:"post",
data: {
'subject' : 'subject test',
'message' : 'message test'
},
url:"[[#{/test/post}]]",
success: function(data, textStatus, jqXHR){
$("#result").text(data);
}
});
}
</script>
</head>
<body>
<h4 th:text="'Hello to Thymeleaf '+${myParam}">Hello from Thymeleaf</h4>
<button type="button" onClick="postTest()">Test post</button>
<div>
<span>result :</span><span id="result"></span>
</div>
</body>
and the controller
#Controller
public class WelcomeController {
#GetMapping("/")
public String init(Model model) {
model.addAttribute("myParam", "Guillaume");
return "welcome";
}
#PostMapping("/test/post")
public #ResponseBody String post(#RequestParam String subject, #RequestParam String message, Model model) {
return subject + " " + message;
}
}
you can also find the complete code on my github https://github.com/guisimon28/spring-test-htmlunit
Can you help me to find if there is some missing configuration or if its a htmlunig bug or pull request ?
Thanks for All
Guillaume

Can a _Layout.cshtml have a controller

I want to add navigation from database in _Layout.cshtml. I've created a controller for this and create _Layout.cshtml as a list view but its not working
This is my view code
#model IEnumerable<ITM_College.Models.field_tbl>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<nav>
<ul>
#foreach (var item in Model)
{
<li> #Html.DisplayFor(modelItem => item.Field_Name)</li>
}
</ul>
</nav>
Controller code
public class SharedController : Controller
{
ITMCollegeEntities db = new ITMCollegeEntities();
// GET: Shared
[ChildActionOnly]
public ActionResult _Layout()
{
var li = db.field_tbl.ToList();
return View(li);
}
}
No, but there are various ways to solve it:
1) Create base controller class or another tooling class that contains some common utilities that should be shared between your controllers.
2) PartialView and Html.RenderAction
[ChildActionOnly]
public ActionResult Something(string p)
{
var entities = repository.GetEntities(p);
var partialViewModel = new PartialViewModel(entities);
return PartialView(partialViewModel);
}

Static resource are conflicting with #PathParam in Spring boot with thymleaf localhost:8080/script.js is conflicting with localhost:8080/{message}

Main Class-
#SpringBootApplication
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Controller Class
#Controller
public class GreetingController {
#GetMapping("/{message}")
public String greeting(#PathVariable(name="message", required=false) String message, Model model) {
model.addAttribute("message", message);
return "greeting";
}
}
Html File
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="/script.js"></script>
</head>
<body>
<p th:text="'Hello, ' + ${message} + '!'" />
</body>
</html>
Script File
console.log("hi");
Index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Get your greeting here</p>
</body>
</html>
Find Screenshot of Directory Structure here
Moreover, this project reference is from https://spring.io/guides/gs/serving-web-content/ with below modification
In GreetingController instead of query param accepting parameter
through path param
Added a script file to /resources/static folder
In greeting.html added one line to include script file
Use this
<script type="text/javascript" src="/script.js"></script>
Instead of
<link href="/script.js" rel="stylesheet">
You better post full home.html file and full Controller class.
OR
Try #PathVariable instead of #PathParam . As #PathParam can use with REST only, where #PathVariable used in Spring so it works in MVC and REST.

Spring: ModelMap attributes are not shown in jsp

my data, which I try to pass from my controller to the view is apparently ignored. The console doesn't output any errors. Can somebody point me to the apparently obvious mistake I did?
Controller
#RequestMapping("/notes")
public String index(ModelMap model) {
String test = "Hello Felix";
model.addAttribute("hello", test);
return "notes";
}
View
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Notes</title>
</head>
<body>
<h1>${hello}</h1>
</body>
</html>
HTML Source
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Notes</title>
</head>
<body>
<h1></h1>
</body>
</html>
You need to return the model, something like the following should work:
Map model = ...
model.put(name, value);
return new ModelAndView(view, model);

Json response can't not be evaluated by eval

**index.jsp (client side)**
**************************************************************************************
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Techniques AJAX - XMLHttpRequest</title>
<script type="text/javascript" src="oXHR.js"></script>
<script type="text/javascript">
<!--
function request(callback) {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
alert(xhr.responseText);
var text = xhr.responseText;
var myObject = eval('(' + text + ')');
callback(myObject.Addresses);
}
};
xhr.open("GET", "jsonResponse.jsp", true);
xhr.send(null);
}
function readData(oData) {
alert(oData);
}
function getXMLHttpRequest() {
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
} else {
xhr = new XMLHttpRequest();
}
} else {
alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
return null;
}
return xhr;
}
//-->
</script>
</head>
<body>
<p>
<button onclick="request(readData);">Afficher le fichier XML</button>
<div id="output"></div>
</p>
</body>
</html>
***jsonResponse.jsp (server side)***
**********************************************************************************
<%--
Document : jsonResponse
Created on : Mar 4, 2012, 8:39:23 PM
Author : ghorbel
--%>
<%#page import="org.json.JSONException"%>
<%#page import="org.json.JSONArray"%>
<%#page contentType="text/html; charset=UTF-8"%>
<%#page import="org.json.simple.JSONObject"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%
JSONObject json = new JSONObject();
JSONArray addresses = new JSONArray();
JSONObject address;
try
{
int count = 15;
for (int i=0 ; i<1 ; i++)
{
address = new JSONObject();
address.put("CustomerName" , "Decepticons" + i);
addresses.put(i,address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
}
response.getWriter().flush();
response.setContentType("application/json");
response.getWriter().write(json.toString());
%>
</body>
</html>
The result of 'alert(xhr.responseText);' (the json return response from the server).
*************************************************************************************************
{"Addresses":[{"CustomerName":"Decepticons0"}]}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
****************************************************************************************
The problem here that the 'var myObject = eval('(' + text + ')');' cannot evaluate the json return response from the server.(the result is just above).
My question. Why the result contains these extra linges.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
</body>
</html>
when it' supposed to return just
{"Addresses":[{"CustomerName":"Decepticons0"}]}.
If someone can tell me what's wrong with the program.
I use Netbeans , Glassfish.
Thanks in advance.
As well as your code your JSP contains literal HTML. You only want the <%#page import...%> and your central code inside <% ... %> that does the work.

Resources