Trying to create a dropdown in my jsp page - spring

I am trying to create a dropdown which will have dynamic values in my jsp page but getting an exception, i am trying to use spring form tags here.
WebController.java
#RequestMapping(value="/addAchivement",method=RequestMethod.GET)
public String addAchievements(){
Object object=null;
try {
object = genericAppProcessor.checkLogin(username, password,null,null);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SchoolLoginDetails sld=new SchoolLoginDetails();
sld=(SchoolLoginDetails)object;
List<GroupDetails> list=new ArrayList<GroupDetails>();
list=(List<GroupDetails>) sld.getGroupDetails();
Set<Object> addedClass = new HashSet<Object>();
Set<Object> addedSection = new HashSet<Object>();
Map referenceData = new HashMap();
Map<Object,Object> classs = new LinkedHashMap<Object,Object>();
for(int i=0;i<list.size();i++){
Object obj=list.get(i).getClazz();
Object objj=list.get(i).getSection();
addedClass.add(obj);
addedSection.add(objj);
List<Object> convertTolist=new ArrayList<Object>(addedClass);
classs.put(convertTolist.get(0),convertTolist.get(0));
addedClass.clear();
}
referenceData.put("classList",classs);
return "addAchivement";
}
addAchivement.jsp
<form:form method="POST" role="form" action="/GenericApp/addWebAchievement" enctype="multipart/form-data">
<form:select path="classs">
<form:options items="${classList}" />
</form:select>
Exception :-
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/addAchivement.jsp at line 72
<div class="input-field col s12 m4 l3" >
<!--Line 72 --> <form:select path="classs" class="text-black custom-select">
<form:options items="${classList}" />
</form:select>

you need to return model and view instead of just returning a view Use Below Code :
// Java Code
#RequestMapping(value="/addAchivement",method=RequestMethod.GET)
public ModelAndView addAchievements(){
Object object=null;
try {
object = genericAppProcessor.checkLogin(username, password,null,null);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SchoolLoginDetails sld=new SchoolLoginDetails();
sld=(SchoolLoginDetails)object;
List<GroupDetails> list=new ArrayList<GroupDetails>();
list=(List<GroupDetails>) sld.getGroupDetails();
Set<Object> addedClass = new HashSet<Object>();
Set<Object> addedSection = new HashSet<Object>();
Map referenceData = new HashMap();
Map<Object,Object> classs = new LinkedHashMap<Object,Object>();
for(int i=0;i<list.size();i++){
Object obj=list.get(i).getClazz();
Object objj=list.get(i).getSection();
addedClass.add(obj);
addedSection.add(objj);
List<Object> convertTolist=new ArrayList<Object>(addedClass);
classs.put(convertTolist.get(0),convertTolist.get(0));
addedClass.clear();
}
referenceData.put("classList",classs);
ModelAndView mav = new ModelAndView("addAchivement", referenceData);
return mav;
}
You are assigning a path to classs in your jsp
<!--Line 72 --> <form:select path="classs" class="text-black custom-select">
but you are not sending anything from model on which this class variable can map so you need to use modelAttribute in your spring form so that this class variable can map .
for eg .
: you need to make a class object which has a class as member :
below is java code change :
referenceData.put("classList",classs);
referenceData.put("classObject",class); // Here class is a object that has class attribute by which that value in jsp will bind .
ModelAndView mav = new ModelAndView("addAchivement", referenceData);
Here is Jsp Code change :
<form:form method="POST" role="form" action="/GenericApp/addWebAchievement" enctype="multipart/form-data" modelAttribute="classObject">
<form:select path="classs">
<form:options items="${classList}" />
</form:select>
Sample class object :
public Class{
String classs ;
// getter setter for classs member variable .
}

Related

unable to render index or mobile page with spring mobile

I was able to get my project to run just fine until I brought in spring-mobile. Now only Strings will return in the browser that the spring-mobile method is returning:
#Controller
public class DeviceDetection {
private Logger logger = LoggerFactory.getLogger(DeviceDetection.class);
#RequestMapping(value="/index")
public String detectDevice(Device device) {
if (device.isNormal()) {
System.out.println("Inside isNormal()");
return "index";
} else if (device.isMobile()) {
System.out.println("Inside isMobile()");
return "mobilePage";
} else if (device.isTablet()) {
return "mobilePage";
}
return "index";
}
}
So I decided I needed internalResourceViewResolver but that just gives me the following error:
Error creating bean with name 'viewResolver' defined in class path resource
[org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoCon
figurationAdapter.class]: Initialization of bean failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean
with name 'org.springframework.boot.autoconfigure.mobile
and
DeviceDelegatingViewResolverAutoConfiguration$DeviceDelegatingViewResolverConfigur
ation$InternalResourceViewResolverDelegateConfiguration.viewResolver; nested
exception is
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
qualifying bean of type
[org.springframework.web.servlet.view.InternalResourceViewResolver] is
defined: expected single matching bean but found 2:
getViewResolver,defaultViewResolver
Resolver class
#Configuration
public class MvcConfiguration extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".html");
return resolver;
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Main Class
#SpringBootApplication
public class StidhamFinancialApplication extends SpringBootServletInitializer {
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(StidhamFinancialApplication.class);
Environment env = app.run(args).getEnvironment();
System.out.println(String.format("Access URLs:\n----------------------------------------------------------\n\t" +
"Local: \t\thttp://127.0.0.1:%1s\n\t" +
"External: \thttp://%2s:%3s\n----------------------------------------------------------",
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port")));
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(StidhamFinancialApplication.class);
}
}
project structure:
I am running it on Tomcat 8...
--------Update 1---------------
I deleted my configuration package and add #ResponeBody to my detectDevice method like so:
//If I remove #ResponseBody it complains of a Circular view path [index] with
#ResponseBody it just renders a String and not a view
#RequestMapping(value="/index")
public #ResponseBody String detectDevice(Device device) {
if (device.isNormal()) {
System.out.println("Inside isNormal()");
return "index";
} else if (device.isMobile()) {
System.out.println("Inside isMobile()");
return "mobilePage";
} else if (device.isTablet()) {
return "mobilePage";
}
return "index";
}
Only the String index or mobilePage will render in the browser. If I delete the #ResponseBody then the project gives an error saying the following:
2016-05-29 08:55:03.682 ERROR 8230 --- [nio-8080-exec-1]
o.s.boot.context.web.ErrorPageFilter : Forwarding to error page
from request [/index.html] due to exception [Circular view path
[index]: would dispatch back to the current handler URL [/index] again.
Check your ViewResolver setup! (Hint: This may be the result of an
unspecified view, due to default view name generation.)]
If I remove the /index then the method is ignored completely and spring-boot just maps my index file and works again but I need the mobile site to work.
-------------------UPDATE 2-------------------
Ok I added thymeleaf and my index page is rendering again. Even better the DeviceDetection is working but once my project looks for my mobilePage I get the following error:
Error resolving template "mobile/index", template might not exist or might not be accessible by any of the configured Template Resolvers
I had to add the follow ing #Configuration to get the project to work. The spring-boots defaultViewResolver was causing me to many issues. Here is the project structure now:
I updated the project on GIT too.
First I needed to use something like Thymeleaf and create a viewResolver. Spring-boots defaultViewResolver was causing me issues:
#Configuration
public class WebConfiguration extends WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public DispatcherServlet dispatcherServlet(){
DispatcherServlet dispatcherServlet = new DispatcherServlet();
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
return dispatcherServlet;
}
#Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setOrder(1);
return resolver;
}
}
Since I was using Thymeleaf I needed bindingResult and a few other things. This is also where I implemented springs mobile Device interface to detect the device.
#Controller
public class FormController {
#RequestMapping(value="/", method= RequestMethod.GET)
public String contactForm(#Valid #ModelAttribute("person") Contact contact, BindingResult bindingResult,
HttpServletRequest request, Model model, Device device) throws IOException {
if(bindingResult.hasErrors()){
System.out.println("There was a error "+bindingResult);
return "error";
}
model.addAttribute("contact", new Contact());
if(device.isNormal()){
System.out.println("I am normal");
return "index";
} else if(device.isMobile()){
System.out.println("I am a mobile");
return "mobilePage";
} else if (device.isTablet()){
System.out.println("I am a tablet");
return "mobilePage";
}
return "index";
}
Now I just needed to put the different views in the correct directories like so:
That was it and it is working perfectly.
Here is the form I created to use implement Thymeleaf:
<!-- Contact form -->
<form action="#" th:action="#{/contact}" th:object="${contact}" method="POST" class="contact-form clear-fix">
<div class="clear-fix">
<ul class="list-0 clear-fix">
<!-- Name -->
<li>
<div class="block field-box">
<label for="contact-form-name" class="text-color-black">Your Name</label>
<input type="text" th:field="*{name}" class="contact noMarr col-md-6 text-color-black" id="contact-form-name" />
</div>
</li>
<!-- /Name -->
<!-- E-mail address -->
<li>
<div class="block field-box">
<label for="contact-form-mail" class="text-color-black">Your E-mail</label>
<input type="text" th:field="*{email}" class="contact noMarr col-md-6 text-color-black" id="contact-form-mail" />
</div>
</li>
<!-- /E-mail address -->
<!-- Website URL -->
<li>
<div class="block field-box">
<label for="contact-form-subject" class="text-color-black">Subject</label>
<input type="text" th:field="*{subject}" class="contact noMarr col-md-6 text-color-black" id="contact-form-subject" />
</div>
</li>
<!-- /Website URL -->
<!-- Message -->
<li>
<div class="block field-box ">
<label for="contact-form-message" class="text-color-black">Your message</label>
<textarea name="comment" class="contact col-md-12 text-color-black" th:field="*{message}" id="contact-form-message"></textarea>
</div>
</li>
<!-- /Message -->
<!-- Submit button -->
<li>
<div class="block field-box field-box-button text-color-black">
<input type="submit" id="contact-form-submit" name="contact-form-submit" class="button text-color-black" value="Submit"/>
</div>
</li>
<!-- /Submit button -->
</ul>
</div>
</form>

Why update method isn't calling?

I have a problem. When I click to update image on form, update method isn't calling. I see that in my output logs window. Only may update image in first row in my table.
When I updating first row:
Hibernate: update shoe_goods set description=?, image=?, in_stock=?,
name=?, price=?, size=?, web_store_id=? where id=?
When other rows - nothing.
I save my images in db as byte.
This is my method to display images:
Controller:
#RequestMapping(value = "/imageController/{id}")
#ResponseBody
public byte[] getImages(#PathVariable int id) {
return shoeGoodsService.getById(id).getImage();
}
JSP:
<img src="/imageController/${goods.id}" alt="Image" />
Code in DAO class:
#Override
public void update(ShoeGoods shoeGoods) {
sessionFactory.getCurrentSession().merge(shoeGoods);
sessionFactory.getCurrentSession().getTransaction().commit();
}
Code in Service class:
#Override
public void update(ShoeGoods shoeGoods) {
shoeGoodsDAO.update(shoeGoods);
}
Code in controller, when update method is call only for first row in table:
#RequestMapping(value="/upload_shoe_image", method = RequestMethod.POST)
public #ResponseBody ModelAndView handleFileUpload1(#RequestParam("file") MultipartFile file){
...
try {
ShoeGoods shoeGoods = shoeGoodsService.getById(goodsId);
shoeGoods.setImage(file.getBytes());
//not call always
shoeGoodsService.update(shoeGoods);
} catch (Exception e) {
e.printStackTrace();
}
...
}
In JSP:
<form id="send-image-form" method="POST" enctype="multipart/form-data"
action="/upload_shoe_image">
Edit: <input type="file" name="file">
<br />
Save: <input type="submit" id="save-image" value="Upload">
</form>

