Spring: printing variables in jsp page - spring

I have been trying out Spring framework and while trying to print java-class attributes in jsp file I have hit a little snag. While trying to print the date to my page I get nothing. I know there is a value in the variable as I can see it in the console but on the page there is nothing. Here is my index.jsp where the value should be shown:
<!-- contains taglibraries -->
<%# include file="/WEB-INF/jsp/include.jsp" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Hello :: Spring Application</title>
</head>
<body>
<h1>Hello - Spring Application</h1>
<h2>Testing tags</h2>
<p> <c:out value="If you see this then C-tag works."/> </p>
<h2>Testing values brought from controller. One should see a date after "now".</h2>
<p>Greetings, it is now <c:out value="${now}"/></p>
</body>
</html>
And here is my indexController.java:
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class IndexController implements Controller{
protected Log logger = LogFactory.getLog(getClass());
#Override
public ModelAndView handleRequest(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
String now = (new Date()).toString();
logger.info("Returning hello view and " + now);
return new ModelAndView("WEB-INF/jsp/index.jsp" , "now" , now);
}
}
Could someone point out what is it I am doing wrong? Oh and just to clarify: the "include.jsp" contains all my taglibraries so missing taglibrary like this:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
Is not a problem as
the first c-tag on the index.jsp works. The problem is the second c-tag with the variable "now" which refuses to show.

<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
not including that in your jsp

Related

Why model.addAttribute and ${} is not matching and it shows just . on web?

I just started to learn jsp and spring. I deleted formattedDate (as a default) in HomeController.java and changed to model.addAttribute("answer", "yes") and on web, it only shows . and i don't understand why.
I tried to put definition like String answer = "yes" but it didnt work.
this is HoneController.java:
#Controller
public class HomeController {
#RequestMapping("/main")
public String home(Locale locale, Model model) {
model.addAttribute("answer", "yes");
return "home";
}
}
and here is home.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" pageEncoding="UTF-8" %>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>
hello
</h1>
<P> Is it happening? : ${answer}. </P>
</body>
</html>
There was no error messages

Property [id] not found on type [java.util.Optional]

I am trying to perform crud operation with spring boot and i am new to it. I have successfully performed delete and create part. The problem i am having when i am trying to edit my fields. I am using MYSQL as my database. I am having error mentioned in question title. Any help to resolve it and please check my logic i think my logic is wrong in /showUpdate method. When i press edit button then it is not taking me to edit page and throwing me this error.
My controller class is pasted below:
Snapshot of Actual error i am having
package com.bilal.location.controllers;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.bilal.location.entities.Location;
import com.bilal.location.service.LocationService;
#Controller
public class LocationController {
#Autowired
LocationService service;
#RequestMapping("/showCreate")
public String showCreate() {
return "createLocation";
}
#RequestMapping("/savLoc")
public String saveLocation(#ModelAttribute("location") Location location,ModelMap modelMap) {
Location locationSaved = service.saveLocation(location);
String msg = "Location saved with id: " + locationSaved.getId();
modelMap.addAttribute("msg", msg);
return "createLocation";
}
#RequestMapping("/displayLocations")
public String displayLocations(ModelMap modelMap) {
List<Location> locations = service.getAllLocations();
modelMap.addAttribute("locations", locations);
return "displayLocations";
}
#RequestMapping("/deleteLocation")
public String deleteLocation(#RequestParam("id")int id,ModelMap modelMap) {
Location location = new Location();
location.setId(id);
service.deleteLocation(location);
List<Location> locations = service.getAllLocations();
modelMap.addAttribute("locations", locations);
return "displayLocations";
}
#RequestMapping("/showUpdate")
public String showUpdate(#RequestParam("id")int id,ModelMap modelMap) {
Optional<Location> location = service.getLocationById(id);
modelMap.addAttribute("location", location);
return "updateLocation";
}
#RequestMapping("/updateLoc")
public String updateLocation(#ModelAttribute("location") Location location,ModelMap modelMap) {
service.updateLocation(location);
List<Location> locations = service.getAllLocations();
modelMap.addAttribute("locations", locations);
return "displayLocations";
}
}
Display Location JSP Page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#page isELIgnored="false" %>
<!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>Display Locations</title>
</head>
<body>
<h2>Locations:</h2>
<%--Table Starting from here --%>
<table>
<tr>
<th>id</th>
<th>code</th>
<th>name</th>
<th>type</th>
</tr>
<c:forEach items = "${locations}" var="location" >
<tr>
<td>${location.id}</td>
<td>${location.code}</td>
<td>${location.name}</td>
<td>${location.type}</td>
<td>delete</td>
<td>edit</td>
</tr>
</c:forEach>
</table>
<%--Table Ending here --%>
Add Location
</body>
</html>
Update Location JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#page isELIgnored="false" %>
<!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>Create Location</title>
</head>
<body>
<form action="updateLoc" method="post">
<pre>
id: <input type="text" name="id" value = "${location.id}" readonly/>
code: <input type="text" name="code" value = "${location.code}"/>
name: <input type="text" name="name" value = "${location.name}"/>
type: rural <input type ="radio" name="type" value ="RURAL" ${location.type=='URBAN'?'checked':'' }/>
Urban <input type ="radio" name="type" value= "URBAN" ${location.type=='RURAL'?'checked':'' }/>
<input type="submit" name="save"/>
</pre>
</form>
</body>
</html>
Read the error message carefully. It says you are trying to acces .id, but not on your Location, but on an Optional instead - which doesn't have that property.
Check your code:
#RequestMapping("/showUpdate")
public String showUpdate(#RequestParam("id")int id,ModelMap modelMap) {
Optional<Location> location = service.getLocationById(id);
modelMap.addAttribute("location", location);
return "updateLocation";
}
You are not adding the location, but an Optional that might contain the location.
You can check whether an Optional holds a value by calling ìsPresent(), e.g.
if (location.isPresent()) {
modelMap.addAttribute("location", location.get());
} else {
// ERROR?
}
More on Optional, if you are not familiar: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
In my case it was solve by
In controller
ModelAndView modelAndView = new ModelAndView();
Optional<Employee> employee = employeeRepository.findById( employeeDto.getId());
if (employee.isPresent()) {
modelAndView.addObject("employeeDto", employee.get());
System.out.println(employee);
} else {
System.out.println("Error Found"); // error message
}
In views

