i am new to Spring Mvc,so i have this simple question below
Code1:
#RequestMapping("/hello")
public ModelAndView hello()
{
String str="Be happy!!!!!";
return new ModelAndView("hello","message",str);
}
In hello.jsp View Page ,when i print str then i get result as ${message}
code2:
#RequestMapping("/hello")
public ModelAndView hello()
{
String str="Be happy!!!!!";
return new ModelAndView("hellopage","message",str);
}
but in hellopage.jsp i get result as Be happy!!!!!
so why above code1 does not print str string?
below is my view page jsp code and it is same for both hello.jsp and hellopage.jsp :
<%# 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">
</head>
<body>
${message}
</body>
</html>
In hello.jsp put this expression <%# page isELIgnored="false"%> at the top. Sometimes expression language automatically off for page
The EL expression doesn't get evaluated? That can have one or more of the following causes:
Application server in question doesn't support JSP 2.0.
The web.xml is not declared as Servlet 2.4 or higher.
The #page is configured with isELIgnored=true.
The web.xml is configured with true in .
In your case it looks like case no 3. Try to put isElIgnored=false in your jsp file.
Related
I tried to write my Spring Controller, using Thymeleaf, for a simple code sharing platform. So I wrote these methods
#PostMapping(value = "/api/code/new")
#ResponseBody
public String addNewCode(#RequestBody RequestCodeDTO code, Model model) {
CodeSnippet codeSnippet = new CodeSnippet();
codeSnippet.setCode(code.getCode());
codeSnippet.setDate("Jul 17, 2022");
model.addAttribute("code", codeSnippet);
return "";
}
#GetMapping(value = "/code/new")
public String returnNewCode(Model model){
return "CodeSnippet";
}
And my CodeSnippet.html is like this
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://thymeleaf.org" lang="en">
<head>
<title>Code</title>
</head>
<body>
<span id="load_date" th:text="${code.getDate()}">date</span>
<pre id="code_snippet" th:text="${code.getCode()}">code</pre>
</body>
</html>
But when I try to make this get request, I reseive "org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/CodeSnippet.html]")".
I tried to change tags of html file, change gradle build file, but it all was in vain.
I am trying to practice SAP Hybris basic flow and while hitting the URL from the controller I am getting a "server error" as the response as shown below.
The controller looks something like this:
#Controller
public class NewCustomerController {
#RequestMapping(value = "/custid", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getCustomerNameFromCustId(#RequestBody final Model model){
final List<NewCustomerData> nameList = newCustomerFacade.getCustomerNamefromID();
model.addAttribute("nameList",nameList);
return ControllerConstants.Views.Pages.NewCustomer.CustId;
}
}
The JSP page "custid.jsp" looks something like this:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="" tagdir="" %>
<html>
<head>
<title>Customer ID detail</title>
</head>
<body>
<h1>This page displays the name of the customer based on customer ID</h1>
<h3>The name of the customer is ${nameList}.<h3>
</body>
</html>
In the dao layer, when I evaluate the call to execute the query, I get this error:
Can anyone help me please what am I doing wrong? I am stuck on this since 2 days now.
How can I addObject to modelandview with modelandview parameter? I mean something like that:
ModelAndView mav = new ModelAndView();
mav.setViewName("index");
ModelAndView m = new ModelAndView();
m.addObject("test", t, '1');
mav.addObject("site", m);
I mean I have a index file witch I deal like a template and I want to parse it to other file (template)
My second question:
Is this good solution? If not, please tell me what is preffered:)
Sorry, I'm new to Java EE and Spring
edit: source code
ModelAndView is just a container used by Spring's MVC request handling. Every object you add to ModelAndView will be added as request attribute (request#setAttribute) and then available within your JSP.
Nesting ModelAndView does not make any sense. You can just forward the request from your JSP file and all the model attributes will be still set on the request and available.
Regarding your approach:
I would say that having template JSP (such as your index) can be used. I personally prefer having TAG file with layout and then JSP files being enclosed within this layout.
<%# tag language="java" description="Content border for layout decoration." trimDirectiveWhitespaces="true" %>
<!DOCTYPE html>
<html lang="cs">
<head profile="http://www.w3.org/2005/10/profile">
<meta charset="utf-8" />
</head>
<body>
<div class="pageContent">
<jsp:doBody />
</div>
</body>
</html>
-
<%# include file="/WEB-INF/taglib.jspf"%>
<layout:admin>
THIS IS MY CONTENT
</layout:admin>
Alternatively you can use templating engine such as Apache Tiles.
I'm learning how to write java servlets and jsp pages on google app engine. I'm attempting to use an MVC model but I'm not sure if I'm doing it right. Currently, I have a servlet that is called when a page is accessed. The servlet does all the processing and creates a HomePageViewModel object that is forwarded to the jsp like this:
// Do processing here
// ...
HomePageViewModel viewModel = new HomePageViewModel();
req.setAttribute("viewModel", viewModel);
//Servlet JSP communication
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("/jsp/home.jsp");
reqDispatcher.forward(req, resp);
Over on the jsp side, I have something like this:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="viewmodels.HomePageViewModel" %>
<%
HomePageViewModel viewModel = (HomePageViewModel) request.getAttribute("viewModel");
pageContext.setAttribute("viewModel", viewModel);
%>
<html>
<body>
<% out.println(((HomePageViewModel)pageContext.getAttribute("viewModel")).Test); %>
</body>
</html>
So my question is two fold. First, is this a reasonable way to do things for a small webapp? This is just a small project for a class I'm taking. And second, in the jsp file, is there a better way to access the viewmodel data?
If you adhere the Javabeans spec (i.e. use private properties with public getters/setters),
public class HomePageViewModel {
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
then you can just use EL (Expression Language) to access the data.
<%# page pageEncoding="UTF-8" %>
<html>
<body>
${viewModel.test}
</body>
</html>
See also:
Our Servlets wiki page
Our JSP wiki page
Our EL wiki page
How to avoid Java code in JSP files?
I would like to have a JSTL file of "constants" and reference them in other files.
e.g.
constants.jsp:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="colour" value="blue"/>
<c:set var="car">Audi</c:set>
Other file:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:import url="constants.jsp"/>
<p>I drive an ${car} which is ${colour}</p>
The code above (obviously) does not work. How can I get something similar to work?
Bonus points if I can use namespaces as well.
You could use an include directive:
<%#include file="/constants.jsp" %>
Or you could use a dynamic include, but then the variables would have to be stored in the request, rather than the page scope:
<jsp:include page="/constants.jsp" />
<c:set var="colour" value="blue" scope="request"/>
<c:set var="car" scope="request">Audi</c:set>
But the best way would probably be to put all these constants in an object, and store this object in the request (or session, or application) from a servlet or filter:
private class Constants {
private String color = "blue";
private String car = "Audi";
public String getColor() {
return color;
}
public String getCar() {
return car;
}
}
...
request.setAttribute("constants", new Constants());
...
<p>I drive an ${constants.car} which is ${constants.color}</p>