Hello everyone thanks for helping alot people all over the world.
Guys I try for two past days just simply pass attributes between request methods in my cntroller, tried alot's of different ways, but nothing happend. I have bean CreationDate and I need fill up by form properties in that bean and simply render them on my second page. I see in my url bar in browser that it's passing(cuz I do GET method for passing) but it's nothing appears on second page just blank list.
My controller class:
#Controller
public class HomeController{
private static final long serialVersionUID = 4825408935018763217L;
#SuppressWarnings("unused")
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private ControllerSupportClass controllerSupportClass;
public void setControllerSupportClass(
ControllerSupportClass controllerSupportClass) {
this.controllerSupportClass = controllerSupportClass;
}
#RequestMapping(value ="/index", method=RequestMethod.GET)
public String index(Model model) {
CreationDate creationDate = new CreationDate();
model.addAttribute("creationD", creationDate);
return "index";
}
#RequestMapping(value="/add", method=RequestMethod.GET)
public String addingData(#ModelAttribute("creationD") CreationDate creationDate, BindingResult result, Model model) {
model.addAttribute("creationD", creationDate);
return "add";
}
}
My bean:
public class CreationDate implements Serializable {
private static final long serialVersionUID = 1648102358397071136L;
private int dateId;
#Id
#GeneratedValue(strategy=IDENTITY)
#Column(name="DATE_ID")
public int getDateId() {
return dateId;
}
public void setDateId(int dateId) {
this.dateId = dateId;
}
private Date particularDate;
#Column(name="PARTICULAR_DATE")
public Date getParticularDate() {
return particularDate;
}
public void setParticularDate(Date particularDate) {
this.particularDate = particularDate;
}
private int version;
#Version
#Column(name="VERSION")
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
private Date childGoSchoolDate;
#Temporal(TemporalType.DATE)
#Column(name="CHILD_GO_SCHOOL_DATE")
public Date getChildGoSchoolDate() {
return childGoSchoolDate;
}
public void setChildGoSchoolDate(Date childGoSchoolDate) {
this.childGoSchoolDate = childGoSchoolDate;
}
private Date childAdmissionDate;
#Temporal(TemporalType.DATE)
#Column(name="CHILD_ADMISSION_DATE")
public Date getChildAdmissionDate() {
return childAdmissionDate;
}
public void setChildAdmissionDate(Date childAdmissionDate) {
this.childAdmissionDate = childAdmissionDate;
}
}
My form page:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8"%>
<%# taglib prefix="form" 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=utf-8">
<title>Страница выборки</title>
</head>
<body>
<h3>Вставка данных:</h3>
<form:form modelAttribute="creationD" method="GET" action="add">
<form:label path="particularDate">Particular Date</form:label>
<form:input path="particularDate" /> <br>
<form:label path="childGoSchoolDate">Child go to School</form:label>
<form:input path="childGoSchoolDate"/> <br>
<form:label path="childAdmissionDate">Child admission Date</form:label>
<form:input path="childAdmissionDate"/> <br>
<input type="submit" value="Save"/>
</form:form>
</body>
</html>
My second page where I need to rented data from my form:
<?xml version="1.0" encoding="UTF-8" ?>
<%# 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="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<h1>Result:</h1>
Attribute 1:<c:out value="${creationD.particularDate}"/>
Attribute 2:<c:out value="${creationD.childGoSchoolDate}"/>
Attribute 3:<c:out value="${creationD.childAdmissionDate}"/>
</body>
</html>
I would check following to isolate the problem:
Have you got a date resolver? You have a property of type Date on your form bean, Spring wouldn't automatically know the date format unless you tell it. On Spring 3.2.3 you can simply use #DateTimeFormat annotation
Have you setup view resolver properly? I'm assuming "index" and "add" resolves to index.jsp and add.jsp, make sure you're not editing the wrong file
Have you got any Spring MVC handler interceptor / servlet filters that mess around with stuff in your model?
v.a,
Try this:
Note: I commented out the logging in your controller to save time. You can add that back in.
I also took the database annotations out of your controller, again to save time, and I also changed the way you were building your attributes in the /add routine to a style I was familiar with.
Last but not least, I also changed the way you were displaying your output slightly..
web.xml:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Form Handling</display-name>
<servlet>
<servlet-name>Student</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Student</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Student-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.hcsc" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
CreationDate.Java:
package com.hcsc;
import java.util.Date;
public class CreationDate {
private int dateId;
public int getDateId() {
return dateId;
}
public void setDateId(int dateId) {
this.dateId = dateId;
}
private Date particularDate;
public Date getParticularDate() {
return particularDate;
}
public void setParticularDate(Date particularDate) {
this.particularDate = particularDate;
}
private int version;
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
private Date childGoSchoolDate;
public Date getChildGoSchoolDate() {
return childGoSchoolDate;
}
public void setChildGoSchoolDate(Date childGoSchoolDate) {
this.childGoSchoolDate = childGoSchoolDate;
}
private Date childAdmissionDate;
public Date getChildAdmissionDate() {
return childAdmissionDate;
}
public void setChildAdmissionDate(Date childAdmissionDate) {
this.childAdmissionDate = childAdmissionDate;
}
}
HomeController.java:
package com.hcsc;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
#Controller
public class HomeController{
private static final long serialVersionUID = 4825408935018763217L;
// #SuppressWarnings("unused")
// private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#RequestMapping(value ="/index", method=RequestMethod.GET)
public ModelAndView index() {
return new ModelAndView("index","command", new CreationDate());
}
#RequestMapping(value="/add", method=RequestMethod.GET)
public String addingData(#ModelAttribute("creationD")CreationDate creationDate, ModelMap model) {
model.addAttribute("particularDate", creationDate.getParticularDate());
model.addAttribute("childGoSchoolDate", creationDate.getChildGoSchoolDate());
model.addAttribute("childAdmissionDate", creationDate.getChildAdmissionDate());
return "add";
}
}
index.jsp:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8"%>
<%# taglib prefix="form" 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=utf-8">
<title>Страница выборки</title>
</head>
<body>
<h3>Вставка данных:</h3>
<form:form method="GET" action="/Student/add">
<form:label path="particularDate">Particular Date</form:label>
<form:input path="particularDate" /> <br>
<form:label path="childGoSchoolDate">Child go to School</form:label>
<form:input path="childGoSchoolDate"/> <br>
<form:label path="childAdmissionDate">Child admission Date</form:label>
<form:input path="childAdmissionDate"/> <br>
<input type="submit" value="Save"/>
</form:form>
</body>
</html>
add.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Student UI Output</title>
</head>
<body>
<h1>Result:</h1>
Attribute 1: <c:out value="${particularDate} "/><br />
Attribute 2: <c:out value="${childGoSchoolDate} "/><br />
Attribute 3: <c:out value="${childAdmissionDate} "/><br />
</body>
</html>
Related
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
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.
I've searched through several tutorials and answers to this forum to try to solve my problem: I want to show the validation errors from my bean in my form using spring MVC.
No matter what I try, I can't get it to work. Im not using redirections, my binding results are directly after the model class and so on.
Here's what I have so far:
Login Class:
public class LoginUser implements Serializable {
#NotNull
#Column(name="username", unique=true)
#Size(min=5)
private String username;
#NotNull
#Size(min=5)
private String password;
Login Controller:
#Transactional
#Controller
public class LoginController {
#Autowired
UserDao dao;
#RequestMapping(value = "enter", method = RequestMethod.POST)
public String doLogin(#ModelAttribute("user") #Valid LoginUser user, BindingResult result, HttpSession session) {
if (result.hasErrors()) {
return "login/loginForm";
} else {
if (dao.authenticate(user)) {
session.setAttribute("userLoggedIn", user.getUsername());
return "forward:index";
} else {
return "redirect:login";
}
}
}
Login Form:
<%# 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"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# 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">
<script type="text/javascript" src="resources/js/bootstrap.js"></script>
<script type="text/javascript" src="resources/js/jquery-3.1.0.min.js"></script>
<link rel="stylesheet" href="resources/css/bootstrap.css">
<title><spring:message code="title.login" /></title>
</head>
<body>
<spring:message code="login.message.login" />
<form:form action="enter" commandName="loginForm" method="POST">
<spring:message code="username.login" />
<input type="text" name="username" id="username" /><br />
<form:errors path="username" />
<spring:message code="password.login" />
<input type="password" name="password" id="password" /><br /> <input
type="submit" value="<spring:message code='button.login'/>"><br />
<spring:message code="does.not.have.account.login" />
<spring:message code="register.link.login" />
</form:form>
</body>
</html>
Ohh, I forgot to add - I have a messages.properties configured (working fine, tested) and the messages are comming from there. Here is the line related to the form:
messages_en.Properties
NotEmpty.loginForm.username= Please fill the username field
By the way, it may be worth to note that my view is mounted trough a composite view (made of JSP includes of header, mainpage and footer) that overrides the customary viewloading in Sping-MVC.
You are using RedirectAttributes but you are not redirecting user any where. Try to use "redirect:/<register_path>" or just add Model model to method params and use model.addAtribute("someName", result);
Try below code..
<form:form action="enter" commandName="loginForm" method="POST">
commandName is loginForm so #ModelAttribute("loginForm").
#RequestMapping(value = "enter", method = RequestMethod.POST)
public String doLogin( #Valid #ModelAttribute("loginForm") LoginUser user, BindingResult result, Map<String, Object> model, HttpSession session) {
if (result.hasErrors()) {
return "login/loginForm";
} else {
if (dao.authenticate(user)) {
session.setAttribute("userLoggedIn", user.getUsername());
return "forward:index";
} else {
return "redirect:login";
}
}
}
UPDATE :
You are using NotEmpty.loginForm.username= Please fill the username field which is wrong,It should be NotNull.loginForm.username= Please fill the username field
And also
#NotNull will not validate for empty string..Request from the front end will be "" which is not null.So use #NotEmpty instead.
If you still want to use #NotNull add InitBinder in your controller as shown below
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
Then it will validate for empty string.
That is the reason you are getting size error directly and since you have not mentioned any message for that no message is displaying.
I am developing simple web application using Spring MVC. Could you please point me out why the resources are not rendered on the page when I am accessing it? The whole page is being rendered however.
Here my project structure
I am receiving the following warning:
No mapping found for HTTP request with URI [/resources/css/styles.css] in DispatcherServlet with name 'SpringDispatcher'
JSP page that holds the links to the resources:
includes.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="base" value="${pageContext.request.contextPath}"/>
<link href="<c:url value="${base}/resources/css/pure/pure-min.css" />" rel="stylesheet">
<link href="<c:url value="${base}/resources/css/styles.css" />" rel="stylesheet">
<link href="<c:url value="${base}/resources/css/menu.css" />" rel="stylesheet">
<script src="${base}/resources/js/validateInput.js"></script>
JSP page that has to be rendered:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<jsp:include page="/resources/includes.jsp"/>
</head>
<body>
<div id="main-container">
<div class="site-content">
<h1 class="fueling-header">Registration</h1>
<form class="pure-form pure-form-aligned"
action="/register"
method="post"
onsubmit="return validateUserInput();">
</fieldset>
</form>
</div>
</div>
</body>
</html>
Here is my WebAppInitializer code:
public class WebAppContextInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
annotationConfigWebApplicationContext.register(WebContextConfiguration.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"SpringDispatcher",new DispatcherServlet(annotationConfigWebApplicationContext)
);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
ContextConfiguration class
#Configuration
#EnableWebMvc
#Import(ServiceContextConfiguration.class)
#ComponentScan("controllers")
public class WebContextConfiguration {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
#Bean(name = "view_resolver")
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
}
And my simple controller
#Controller
public class BasicController {
#RequestMapping(value = "/greeting")
public String sayBasic(Model model){
model.addAttribute("greeting", "Hello world");
return "register";
}
}
The problem was that I had the cyclic reference in another controller i.e. the get method and post were mapped to the same logical view name. My configuration was correct.
For those who will meet the same problem: remove all request mappings and add them step by step till you will see where the problem occurred.
Remove ${base} as it is adding additional / Character.
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