Spring portlet form: #ModelAttribute not populated - forms

I am a beginner at Spring and I was wondering why my ModelAttribute did not populate (All the values were null)
I want to create a multipart from that allows me to upload a csv file as well as the type of CSV file too.
My codes are as such:
In the CSVUpload-portlet.xml:
<bean class="org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000000"></property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
CSVUploadPortlet.java (Controller)
*All imports
#Controller("uploadCsvToDatabase")
#RequestMapping(value = "VIEW")
public class CSVUploadPortlet {
private static final Logger log = Logger.getLogger(CSVUploadPortlet.class);
private static IWBCSVUploadRemote csvupload;
#RenderMapping
public String viewCSVUploadBase(Model model, RenderRequest request) {
try {
} catch (Exception e) {
e.printStackTrace();
log.info("problem in retrieving the CSV Upload service" + e);
}
return "csvupload/csvupload_view";
}
#ModelAttribute("csvFileUploadVO")
public CSVFileUploadVO getCommandObject()
{
System.out.println("SpringFileController -> getCommandObject -> Building VO");
return new CSVFileUploadVO();
}
#ActionMapping(params="action=uploadCsvToDatabase")
public void uploadCsvToDatabase(
#ModelAttribute("csvFileUploadVO") CSVFileUploadVO csvFileUploadVO, BindingResult result, ActionRequest request, ActionResponse response, SessionStatus sessionStatus){
try{
System.out.println("FileType:"+csvFileUploadVO.getFileType()); //This returns null
System.out.println("CSVFile Size:"+csvFileUploadVO.getCsvFile().getSize()); //This returns a null-pointer exception
} catch (Exception e) {
log.info("Problem in retrieving the CSVUpload configuration list " + e);
e.printStackTrace();
}
}
}
CSVFileUploadVO.java
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class CSVFileUploadVO {
private String fileType;
private CommonsMultipartFile csvFile;
private String message;
public CSVFileUploadVO() {
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public CommonsMultipartFile getCsvFile() {
return csvFile;
}
public void setCsvFile(CommonsMultipartFile csvFile) {
this.csvFile = csvFile;
}
}
Form JSP
All taglibs imported...
<portlet:actionURL var="fileUploadURL">
<portlet:param name="action" value="uploadCsvToDatabase" />
</portlet:actionURL>
<form:form method="post" action="${fileUploadURL}"
commandName="csvFileUploadVO" enctype="multipart/form-data">
<table>
<tbody>
<tr>
<td><label>Department:</label></td>
<td><form:select path="fileType">
<form:option value="BRMAdd" label="BRM Add" />
<form:option value="FOSAdmin" label="FOS Admin" />
<form:option value="FOSRM" label="FOS RM" />
<form:option value="FOSTeam" label="FOS Team" />
<form:option value="ITRelationships" label="IT Relationships" />
<form:option value="HRAttendance" label="HR Attendance" />
<form:option value="iCareCallReport" label="iCare Call Report" />
</form:select></td>
</tr>
<tr>
<td><label>Specify your File:</label></td>
<td><form:input path="csvFile" type="file" /></td>
</tr>
<tr>
<tr>
<td colspan="100%"><input type="submit" value="Submit" /></td>
</tr>
<tr>
<td colspan="100%">${csvFileUploadVO.message}</td>
</tr>
</tbody>
</table>
</form:form>
I know it seems like asking you to help solve a problem for me but I've been stuck on this for 8 hours, reading every resource and stackoverflow website i could google on. But despite that, I wasn't able to find anything.
Thank you for your help in this.

You will want to look at http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html#mvc-multipart-resolver particularly the RequestMapping where the parameter is MultipartFile
#RequestMapping(value = "/form", method = RequestMethod.POST)
public String handleFormUpload(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) {

You have to define the ModelAttribute in your JSP form, something like this:
<form:form method="post" action="${fileUploadURL}"
modelAttribute="csvFileUploadVO" enctype="multipart/form-data">

Liferay 6.0.5 and Spring 3.2.2.RELEASE:
I tried with editing spring classes, but there is much easier solution to this problem. Just check whether your CommonsPortletMultipartResolver really has been initilized. The fact that it is declared in spring.xml does not mean that it is loaded.
If it is not initialized, than the file part of the request would never be converted to CommonsMultipartFile because your request would not be a commons Multipart request.
CommonsPortletMultipartResolver will be invoked by org.springframework.web.portlet.DispatcherPortlet lifecycle if it is loaded and spring uses this class.

Your multipart resolver must have the id portletMultipartResolver and be of type org.springframework.web.portlet.multipart.CommonsPortletMultipartResolver
<bean id="portletMultipartResolver" class="org.springframework.web.portlet.multipart.CommonsPortletMultipartResolver">
</bean>

Related

Get list from DB using stuts2

I have a list in Stuts2 and I would like to see it in the jpa I put the name of the list but I dosen't work and I dont recive any error
<s:iterator value="UserService.users">
<tr>
<td><s:property value="nom" /></td>
<td><s:property value="prenom" /></td>
<td><s:property value="username" /></td>
<td><s:property value="password" /></td>
<td><s:property value="tel" /></td>
</tr>
</s:iterator>
public static void list() {
SessionFactory sessionFactory = new Configuration().
configure("hibernate.cfg.xml").
addAnnotatedClass(User.class).
buildSessionFactory();
Session session = sessionFactory.openSession();
try{
session.beginTransaction();
List<User> users = session.createQuery("from User").getResultList();
for(User u : users){
System.out.println(u);
}
session.getTransaction().commit();
}finally{
sessionFactory.close();
}
}
A Struts 2 tutorial will save you some time; this is very basic and shows little effort.
Make users a property on the action and expose it with a getter.
<s:iterator value="users">
<s:property value="nom" />
...

How Can I Access A Patient's Id?

Please have a look at the following Patient response that I received from http://fhirtest.uhn.ca/baseDstu3. I would like to access the 4081340 value in the id tag but I have been unable to find it in the org.hl7.fhir.dstu3.model.Patient API. Would someone please show me how?
<Patient xmlns="http://hl7.org/fhir">
<id value="4081340"></id>
<meta>
<versionId value="1"></versionId>
<lastUpdated value="2018-06-04T15:13:28.069+00:00"></lastUpdated>
</meta>
<text>
<status value="generated"></status>
<div xmlns="http://www.w3.org/1999/xhtml">
<div class="hapiHeaderText">Robert Jozef
<b>VAESSEN </b>
</div>
<table class="hapiPropertyTable">
<tbody>
<tr>
<td>Identifier</td>
<td>12345</td>
</tr>
<tr>
<td>Date of birth</td>
<td>
<span>30 January 1954</span>
</td>
</tr>
</tbody>
</table>
</div>
</text>
<identifier>
<system value="http://dmw.levy.com/mrn"></system>
<value value="12345"></value>
</identifier>
<name>
<family value="Vaessen"></family>
<given value="Robert"></given>
<given value="Jozef"></given>
</name>
<gender value="male"></gender>
<birthDate value="1954-01-30"></birthDate>
</Patient>
Update:
The reason that I want to access the 4081340 value is that I need it in order to execute code such as this:
private void deletePatient(String id) {
try {
OperationOutcome outcome = (OperationOutcome) client.delete().resourceById(new IdDt("Patient", id)).execute();
}
catch (Exception e) {
System.out.printf("Cannot delete patient with id = %s\n%s\n", id, e.getMessage());
}
}
private void retrievePatient(String id) {
try {
Patient patient = client.read().resource(Patient.class).withId(id).execute();
String description = parser.encodeResourceToString(patient);
System.out.printf("Successfully retrieved patient with ID = %s:\n%s\n", id, description);
}
catch (ResourceNotFoundException e) {
System.out.printf("Cannot find patient with id = %s\n", id);
}
}
The following statements all print http://hapi.fhir.org/baseDstu3/Patient/4081340/_history/1. I could parse that to obtain the 4081340
System.out.printf("\t%s\n", patient.getId());
System.out.printf("\t%s\n", patient.getIdBase());
System.out.printf("\t%s\n", patient.getIdElement());
When I examine a Patient in the debugger, I can see the value in the field myUnqualifiedId but I cannot discover how to get at it.
I found it:
patient.getIdElement().getIdPart()

Rendering a form based on bean field value

I want to ask user to input password before submitting a file. So <h:panelGroup> should be rendered after hit the Submit button. But, <h:panelGoup> never be rendered.
test.xhtml
<ui:define name="body">
<h:form id="uploadForm" enctype="multipart/form-data">
<table>
<t:inputFileUpload id="uploadedFile" storage="file"
value="#{UpdateBean.uploadedFile}"/>
<h:commandButton value="Submit" action="#{UpdateBean.submit()}"/>
</table>
</h:form>
<h:panelGroup id="checkPassword" rendered="#{UpdateBean.submitIsPerformed}">
<h:outputText id="message" value="${UpdateBean.message}" />
<h:inputText id="password" value="#{UpdateBean.password}" />
<h:commandButton value="submit" action="#{UpdateBean.submitPassword()}"/>
</h:panelGroup>
</ui:define>
UpdateBean.java
#ManagedBean(name = "UpdateBean")
#SessionScoped
public class UpdateBean {
protected boolean submitIsPerformed = false;
protected String password = "";
protected String message = "Input your password ";
// omit getter and setter
public void submit() {
this.setSubmitIsPerformed(true);
System.out.println(submitIsPerformed); // output is true
while(true) {
if(password.equals("123")) {
break;
}
}
// then process uploadedFile
}
public void submitPassword(){
if(password.equals("123")) {
message = "Password confirmed !";
} else {
message = "Password is wrong !";
}
}
}
Your mistake is in the submit() method:
while(true) {
if(password.equals("123")) {
break;
}
}
The while(true) prevents the action method from returning. As long as the action method doesn't return, the server won't return the HTTP response with the updated view. Effectively, one of your server's CPU is stuck into 100% and the client is infinitely waiting for HTTP response. You should have noticed it by checking the browser's progress indicator, if it has one.
You should basically immediately return after toggling the boolean:
public void submit() {
submitIsPerformed = true;
}
And perform the password checking and upload file saving in submitPassword() method. However, as this isn't in the same form, the uploaded file will get lost. Even if you put it in the same form, it would be uploaded twice. But that's a different problem. I suggest to do the job the other way round.
Follow the suggestion from #BalusC, this is my updated code.
test.xhtml
<ui:define name="body">
<h:form>
<h:commandButton value="Upload a file" action="#{UpdateBean.submit()}">
<f:ajax render=":checkPassword" />
</h:commandButton>
</h:form>
<h:form id="checkPassword" styleClass="toggle" rendered="#{UpdateBean.submitIsPerformed}">
<table>
<tr>
<td><h:outputText value="Password" /></td>
<td><h:inputText id="password" value="#{UpdateBean.password}" /></td>
<td>
<h:commandButton value="Submit" action="#{UpdateBean.submitPassword()}">
<f:ajax execute="password" render=":uploadFile" />
</h:commandButton>
</td>
</tr>
</table>
</h:form>
<h:form id="uploadFile" enctype="multipart/form-data"
styleClass="toggle" rendered="#{UpdateBean.uploadFileIsPerformed}">
<t:inputFileUpload id="uploadedFile" storage="file"
value="#{UpdateBean.uploadedFile}">
</t:inputFileUpload>
<h:commandButton value="Submit" action="#{UpdateBean.uploadFile()}" />
</h:form>
</ui:define>
UploadBean.java
public String submit() {
setSubmitIsPerformed(true);
return "SUCCESS";
}
public String submitPassword(){
if(password.equals("123"){
setUploadFileIsPerformed(true);
setSubmitIsPerformed(false);
}
return "SUCCESS";
}
public String uploadFile(){
return "SUCCESS";
}

Spring 3 form validation shows error messages but field name not displayed

I have a 2 item form, that requires that both fields be entered. I'm using annotated validations, and am getting error messages, but they do not print the field name, just "may not be blank" instead of "one may not be blank" where one is the field name.
Any ideas? This is a pretty simple example:
#Controller
#SessionAttributes
public class HomeController
{
private static final Logger logger = LoggerFactory
.getLogger(HomeController.class);
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model)
{
logger.info("Welcome home! The client locale is {}.", locale);
model.addAttribute("homeformitem", new HomeFormItem());
return "home";
}
#RequestMapping(value = "/", method = RequestMethod.POST)
public String home(
#ModelAttribute("homeformitem") #Valid HomeFormItem item,
BindingResult result)
{
logger.info("Posting form");
logger.info(item.toString());
if (result.hasErrors())
{
return "home";
} else
{
logger.info("No Errors");
return "done";
}
}
}
Here is the form. I get the error message, but not the field name.
Form Validation!
<f:form method="post" modelAttribute="homeformitem">
<fieldset>
<legend>Fields</legend>
<table>
<tr><td colspan="3"><f:errors path="*"/></td></tr>
<tr>
<td><f:label path="one" for="one">One: </f:label></td>
<td><f:input path="one" /></td>
<td><f:errors path="one" cssClass="errorblock"/></td>
</tr>
<tr>
<td><f:label path="two" for="two">Two: </f:label></td>
<td><f:input path="two" /></td>
<td><f:errors path="two" cssClass="errorblock"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Test" /></td>
</tr>
</table>
</fieldset>
</f:form>
You need a validation.properties file at /WEB-INF/messages with an entry similar to this (for example):
NotEmpty.homeFormItem.one=The field {0} is empty
And don't forget to add a spring bean to resolve your validation messages:
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/validation" />
</bean>

Spring 3 mvc nested form:select

In my scenario, i'm developing nested select on a JSP, binded to a bean:
Bean
public class WizardPanelp1Bean {
private Integer id;
private Stringofpanels stringofpanels;
private Paneltype paneltype;
private Integer number;
private String paneltypestring;
//and getters/setters... [Omitted]
Now i have the Paneltype object, another simple bean
Paneltype
private Integer id;
private double peakpower;
private double weight;
private String name;
private double dimension;
private double conversion;
private Set functions = new HashSet(0);
private Set sensors = new HashSet(0);
private Set panels = new HashSet(0);
//[Getters/setters omitted as usual]
So, i prepare the view, with a bean named wb
a simple arraylist of panels
public class PanelsBean {
private ArrayList<WizardPanelp1Bean> panels =new ArrayList<WizardPanelp1Bean>();
and finally i go to the jsp (please note this is in a )
<tbody>
<c:forEach items="${wb.panels}" varStatus="loop" var="item">
<tr>
<td>${item.id}</td>
<td>
<form:select path="panels[${loop.index}].paneltype" >
<c:forEach var="type" items="${types}">
<c:choose>
<c:when test="${item.paneltype.id==type.id}">
<form:option selected="selected" value="${type.id}" label="${type.name}" />
</c:when>
<c:otherwise>
<form:option value="${type.id}" label="${type.name}" />
</c:otherwise>
</c:choose>
</c:forEach>
</form:select>
</td>
<td><form:input style="width:180px" path="panels[${loop.index}].number" /></td>
<td>
<div>
<form:input style="visibility: hidden ; width:0px" path="panels[${loop.index}].id" disabled="disabled" />
<a href="javascript:remove(${item.id},${stringofpanels.id})" class="wb.panels.remove" >Rimuovi</a>
</div>
</td>
</tr>
</c:forEach>
</tbody>
every time i get a null reference to paneltype. I obviously used a #InitBinder on the controller:
Initbinder
#InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Paneltype.class, "paneltype", new PropertyEditorSupport() {
#Override
public void setAsText(String text) {
int i=0;
PaneltypeDAO pDAO=new PaneltypeDAO();
setValue(pDAO.findById(Integer.parseInt(text)));
}
});
}
but the code never reach this. It's like the jsp is sure that the value is null.
Suggestions? Thanks
I think your problem persists when you try to submit this form and not getting the binded values in the model.
Try to initialize your list using LazyList. Please replace your panels declaration in PanelsBean class as below.
private List<WizardPanelp1Bean> panels = LazyList.decorate(new ArrayList<WizardPanelp1Bean>(),FactoryUtils.instantiateFactory(WizardPanelp1Bean.class));
Hope this helps you. Cheers.