Validation Spring confusion to render error message

I try to render error message but it's not appears:
I have validator:
#Component
class ValidatorFBOSSearch implements Validator {
#SuppressWarnings("rawtypes")
#Override
public boolean supports(Class clazz) {
return FormBackObjectSearch.class.equals(clazz);
}
#Override
public void validate(Object obj, Errors error) {
FormBackObjectSearch fbos = (FormBackObjectSearch)obj;
if ("".equals(fbos.particularDate)){
error.rejectValue("particularDate", "required.listOfDates", "This field is required");
}
}
}
it have to cheak does my field in backing object for form have value inputed or not. rejectValue has three param. First - looks for a value in Model Attribute in my backing object, Secong looks for error message in properties file(my properties file located in resourses/error forlder) Third param in methos says if it won't be able to find message in error properties file will render it as default, here is my sniped of code in my servlet-context.xml
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
And this my xml config for messageSourse to get errors for Validator in servlet-context.xml:
<!-- Resolves error messages for validator from /Education/src/main/webapp/resources/errors-->
<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="errors/errormessages"/>
</beans:bean>
Here peace of my controller code for dealing with requests:
#RequestMapping(value="/search", method=RequestMethod.GET)
public void search(Model model) {
FormBackObjectSearch fbos = new FormBackObjectSearch();
model.addAttribute("fbosAttribute", fbos);
}
#RequestMapping(value ="/result", method=RequestMethod.POST)
public String extract(#RequestParam String nameOfInstitution,
#RequestParam String particularDate,
#RequestParam String typeOfInstitution,
#ModelAttribute("fbosAttribute") FormBackObjectSearch fbos,
BindingResult result, RedirectAttributes redirectAttributes,
Model model) throws Exception {
ValidatorFBOSSearch validatorFBOS = new ValidatorFBOSSearch();
validatorFBOS.validate(fbos, result);
if(result.hasErrors()) {
redirectAttributes.addFlashAttribute("fbosAttribute", fbos);
return "redirect:/search";
} else {
if(particularDate !="" && nameOfInstitution !="" && typeOfInstitution =="") {
controllerSupportClass.findWithDateAndName(nameOfInstitution, particularDate, model);
} else if(particularDate !="" && nameOfInstitution =="" && typeOfInstitution !="") {
controllerSupportClass.findWithAddedDateAndType(typeOfInstitution, particularDate, model);
} else if(particularDate !="" && nameOfInstitution =="" && typeOfInstitution ==""){
controllerSupportClass.findWithAddedDate(particularDate, model);
} else if(particularDate !="" && nameOfInstitution !="" && typeOfInstitution !="") {
throw new Exception("Search by choose all parameters is not exceptable");
} else {
throw new Exception("You didn't put any search parameters");
}
}
return "search";
}
And here is peace of my jsp:
<form:form action="result" method="post" modelAttribute="fbosAttribute" >
<table>
<tr>
<th>Date for extracting:</th>
<td><form:select path="particularDate">
<form:option value=""> -Choose date-</form:option>
<form:options items="${listOfDates}"></form:options>
</form:select> <td><form:errors path="particularDate" cssClass="error"/></td>
</td>
</tr>
</table>
</form:form>
The problem is thet I can not see error messages show up. I tried to use Flash Attributes to have error appears after riderect, but nothing heppend. cuz I found here that when I use rederect it makes my model and errors deleted and start new one. But How can I have advantage to use flash attibutes to solve my problem. Thank you
To register the validator for an specific controller you need can use the `#InitBimder' annotation.
#InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new ValidatorFBOSSearch());
}
For mor details how to register the validator see my answer at:
Validation in Spring MVC
I think your check statement is wrong:
if ("".equals(fbos.particularDate)){
If a user enters nothing, then a String will not be empty ( "" ), it will be null. Therefore use:
if (fbos.particularDate == null || fbos.particularDate.isEmpty())

My Spring CustomCollectionEditor implementation , not binding correctly

I have one select multiple in Spring:
<form:select path="categoryProducts" id="destinationData" itemLabel="product.name" items="${categoryProducts}" itemValue="product.id" multiple="true" ondblclick="moveLeft(document.getElementById('destinationData'), document.getElementById('sourceData'))" size="10" />
In my controller:
#InitBinder
public void initBinder(WebDataBinder binder){
binder.registerCustomEditor(Set.class, "categoryProducts", new CustomCollectionEditor(Set.class)
{
#Override
protected Object convertElement(Object element)
{
Product p = new Product() ;
try {
Short id = new Short(String.valueOf(element));
p = (Product) dataManager.find(Product.class, id);
System.out.println(p.getId() + "\\" +p.getName());
CategoryProduct c = new CategoryProduct ();
c.setProduct(p);
return c;
} catch (Exception e) {
e.printStackTrace();
}
return p;
}
});
When I do submit, receive this log:
136 Product Name
105 Product Name
104 Product Name
211 Product Name
204 Product Name
409 Product Name
30/03/2011 07:32:20 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() para servlet cms lanzó excepción
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'category' on field 'categoryProducts': rejected value [136,105,104,211,204,409][type
The initiBinder is initialized, but throws exception in the end: (rejected value [136,105,104,211,204,409]) .
Why?
Most likely the field "categoryProducts" of your command class (model attribute) is a
Set<String>
...or a Set of any class other than CategoryProduct. Try to change it to:
Set<CategoryProduct>

Neither BindingResult nor plain target object for bean name available as request attr [duplicate]

This question already has answers here:
What causes "java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute"?
(7 answers)
Closed 6 years ago.
Hi Experts,
I have this controller code which is throwing the above mentioned error. It was working fine till yesterday, I have no clue what colleague did to this code and today I am seeing the error:
Neither BindingResult nor plain target object for bean name 'sideForm' available as request attribute
Can you please suggest me where to look for this kind of error. Am I making any mistake in POST or GET method declaration or returning something wrong?
Your help is greatly appreciated :)
package com.att.analytics.ui;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
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.RequestMethod;
import com.si.myworld.business.AdminChart;
import com.si.myworld.business.Chart;
import com.si.myworld.dao.AdminChartSummaryData;
import com.si.myworld.dao.BulletinData;
import com.si.myworld.dao.ChartData;
#RequestMapping("/index.html")
#Controller
public class IndexController {
private static final Logger log = Logger.getLogger(IndexController.class);
/**
* Called to load the page initially (GET request)
*
* #param model
* #return
*/
#RequestMapping(method = RequestMethod.GET)
public String getCharts(ModelMap model) {
Chart chart = new Chart();
chart.setTimeline("Monthly");
chart.setStartDt("mm/dd/yyyy");
chart.setEndDt("mm/dd/yyyy");
AdminChartSummaryData acsd = new AdminChartSummaryData();
List<AdminChart> list = acsd.getLandingChartDataList();
if (list.size() == 4) {
Chart chart1 = new Chart(list.get(0));
Chart chart2 = new Chart(list.get(1));
Chart chart3 = new Chart(list.get(2));
Chart chart4 = new Chart(list.get(3));
model.put("chart1", chart1);
model.put("chart2", chart2);
model.put("chart3", chart3);
model.put("chart4", chart4);
log.info("chart 1>>>>" + chart1);
ChartData cd = new ChartData();
String chartOneDatasource = cd.fetchChartDatasourceName(chart1
.getChartSubgroup());
String chartTwoDatasource = cd.fetchChartDatasourceName(chart2
.getChartSubgroup());
String chartThreeDatasource = cd.fetchChartDatasourceName(chart3
.getChartSubgroup());
String chartFourDatasource = cd.fetchChartDatasourceName(chart4
.getChartSubgroup());
String breadcrumbOne = chart1.getChartGroup() + ">>"
+ chart1.getChartSubgroup();
String breadcrumbTwo = chart2.getChartGroup() + ">>"
+ chart2.getChartSubgroup();
String breadcrumbThree = chart3.getChartGroup() + ">>"
+ chart3.getChartSubgroup();
String breadcrumbFour = chart4.getChartGroup() + ">>"
+ chart4.getChartSubgroup();
BulletinData bd = new BulletinData();
String bulletin = bd.getBulletinData();
model.put("sideForm", chart);
model.put("chartOneDatasource", chartOneDatasource);
model.put("chartTwoDatasource", chartTwoDatasource);
model.put("chartThreeDatasource", chartThreeDatasource);
model.put("chartFourDatasource", chartFourDatasource);
model.put("breadcrumbOne", breadcrumbOne);
model.put("breadcrumbTwo", breadcrumbTwo);
model.put("breadcrumbThree", breadcrumbThree);
model.put("breadcrumbFour", breadcrumbFour);
model.put("bulletin", bulletin);
}
return "land";
}
#RequestMapping(method = RequestMethod.POST)
public String loadCharts(HttpServletRequest request, ModelMap model, #ModelAttribute("sideForm") Chart chart) {
String from_date = request.getParameter("startDt");
String to_date = request.getParameter("endDt");
chart.setStartDt(from_date);
chart.setEndDt(to_date);
ChartData cd = new ChartData();
BulletinData bd = new BulletinData();
String bulletin = bd.getBulletinData();
AdminChartSummaryData acsd = new AdminChartSummaryData();
List<AdminChart> list = acsd.getLandingChartDataList();
if (list.size() == 4) {
Chart chart1 = new Chart(list.get(0));
Chart chart2 = new Chart(list.get(1));
Chart chart3 = new Chart(list.get(2));
Chart chart4 = new Chart(list.get(3));
model.put("chart1", chart1);
model.put("chart2", chart2);
model.put("chart3", chart3);
model.put("chart4", chart4);
String chartOneDatasource = cd.fetchChartDatasourceName(chart1
.getChartSubgroup());
String chartTwoDatasource = cd.fetchChartDatasourceName(chart2
.getChartSubgroup());
String chartThreeDatasource = cd.fetchChartDatasourceName(chart3
.getChartSubgroup());
String chartFourDatasource = cd.fetchChartDatasourceName(chart4
.getChartSubgroup());
model.put("chartOneDatasource", chartOneDatasource);
model.put("chartTwoDatasource", chartTwoDatasource);
model.put("chartThreeDatasource", chartThreeDatasource);
model.put("chartFourDatasource", chartFourDatasource);
String breadcrumbOne = chart1.getChartGroup() + ">>"
+ chart1.getChartSubgroup();
String breadcrumbTwo = chart2.getChartGroup() + ">>"
+ chart2.getChartSubgroup();
String breadcrumbThree = chart3.getChartGroup() + ">>"
+ chart3.getChartSubgroup();
String breadcrumbFour = chart4.getChartGroup() + ">>"
+ chart4.getChartSubgroup();
model.put("breadcrumbOne", breadcrumbOne);
model.put("breadcrumbTwo", breadcrumbTwo);
model.put("breadcrumbThree", breadcrumbThree);
model.put("breadcrumbFour", breadcrumbFour);
}
return "land";
}
#ModelAttribute("timeline")
public Collection<String> populateTimeline() {
return Arrays.asList("Daily", "Weekly", "Monthly", "Quarterly",
"Annually", "12_Month_Rolling");
}
}
This page gets values from a form shown below:
<form:form commandName="sideForm">
<div style="font-weight:bold; color:#000">Timeline</div>
<div style="margin:0 0 5px 0;"><form:select path="timeline" items="${timeline}" id="tm"/></div>
<div class="tofrom">From:</div>
<form:input path="startDt" id="from_date" size="7" maxlength="10" />
<div class="tofrom">To:</div>
<form:input path="endDt" id="to_date" size="7" maxlength="12" />
<input type="submit" value="Update Chart" />
</form:form>
Make sure that your Spring form mentions the modelAttribute="<Model Name".
Example:
#Controller
#RequestMapping("/greeting.html")
public class GreetingController {
#ModelAttribute("greeting")
public Greeting getGreetingObject() {
return new Greeting();
}
/**
* GET
*
*
*/
#RequestMapping(method = RequestMethod.GET)
public String handleRequest() {
return "greeting";
}
/**
* POST
*
*
*/
#RequestMapping(method = RequestMethod.POST)
public ModelAndView processSubmit(#ModelAttribute("greeting") Greeting greeting, BindingResult result){
ModelAndView mv = new ModelAndView();
mv.addObject("greeting", greeting);
return mv;
}
}
In your JSP :
<form:form modelAttribute="greeting" method="POST" action="greeting.html">
Make sure you declare the bean associated with the form in GET method of the associated controller and also add it in the model model.addAttribute("uploadItem", uploadItem); which contains #RequestMapping(method = RequestMethod.GET) annotation.
For example UploadItem.java is associated with myform.jsp and controller is SecureAreaController.java
myform.jsp contains
<form:form action="/securedArea" commandName="uploadItem" enctype="multipart/form-data"></form:form>
MyFormController.java
#RequestMapping("/securedArea")
#Controller
public class SecureAreaController {
#RequestMapping(method = RequestMethod.GET)
public String showForm(Model model) {
UploadItem uploadItem = new UploadItem(); // declareing
model.addAttribute("uploadItem", uploadItem); // adding in model
return "securedArea/upload";
}
}
As you can see I am declaring UploadItem.java in controller GET method.
Try adding a BindingResult parameter to methods annotated with #RequestMapping which have a #ModelAttribute annotated parameters. After each #ModelAttribute parameter, Spring looks for a BindingResult in the next parameter position (order is important).
So try changing:
#RequestMapping(method = RequestMethod.POST)
public String loadCharts(HttpServletRequest request, ModelMap model, #ModelAttribute("sideForm") Chart chart)
...
To:
#RequestMapping(method = RequestMethod.POST)
public String loadCharts(#ModelAttribute("sideForm") Chart chart, BindingResult bindingResult, HttpServletRequest request, ModelMap model)
...
I worked on this same issue and I am sure I have found out the exact reason for it.
Neither BindingResult nor plain target object for bean name 'command' available as request attribute
If your successView property value (name of jsp page) is the same as your input page name, then second value of ModelAndView constructor must be match with the commandName of the input page.
E.g.
index.jsp
<html>
<body>
<table>
<tr><td>Login</td></tr>
</table>
</body>
</html>
dispatcher-servlet.xml
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/Login.html">
<ref bean="userController"/>
</entry>
</map>
</property>
</bean>
<bean id="userController" class="controller.AddCountryFormController">
<property name="commandName"><value>country</value></property>
<property name="commandClass"><value>controller.Country</value></property>
<property name="formView"><value>countryForm</value></property>
<property name="successView"><value>countryForm</value></property>
</bean>
AddCountryFormController.java
package controller;
import javax.servlet.http.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.mvc.SimpleFormController;
public class AddCountryFormController extends SimpleFormController
{
public AddCountryFormController(){
setCommandName("Country.class");
}
protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,Object command,BindException errors){
Country country=(Country)command;
System.out.println("calling onsubmit method !!!!!");
return new ModelAndView(getSuccessView(),"country",country);
}
}
Country.java
package controller;
public class Country
{
private String countryName;
public void setCountryName(String value){
countryName=value;
}
public String getCountryName(){
return countryName;
}
}
countryForm.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
<form:form commandName="country" method="POST" >
<table>
<tr><td><form:input path="countryName"/></td></tr>
<tr><td><input type="submit" value="Save"/></td></tr>
</table>
</form:form>
</body>
<html>
Input page commandName="country"
ModelAndView Constructor as return new ModelAndView(getSuccessView(),"country",country);
Means inputpage commandName==ModeAndView(,"commandName",)
We faced the same issue and changed commandname="" to modelAttribute="" in jsp page to solve this issue.
I have encountered this problem as well. Here is my solution:
Below is the error while running a small Spring Application:-
*HTTP Status 500 -
--------------------------------------------------------------------------------
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/employe.jsp at line 12
9: <form:form method="POST" commandName="command" action="/SpringWeb/addEmploye">
10: <table>
11: <tr>
12: <td><form:label path="name">Name</form:label></td>
13: <td><form:input path="name" /></td>
14: </tr>
15: <tr>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005flabel_005f0(employe_jsp.java:185)
org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005fform_005f0(employe_jsp.java:120)
org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspService(employe_jsp.java:80)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.26 logs.*
In order to resolve this issue you need to do the following in the controller class:-
Change the import package from "import org.springframework.web.portlet.ModelAndView;"
to "import org.springframework.web.servlet.ModelAndView;"...
Recompile and run the code... the problem should get resolved.

Resources