$() not working in jsp file

I have a Controller called Leave Controller which looks as follows.
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class LeaveController {
#RequestMapping("/")
public ModelAndView loginPage()
{
return new ModelAndView("jsp/login.jsp", "command", new Employee());
}
#RequestMapping(value="verify" ,method=RequestMethod.POST)
public String verify(Employee eform,ModelMap model)
{
System.out.println(EmployeeAccessService.verify(eform));
model.addAttribute("uname",eform.getName());
model.addAttribute("pass",eform.getPassword());
return "jsp/home.jsp";
}
}
The method login.jsp page sends an Employee pojo received as 'eform'. I add the two attributes to (ModelMap)model before going to home.jsp page.
Here is my home.jsp page.
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>Home</title>
</head>
<body>
$(uname)<br>
$(pass)
</body>
</html>
The thing is the $(uname) and $(pass) are displayed as text instead of variables. How do I display them as variables?
It's not $(), it's ${}:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>Home</title>
</head>
<body>
${uname}<br>
${pass}
</body>
</html>

I wonder connection between spring form tag & controller #RequestMapping() method

This jsp file 'selectDetail.jsp' for client inputs their information
and clicks 'update' button to 'update.do'
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# 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=UTF-8">
<title><spring:message code="member.detail.title" arguments="${member.id}"/></title>
</head>
<body>
아이디 : ${member.id}<br>
비밀번호 : ${member.passwd }<br>
이름 : ${member.name }<br>
날짜 : ${member.reg_date }<br>
목록보기 |
update |
삭제 |
</body>
</html>
'UpdateController.java' is get 'update.do' command by '#RequestMapping'.
first, 'updateForm() is worked. b/c of method is get. go to 'updateForm.jsp'
package dr.mini.controller;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import dr.mini.dao.MemberDao;
import dr.mini.domain.MemberCommand;
import dr.mini.validator.MemberValidator;
#Controller
public class UpdateController {
private Logger log = Logger.getLogger(this.getClass());
#Autowired
private MemberDao memberDao;
public void setMemberDao(MemberDao memberDao) {
this.memberDao = memberDao;
System.out.println("UpdateController의 setMemberDao()호출");
}
//1) Get방식: value(요청명령어), method(방식종류)
#RequestMapping(value="/update.do", method=RequestMethod.GET)
public ModelAndView updateForm(#RequestParam("id") String id){
MemberCommand memberCommand = memberDao.getMember(id);
System.out.println("1updateForm()");
return new ModelAndView("updateForm", "memberCommand", memberCommand);
}
//2) Post방식
#RequestMapping(value="/update.do", method=RequestMethod.POST)
public String submit(MemberCommand memberCommand, BindingResult result){
if(log.isDebugEnabled()){
log.debug("3memberCommand="+memberCommand);
}
MemberValidator mv = new MemberValidator();
System.out.println("validate 실행 전 ");
mv.validate(memberCommand, result);
System.out.println("validate 실행 후 ");
if(result.hasErrors()){
System.out.println("updateForm()으로 페이지 이동");
return "updateForm";
}
memberDao.updateMember(memberCommand);
return "redirect:/list.do";
}
}
'updateForm.jsp' outputs memberCommand information. client changes his infomation. He clicks '보내기' button. then go for 'UpdateController.java' again to call 'submit()'
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# 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=UTF-8">
<title><spring:message code="member.update.title"/></title>
</head>
<body>
<h2>레코드 수정</h2>
<form:form commandName="memberCommand">
<form:errors element="div"/>
아이디 : ${memberCommand.id}<br>
비밀번호 : <form:password path="passwd" showPassword="false"/><font color="red"><form:errors path="passwd"/></font><br>
이름 : <form:input path="name"/><font color="red"><form:errors path="name"/></font> <br>
<input type="submit" value="보내기">
</form:form>
</body>
</html>
everyone,
I don't know how to call submit(). when client clicked '보내기' button with no 'update.do' path. Where is it to add this path.

