I have a similar problem to this File Download Does Not Work. However, I have tried all the answers suggested but to no avail. I still get a NEP. Can someone please help
Here is my controller class:
#ManagedBean(name = "fileDownLoadController")
#RequestScoped
public class FileDownloadController {
private StreamedContent downloadFile;
public FileDownloadController() {
InputStream stream = null;
ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
File result = new File(extContext.getRealPath("//WEB-INF//temp//process.png"));
File outFile = new File("process.png");
Logger.getLogger(FileDownloadController.class.getName()).log(Level.SEVERE, outFile.getAbsolutePath());
stream = extContext.getResourceAsStream(result.getAbsolutePath());
downloadFile = new DefaultStreamedContent(stream, "image/png", "process.png");
}
public StreamedContent getFile() {
return downloadFile;
}
public void setFile(StreamedContent file) {
this.downloadFile = file;
}
View code:
<h1 class="title">FileDownload</h1>
<div class="entry">
<p>FileDownload </p>
<h:form>
<p:commandButton value="Download" ajax="false" >
<p:fileDownload value="#{fileDownloadController.file}" />
</p:commandButton>
</h:form>
</div>
Here is the error message:
java.lang.NullPointerException
at org.primefaces.component.filedownload.FileDownloadActionListener.processAction(FileDownloadActionListener.java:53)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:769)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
Problem is with stream = extContext.getResourceAsStream(result.getAbsolutePath()). Note that the file is not in the classpath in this case like in the other one you mentioned. Look below, it should work -
public FileDownloadController() throws FileNotFoundException {
ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
File result = new File(extContext.getRealPath("//WEB-INF//temp//process.png"));
InputStream stream = new FileInputStream(result.getAbsolutePath());
downloadFile = new DefaultStreamedContent(stream, "image/png", "process.png");
}
Related
When I use the below code it's working fine and change the theme, but the problem is if one of the user logged and change the theme it effects to the every user in the system. what I want is to effect the theme only for the particular user but not for every one.
Web.xml
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>#{settingsController.userTheme}</param-value>
</context-param>
primeface (.xhtml)
<h:outputLabel for="userTheme" value="Theme Name *:" style="width: 300px"/>
<p:selectOneMenu id="userTheme" value="#{settingsController.userTheme}" style="width:200px"
required="true" requiredMessage="Theme Name is Required" >
<f:selectItems value="#{settingsController.themeMap}"/>
</p:selectOneMenu>
SettingsController.java class
#ManagedBean(name = "settingsController")
#SessionScoped
#Controller
public class SettingsController {
private String userTheme = "start" ;
private Map<String , String> themeMap ;
#PostConstruct
public void init (){
setThemeMapInit( );
}
public String getUserTheme() {
return userTheme;
}
public void setUserTheme(String userTheme) {
this.userTheme = userTheme;
}
public Map<String, String> getThemeMap() {
return themeMap;
}
public void setThemeMapInit() {
themeMap = new LinkedHashMap<String, String>();
themeMap.put("Aristo", "aristo");
themeMap.put("After-noon", "afternoon");
themeMap.put("After-Work", "afterwork");
themeMap.put("Black-Tie", "black-tie");
themeMap.put("Blitzer", "blitzer");
themeMap.put("Bluesky", "bluesky");
themeMap.put("Bootstrap", "bootstrap");
themeMap.put("Casablanca", "casablanca");
themeMap.put("Cupertino", "cupertino");
themeMap.put("Dark-Hive", "dark-hive");
themeMap.put("Delta", "delta");
themeMap.put("Excite-Bike", "excite-bike");
themeMap.put("Flick", "flick");
themeMap.put("Glass-X", "glass-x");
themeMap.put("Home", "home");
themeMap.put("Hot-Sneaks", "hot-sneaks");
themeMap.put("Humanity", "humanity");
themeMap.put("Overcast", "overcast");
themeMap.put("Pepper-Grinder", "pepper-grinder");
themeMap.put("Redmond", "redmond");
themeMap.put("Rocket", "rocket");
themeMap.put("Sam", "sam");
themeMap.put("Smoothness", "smoothness");
themeMap.put("South-Street", "south-street");
themeMap.put("Start", "start");
themeMap.put("Sunny", "sunny");
themeMap.put("Swanky-Purse", "swanky-purse");
themeMap.put("UI-Lightness", "ui-lightness");
}
public void setThemeMap(Map<String, String> themeMap) {
this.themeMap =themeMap;
}
public void sumbitUserSettings (){
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
try {
ec.redirect(((HttpServletRequest) ec.getRequest()).getRequestURI());
} catch (IOException ex) {
Logger.getLogger(SettingsController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Every Spring bean is a Singletone by default, that's why all users are affected, despite of #SessionScoped.
You can't use #ManagedBean and #Controller at the same time, see why.
The best way to combine Spring and JSF in the same app, is to use Joinfaces.
With Joinfaces your bean will end up looking like this
#Named
#SessionScoped
public class SettingsController {
Related:
JSF vs. Spring MVC
I am newbie to JSF/Java ee7 and tried to test some features to understand how things work.
I used templating for testing purposes. Here is the relevant JSF template client:
<ui:define name="content">
<h:panelGroup class="keret" id="tartalom">
<h:form id="email" rendered="#{emailManagedBean.urlap}">
<h:messages/>
<h:outputLabel for="emailbox" value="Add meg az email címed, és juss hozzá bestsellerünkhöz 5Ft-ért"/>
<h:inputText value="#{emailManagedBean.newEmail.email}"/>
<h:commandButton actionListener="#{emailManagedBean.saveEmail()}" value="Mentés">
<f:ajax immediate="true" execute="#form" render=":tartalom"/>
</h:commandButton>
</h:form>
<h:panelGroup id="szoveg" rendered="#{not emailManagedBean.urlap}">
<h3>Köszönjük!</h3>
<p>
Hamarosan emailt fogsz kapni tőlünk. Kérlek, ellenőrizd a levélszemét, illetve spam mappákban is a tőlünk kapott levelet. A levlében lévő linkre kattintva hozzájuthatsz az ajándékodhoz.
</p>
</h:panelGroup>
</h:panelGroup>
</ui:define>
My managed bean:
#Named(value = "emailManagedBean")
#ViewScoped
public class emailManagedBean implements Serializable {
#EJB
EmailsFacadeLocal emailFacade;
private Emailcamp newEmail;
private boolean urlap;
public Emailcamp getNewEmail() {
return newEmail;
}
public void setNewEmail(Emailcamp newEmail) {
this.newEmail = newEmail;
}
#PostConstruct
public void init() {
newEmail = new Emailcamp();
urlap=true;
}
public boolean isUrlap() {
return urlap;
}
public void setUrlap(boolean urlap) {
this.urlap = urlap;
}
public void validateEmail(FacesContext context, UIComponent comp,
Object value) {
String input = (String) value;
EmailValidator validator = EmailValidator.getInstance();
if (!validator.isValid(input)) {
((UIInput) comp).setValid(false);
FacesMessage message = new FacesMessage(
"Helytelen email cím formátum");
context.addMessage(null, message);
} else {
if(!emailFacade.exist(newEmail.getEmail())){
((UIInput) comp).setValid(true);
}
else {
context.addMessage(null, new FacesMessage("Már megadtad korábban az email címed"));
}
}
}
public void saveEmail() {
/*Get current date and time*/
Calendar c = Calendar.getInstance();
newEmail.setRecemaildate(c.getTime());
/*Get Referral*/
HttpServletRequest hr = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
newEmail.setReferer((hr.getHeader("referer")==null) ? "not available" : hr.getHeader("referer") );
newEmail.setStatus(Status.NOT_SENT.toString());
emailFacade.create(newEmail);
urlap=false;
}
}
The expected behavior is that the init function set urlap boolean variable to true so the h:form should be shown as there is conditional rendering on the view side.
Later the customer clicks on Save ("Mentés") and the new email address and some data will be stored in a database. After the ajax call I urlap boolean varaible is set to false not to render the form again but render a thank you message.
Unfortunately the init function is never called so the boolean variable never set to true. As a consequences my thanks message is shown without collecting the email.
The second strange thing which is the consequence of the ajax component (I guess) that I got an error message: outputScript with no library, no name, and no body content. I did not declare any outputScript in my xhtml.
To sum things up: I want to upload file passed by user through a form with <p:fileUpload> using fileUploadController ManagedBean as its fileUploadListener to a certain path, then get this path along with filename and Store it somehow (the question is - how?) in the wydarzenieMB ManagedBean because I need filePath as a String in my addWydarzenie() method to store this path in a database and later use it.
I've got a table in my database named "Wydarzenie". It has many values like name etc. which I am specyfing in my JSF form for user to fill using primefaces. There is no problem with obtaining them, I just use ManagedBean to store input and later use this input to write into DataBase using addWydarzenie() method.
Part of utworzWydarzenie.xhtml form:
...
<h:outputLabel for="opis" value="Opis :" />
<p:inputTextarea id="opis" value="#{wydarzenieMB.opis}" label="opis">
...
<p:commandButton id="addWydarzenie" value="Zatwierdź" action="#{wydarzenieMB.addWydarzenie}" ajax="false"/>
My addWydarzenie() method in wydarzenieManagedBean:
public String addWydarzenie() {
try {
Wydarzenie wydarzenie = new Wydarzenie();
...
wydarzenie.setOpis(getOpis());
...
getWydarzenieServiceImpl().addWydarzenie(wydarzenie);
return SUCCESS;
} catch (DataAccessException e) {
e.printStackTrace();
}
return ERROR;
}
There is no problem with values like that where I use p:inputText for example, because I specify value of bean (for example: value="#{wydarzenieMB.opis}") in which I want to store them. Problem begins with my <p:fileUpload> field because:
1. I am not specyfing value there because there is no value returned(?) - only file uploaded
2. I am using fileUploadController ManagedBean to handle file uploading BUT I want the filePath String of uploaded file that it possess to be stored in my wydarzenieMB ManagedBean.
Here's my uploading file code from utworzWydarzenie.xhtml form:
...
<h:outputLabel for="plakat" value="Plakat :" />
<p:fileUpload id="plakat" update="messages" fileUploadListener="#{fileUploadController.handleFileUpload}" multiple="false" sizeLimit="1000000" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" />
<p:growl id="messages" showDetail="true"/>
...
And my fileUploadController class:
#ManagedBean(name="fileUploadController")
#RequestScoped
public class FileUploadController
{
private String destination="E:/PROJEKT ZESPOLOWY/events/WebContent/resources/plakaty/";
private String sciezkaPliku = ""; // complete file path including destination and file name
public void handleFileUpload(FileUploadEvent event) throws IOException {
FacesMessage msg = new FacesMessage("Plik: ", event.getFile().getFileName() + " został poprawnie wysłany na serwer.");
FacesContext.getCurrentInstance().addMessage(null, msg);
String path = destination;
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
String name = fmt.format(new Date())
+ event.getFile().getFileName().substring(
event.getFile().getFileName().lastIndexOf('.'));
File file = new File(path + name);
sciezkaPliku += path + name; // I set file path here
InputStream is = event.getFile().getInputstream();
OutputStream out = new FileOutputStream(file);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
out.write(buf, 0, len);
is.close();
out.close();
}
public String getSciezkaPliku() {
return sciezkaPliku;
}
public void setSciezkaPliku(String sciezkaPliku) {
this.sciezkaPliku = sciezkaPliku;
}
}
It is declared as a ManagedBean because I've tried to access its sciezkaPliku variable which is filepath from wydarzenieMB like this:
#ManagedProperty(value="#{fileUploadController.sciezkaPliku}")
private String plakat;
But it was always null. I also tried to get whole wydarzenieMB inside fileUploadController and use it's setter method:
#ManagedBean(name="fileUploadController")
#RequestScoped
public class FileUploadController
{
#ManagedProperty(value="#{wydarzenieMB}")
WydarzenieManagedBean w;
public void handleFileUpload(FileUploadEvent event) throws IOException {
...
sciezkaPliku += path + name; // I set file path here
w.setPlakat(sciezkaPliku);
...
}
...
}
But it was unsuccessful either. File is uploaded and saved in a specified folder without a problem, when I print sciezkaPliku from handleFileUpload it is ok, but when I am creating my new Wydarzenie using addWydarzenie() it is always null.
Any ideas?
If I've understood your question clearly, I suggest you to change your scope to "#SessionScoped" in FileUploadController. I had a same problem and it was solved by this way.
check it out and inform me of the result ;)
Consoder the following code:
<h:commandButton value="do" action="#{testBacking.do}">
<f:ajax execute="#all" render="#all" listener="#{testBacking.listener}"/>
</h:commandButton>
I want to have a custom tag (with value based on server logic), in the Ajax response XML, something like the following:
<isValidationFailed> true </isValidationFailed>
I can use this data to re-enable the button (which was disabled when Ajax begin, to avoid double clicks) if validation is failed.
How can I achieve this (preferably without using any JSF 3rd party libraries)?
EDIT:
The example code, more precisely, should be like this:
<h:commandButton id="myButton" value="do" action="#{testBacking.do}">
<f:ajax execute="id1" render="id2 myButton" listener="#{testBacking.listener}"/>
</h:commandButton>
This is only possible with a custom PartialViewContext which you load into your JSF application using a PartialViewContextFactory. The custom PartialViewContext should in turn return a custom PartialResponseWriter on PartialViewContext#getResponseWriter(). In this custom PartialResponseWriter, you should be able to add extensions to the XML response by calling startExtension() and endExtension() in endDocument(). Something like:
#Override
public void endDocument() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("name1", "value1");
attributes.put("name2", "value2");
startExtension(attributes);
write("lorem ipsum");
endExtension();
super.endDocument();
}
This will then end up in the XML response as
<extension name1="value1" name2="value2">lorem ipsum</extension>
This is available and traversable by data.responseXML in jsf.ajax.addOnEvent() function.
Here's a full kickoff example how you could utilize it in your particular case:
MyPartialViewContextFactory which provides the custom partial view context:
public class MyPartialViewContextFactory extends PartialViewContextFactory {
private PartialViewContextFactory wrapped;
public MyPartialViewContextFactory(PartialViewContextFactory wrapped) {
this.wrapped = wrapped;
}
#Override
public PartialViewContext getPartialViewContext(FacesContext context) {
return new MyPartialViewContext(wrapped.getPartialViewContext(context));
}
}
MyPartialViewContext which provides the custom partial response writer:
public class MyPartialViewContext extends PartialViewContextWrapper {
private PartialViewContext wrapped;
private PartialResponseWriter writer;
public MyPartialViewContext(PartialViewContext wrapped) {
this.wrapped = wrapped;
this.writer = new MyPartialResponseWriter(wrapped.getPartialResponseWriter());
}
#Override
public PartialResponseWriter getPartialResponseWriter() {
return writer;
}
#Override
public void setPartialRequest(boolean isPartialRequest) {
wrapped.setPartialRequest(isPartialRequest);
}
#Override
public PartialViewContext getWrapped() {
return wrapped;
}
}
MyPartialResponseWriter which writes <extension id="myextension"> with the body as JSON):
public class MyPartialResponseWriter extends PartialResponseWriter {
public MyPartialResponseWriter(ResponseWriter wrapped) {
super(wrapped);
}
#Override
public void endDocument() throws IOException {
startExtension(Collections.singletonMap("id", "myextension"));
write("{\"validationFailed\": " + FacesContext.getCurrentInstance().isValidationFailed() + "}"); // Consider a JSON serializer, like Google Gson.
endExtension();
super.endDocument();
}
}
To get it to run, register the factory as follows in faces-config.xml:
<factory>
<partial-view-context-factory>com.example.MyPartialViewContextFactory</partial-view-context-factory>
</factory>
Here's how you can access, parse and use the <extension id="myextension"> in your jsf.ajax.addOnEvent():
jsf.ajax.addOnEvent(function(data) {
if (data.status == "success") {
var args = JSON.parse(data.responseXML.getElementById("myextension").firstChild.nodeValue);
if (args.validationFailed) {
// ...
}
else {
// ...
}
}
});
However, your particular functional requirement can be achieved in a different, likely simpler, manner. Just let the ajax request update the button itself and let the button's disabled attribute evaluate true when there's means of a successful postback.
<h:commandButton id="myButton" value="do" action="#{testBacking.do}"
disabled="#{facesContext.postback and not facesContext.validationFailed}">
<f:ajax execute="id1" render="#this id2" listener="#{testBacking.listener}"/>
</h:commandButton>
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.