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
Related
I am trying to bind a list to drop down in JSP. Below is my controller and JSP.
Controller:
#Controller
public class WeatherServiceController {
#Value("#{'${countryList}'.split(',')}")
private List<String> countries;
#ModelAttribute("CountriesList")
private List<String> getCountries(){
System.out.println(countries.size());
return countries;
}
#RequestMapping(value = "/getweather", method=RequestMethod.GET)
public ModelAndView getWeather(){
Place p = new Place();
ModelAndView mav = new ModelAndView();
mav.addObject("place",p);
mav.setViewName("home");
return mav;
}
}
JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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>Weather Service Client - Home</title>
</head>
<body>
<h2>Welcome to Weather Service</h2>
<form:form modelAttribute="place" action="getWeather">
<table>
<tr>
<td><form:label path="country">Country:</form:label></td>
<td>
<form:select path="country" items="${CountriesList}">
</form:select>
</td>
</tr>
</table>
</form:form>
</body>
</html>
But I am getting error like "Type [java.lang.String] is not valid for option items". Country list is not coming in jsp page. Please help me what I did wrong here.
It is working now.
I have added below line in jsp page.
<%# page isELIgnored="false" %>
I thought by default "isELIgnored" is set to false, so I haven't included earlier. After including this page is binding list result.
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.
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>
I am facing an issue with the flash attributes which I have not able to retrieve it in the GET phase of POST/redirect/GET scenario. This is only happening when I use the ResourceBundleViewResolver.
view resolver
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="spring-views" /> </bean>
view properties
form.(class)=org.springframework.web.servlet.view.JstlView
form.url=/WEB-INF/pages/form.jsp
home.(class)=org.springframework.web.servlet.view.JstlView
home.url=/WEB-INF/pages/home.jsp
home_redirect.(class)=org.springframework.web.servlet.view.RedirectView
home_redirect.url=home
form.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">
<title>Insert title here</title>
</head>
<body>
<form action="register" method="post">
Name: <input type="text" name="name"/> <br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<h2> ${status} </h2>
</body>
</html>
so in this page, home.jsp, the status should contain the value set as the flash attribute.
controller
#Controller
public class WebController {
#RequestMapping(value="/form", method=RequestMethod.GET)
public String showFormPage(){
return "form";
}
#RequestMapping(value="/register", method=RequestMethod.POST)
public ModelAndView login(#RequestParam("name") String name, RedirectAttributes flashMap){
System.out.println("name = " + name);
flashMap.addFlashAttribute("status", "Registered successfully");
//return new RedirectView("home"); -- with this returned its working
return new ModelAndView("home_redirect"); //-- with this returned its not working
//return "redirect:home"; // -- not working
}
#RequestMapping(value="/home")
public String showHomePage(){
return "home";
}
}
on the whole this is the observation made:
if used resource bundle view resolver
return view names as string - not working
return ModelAndView - not working
return RedirectAndView - working
if used internal view resolver
return view names as string - working
2 return modelandview - cannot be used to redirect
return RedirectAndView - working
what should i download for working with validation in spring.know annotations are unknown in my classes for example in blow code:
public String register2( #Valid User user , BindingResult br)
{
if(br.hasErrors())
{
return "edit";
}
//System.out.println("you registers!");
return "thanks";
}
#valid is unknown .which library should i download for work with jsr-303 standard in spring mcv?and where should i download?
and how i setup that in eclipse helious?
thanks
EDIT:MY CODE APPENDED=>
my controller=>
package codes;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.Validator;
import org.apache.jasper.tagplugins.jstl.core.Out;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.BindingResultUtils;
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.portlet.ModelAndView;
#org.springframework.stereotype.Controller
public class Controller {
#RequestMapping(value="/register/" , method=RequestMethod.GET)
public String register(Model model)
{
model.addAttribute("myUser",new User());
return "edit";
}
#RequestMapping(value="/register/" , method=RequestMethod.POST)
public String register2( ModelAndView model,#Valid User myUser , BindingResult br)
{
try
{
if(br.hasErrors())
{
return "edit";
}
else
{
System.out.println(myUser);
System.out.println(myUser.getName());
System.out.println(myUser.getFamily());
System.out.println("salam");
return "thanks";
}
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
return "thanks";
}
}
my edit.jsp page(form)=>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!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>Register</title>
</head>
<body>
<div>
<sf:form method="post" modelAttribute="myUser" >
<label for="USER_NAME">name:</label>
<sf:input path="name" id="USER_NAME"/>
<sf:errors path="name" ></sf:errors>
<br>
<label for="USER_FAMILY">family:</label>
<sf:input path="family" id="USER_FAMILY"/>
<br>
<input type="submit" value="REGISTER" />
</sf:form>
</div>
</body>
</html>
NOTE:only when my user object is invalide i get exception and when thatz valid i give not exeption
You can use Hibernate Validator.
To run it, you need to add these jars to your project:
hibernate-validator*.jar
validation-api*.jar
slf4j-api*.jar
You can find all of them in the Hibernate Validator package.