Controller to write contents or msg varaibles to specific iframe

I am using an JSP page which has two iframe, one of the iframe in the left pane shows the link's and iframe in the right pane is the display window, when I click on the link in the left iframe, the controller is called, to display the content in the right pane/iframe, but it always display the content in the same pane/left pane/left iframe itself, how to display the contents in the right iframe/display window.
refer to the picture for more details
showMessage
<!DOCTYPE html>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<link rel="stylesheet" type="text/css"
href="/LDODashBoard/css/mystyle.css" />
<title>L1 DashBoard page</title>
</head>
<body>
<iframe id="mainContent" src="/LDODashBoard/L1SrcLinkPage.htm" height="500" width=20% scrolling="no">Main</iframe>
<iframe id="displayContent" src="/LDODashBoard/L1OutputDisplayPage.htm" height="500" width=70% scrolling="no">Content</iframe>
<h2>${message}</h2>
</body>
</html>
MainController
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.validation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.security.UrlAuthenticationSuccessHandler;
import org.apache.log4j.Logger;
/*
* author: Crunchify.com
*
*/
#Controller
public class MainController {
static Logger log = Logger.getLogger(MainController.class.getName());
#RequestMapping("/showMessage")
public ModelAndView helloWorld() {
System.out.println("inisde showmessage method");
log.info("inisde showmessage method");
String message = "<br><div style='text-align:center;'>"
+ "<h3>********** Welcome to LDO Support Landing page **********<h3> </div><br><br>";
return new ModelAndView("showMessage", "message", message);
}
#RequestMapping(value = "/L1SrcLinkPage")
public String srcLinkMethod(HttpSession session) {
log.info("inside srcLinkMethod method");
// session.invalidate();
return "L1SrcLinkPage";
}
#RequestMapping(value = "/L1OutputDisplayPage")
public String srcOutputDisplayMethod(HttpSession session) {
log.info("inside L1OutputDisplayPage method");
// session.invalidate();
return "L1OutputDisplayPage";
}
#RequestMapping(value = "/gcmmLink1", method = RequestMethod.GET)
public ModelAndView gcmmLink1(Model model, HttpServletResponse response) {
log.info("inisde gcmmLink1 method");
String message = "<br><div style='text-align:center;'>"
+ "<h3>********** Showing the output of gcmmLink1 **********<h3> </div><br><br>";
return new ModelAndView("L1OutputDisplayPage", "message", message);
}
#RequestMapping(value = "/gcmmLink2", method = RequestMethod.GET)
public ModelAndView gcmmLink2() {
log.info("inisde gcmmLink2 method");
String message = "<br><div style='text-align:center;'>"
+ "<h3>********** Showing the output of gcmmLink2 **********<h3> </div><br><br>";
return new ModelAndView("L1OutputDisplayPage", "message", message);
}
}
L1SrcLinkPage.jsp
<!DOCTYPE html>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
<c:url value="/gcmmLink1" var="messageUrl1" />
<a href="${messageUrl1}" >GCMM process check!!</a> <br>
<c:url value="/gcmmLink2" var="messageUrl2" />
GCMM second process check!!
</body>
</html>
L1OutputDisplayPage.jsp
<!DOCTYPE html>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
solution:
<!DOCTYPE html>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<script type="text/javascript">
function doSomething(UrlValue){
var ifrm = parent.document.getElementById('displayContent');
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
alert (doc.getElementById("h1").innerHTML);
doc.getElementById("h1").innerHTML = "hello, changing the value";
var urlString = "/LDODashBoard/L1OutputDisplayPage?" + UrlValue + "=true";
alert (urlString);
ifrm.contentWindow.location.href = urlString;
}
</script>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
<c:url value="/L1OutputDisplayPage?gcmmLink1=true" var="messageUrl1" />
GCMM process check!! <br>
<c:url value="/L1OutputDisplayPage?gcmmLink2=true" var="messageUrl2" />
GCMM second process check!!
</body>
</html>

Resources