Get list from DB using stuts2 - jpa

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" />
...

Related

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()

Select field in grails workflow

I have a problem prefilling a dropdown list in an grails webflow
I have a controller for the webflow
class ClearanceRequestController {
def index() {
redirect(action: "start")
}
def startFlow = {
contact {
on('next') {
flow.developer = params.developer
flow.project = params.project
flow.projectResponsible = params.projectResponsible
flow.email = params.email
[flow : flow]
}.to('application')
on('cancel').to('finish')
...
and the view looks like this:
contact.gsp
<g:if test="${message}">
<div class="message">${message}</div>
</g:if>
<g:form action="start" method="post">
<div class="dialog">
<table>
<tbody>
<tr class="prop">
<td valign="top" class="name">
<label for="projectName">Projekt:</label>
</td>
<td valign="top">
<input type="text" id="projectName" name="project" value="${params.project}" />
</td>
</tr>
<g:select name="state" from="${Project?.DIVISION_OPTIONS}" value="${Project?.DIVISION_OPTIONS}"/>
This is the Project definition
class Project {
static DIVISION_OPTIONS = ["A", "B", "C", "D"]
String name
String division
String toString(){
"$name"
}
static constraints = {
name(unique: true)
division(inList: DIVISION_OPTIONS)
}
}
I don't know how to get the data from the constraints. I tried to access
Project.constraints.division.inList
or
Project.DIVISION_OPTIONS
but both didn't worked. I assume I have to initialize the Project somewhere and pass it to the contact.gsp, but I don't know how.
OK I got it, just import the Project in the page, like
<%# page import="com.companyName.Project" contentType="text/html;charset=UTF-8" %>
or like:
<g:select name="state" from="${com.companyName.Project?.DIVISION_OPTIONS}" value="${com.companyName.Project?.DIVISION_OPTIONS}"/>

Spring MVC: Displaying of validation messages after redirect

I have some very strange problem with displaying of error messages after redirect. I use RedirectAttributes to pass BindingResult object with error messages to a view, but this solution doesn't work.
When I return just a view name withou redirect, everything works fine.
Can someone give an advice, but without session usage?
#Controller
public class UserRegistrationController {
#Autowired
private UserService userService;
#RequestMapping(value="/registration", method=RequestMethod.GET)
public ModelAndView registrationPage() {
ModelAndView modelAndView = new ModelAndView("user-registration/registration-form");
modelAndView.addObject("user", new User());
return modelAndView;
}
#RequestMapping(value="/registration", method=RequestMethod.POST)
public ModelAndView registerUser(#ModelAttribute #Valid User user,
BindingResult result,
final RedirectAttributes redirectAttributes) {
ModelAndView modelAndView = new ModelAndView("redirect:registration.html");
User tempUser = userService.get(user.getEmail());
Map<String, String> messages = new HashMap<String, String>();
if (tempUser == null && ! result.hasErrors()) {
userService.save(user);
messages.put("success", "message.user.success.register");
} else {
messages.put("error", "message.user.invalid.register");
redirectAttributes.addFlashAttribute("user", user);
redirectAttributes.addFlashAttribute("errors", result);
}
redirectAttributes.addFlashAttribute("messages", messages);
return modelAndView;
}
}
And the view code:
<p>
<c:forEach var="message" items="${messages}">
<span class="${message.key}"><spring:message code="${message.value}" /></span><br />
</c:forEach>
</p>
<form:form method="POST" commandName="user" action="${pageContext.request.contextPath}/registration.html">
<table>
<tbody>
<tr>
<td><spring:message code="user.registration.email" /></td>
<td><form:input path="email" /></td>
<td><form:errors cssClass="error" path="email" /></td>
</tr>
<tr>
<td><spring:message code="user.registration.password" /></td>
<td><form:password path="password" /></td>
<td><form:errors cssClass="error" path="password" /></td>
</tr>
<tr>
<td><input type="submit" /></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</form:form>
Might want to look at this:
https://jira.springsource.org/browse/SPR-8968
And try returning a String rather than a ModelAndView
There should really be no reason to redirect while there are errors remain on the same page and only on success redirect. The reason for redirecting has to do with ensuring the browser does not attempt to repeat the same form submission when the back button is used, but while input is invalid the simplest thing to do is remain on the same page.

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>

Issue Binding AutoPopulating List to a form Spring MVC

I have an issue binding the AutoPupulating List in a form to update the data. I was able to save the data using Autopopulating list though.
Here is the form backing model.
public class AddUpdateShot {
private Integer shootId;
private char shotSelect;
private String shotNotes;
private Integer numOfItems;
private AutoPopulatingList itemNumColors;
private Integer totalNumOfItems;
private String shotName;
----------
public void setItemNumColors(AutoPopulatingList itemNumColors){
this.itemNumColors = itemNumColors;
}
public AutoPopulatingList getItemNumColors(){
return this.itemNumColors;
}
--------
}
Where itemNumClors is a simple model
public class ItemNumColor {
private Integer id;
private Integer itemNum;
private String itemName;
private String colorCode;
private String colorName;
------get and set methods
}
When I first saved the data, depending on how many ItemColors the user wanted,using jquery I added the input fields dynamically as shown in the following code.
<form:form id="createShootForm" method="POST"
commandName="createShoot">
<tr>
<td align="left"><label for="shootName">*Shoot Name:</label></td>
<td><form:input id="shootName" class="required" path="shootName" /></td>
</tr>
------- other input fields in form backing obj----
<c:forEach var="i" begin="${start}" end="${end-1}" step="1" varStatus="status">
<tr>
<td align="left"><label for="itemNumber${i}">Item
Number${i+1}:</label></td>
<td><form:input id="itemNumber${i}"
path="createShoot.itemNumColors[${i}].itemNum" /></td>
<td><form:select id="color${i}"
path="createShoot.itemNumColors[${i}].colorCode">
<form:option value="" label="Color" />
</form:select>
</td>
</tr>
</c:forEach>
<tr id="submitRow">
<td></td>
<td></td>
<td align="right"><input name="submit" type="submit" value="Next" /></td>
</tr>
</table>
</form:form>
The above code worked perfectly fine when I initially saved the data. But now when the user want to update the earlier saved data, I am unable to bind the Autopopulating list to the JSP. Here is how am doing it.
<form:form id="updateShotForm" method="POST"
commandName="shotToUpdate">
----other input fields of form backing object---
<c:forEach var="i" begin="0" end="${totalNumOfItems-1}" step="1"
varStatus="status">
<tr><td align="left"><label for="itemNumber${i}">ItemNumber${i+1}:</label></td>
<td><form:input id="itemNumber${i}"path="shotToUpdate.itemNumColors[${i}].itemNum" /></td>
</tr>
</c:forEach>
<tr id="submitRow">
<td></td>
<td></td>
<td align="right"><input name="submit" type="submit"
value="Next" />
</td>
</table>
</form:form>
When I open the edit JSP, I get the following run time exception
Sep 7, 2011 10:38:00 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jalapeno] in context with path [/OnLocation] threw exception [An exception occurred processing JSP page /WEB-INF/views/app/updateShot.jsp at line 256
253: <tr>
254: <td align="left"><label for="itemNumber${i}">Item
255: Number${i+1}:</label></td>
256: <td><form:input id="itemNumber${i}"
257: path="shotToUpdate.itemNumColors[${i}].itemNum" /></td>
258: <td><form:select id="color${i}"
259: path="shotToUpdate.itemNumColors[${i}].colorCode">
Stacktrace:] with root cause
org.springframework.beans.NotReadablePropertyException: Invalid property 'shotToUpdate' of bean class [com.jcrew.jalapeno.app.model.AddUpdateShot]: Bean property 'shotToUpdate' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:707)
at org.springframework.beans.BeanWrapperImpl.getNestedBeanWrapper(BeanWrapperImpl.java:555)
at org.springframework.beans.BeanWrapperImpl.getBeanWrapperForPropertyPath(BeanWrapperImpl.java:532)
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:697)
at org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:98)
at org.springframework.validation.AbstractBindingResult.getFieldValue(AbstractBindingResult.java:224)
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:120)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:160)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:123)
at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:408)
at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:140)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
I am not sure why I am not able to bind the object this way to the form since my form backing object does have an Autopopulating List which I initialised in the controller before loading this form
AutoPopulatingList itemNumColors = new AutoPopulatingList(ItemNumColor.class);
for( OnLocShotItemNumber onLocItemNumColor : itemNumColorsList){
ItemNumColor itemColor = new ItemNumColor();
itemColor.setId(onLocItemNumColor.getId());
itemColor.setColorCode(onLocItemNumColor.getItemColorCode());
itemColor.setItemNum(onLocItemNumColor.getItemNumber());
itemNumColors.add(itemColor);
}
shotToUpdate.setItemNumColors(itemNumColors);
model.put("shotToUpdate", shotToUpdate);
model.put("totalNumOfItems", itemNumColorsList.size());
Any help is greatly appreciated.
Thanks,
Shravanthi
Remove the 'shotToUpdate.' keyword from the PATH attribute. You have already specified the command object name so the PATH attributes should be relative to the command object.