JSP, Spring - assign to object selected value from drop down box - java

In JSP in drop down box I have a list of countries. Selected country I should assign to "Organization" object as an object "Country".
JSP:
<select name="country">
<c:forEach var="country" items="${countries}" >
<option value="${country}">
<c:out value="${country.name}" />
</option>
</c:forEach>
</select>
Model, Organisation:
#Entity
public class Organization {
#Id
#GeneratedValue
private Integer id;
private String name;
//I should assign "Country" object to this field
#OneToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JoinColumn(name="country")
private Country country;
private String address;
private String phone;
private Long market_cap;
public Organization(Integer id, String name, Country country, String address, String phone, Long market_cap) {
this.id = id;
this.name = name;
this.country = country;
this.address = address;
this.phone = phone;
this.market_cap = market_cap;
}
public Organization() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Long getMarket_cap() {
return market_cap;
}
public void setMarketCap(Long market_cap) {
this.market_cap = market_cap;
}
}
Model, Country:
#Entity
public class Country {
#Id
#GeneratedValue
private Integer id_country;
private String name;
private String isocode;
public Country() {
}
public Country(Integer id_country, String name, String isocode) {
this.id_country = id_country;
this.name = name;
this.isocode = isocode;
}
public Integer getId_country() {
return id_country;
}
public void setId_country(Integer id_country) {
this.id_country = id_country;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsocode() {
return isocode;
}
public void setIsocode(String isocode) {
this.isocode = isocode;
}
}
Controller method:
#RequestMapping(value="add", method=RequestMethod.GET)
public ModelAndView addOrganization() {
ModelAndView modelAndView = new ModelAndView("add");
Organization organization = new Organization();
modelAndView.addObject("organization", organization);
List<Country> countries = countryService.listOfCountries();
modelAndView.addObject("countries", countries);
return modelAndView;
}
I have Bad Request error.

Related

Looping through the entire firebase data

I would like to find the data of all the users and sum of their scores on particular questions and find the highest rank
Now I can walk through the data users data but not through the questions node.
How do read all the data
This is how I have created my POJO :
private String id;
private String name;
private String contact;
private String email;
private String password;
private int score;
private String dob;
private String profession;
private String random;
private String status;
private String fbId;
private UserPuzzleDetails userPuzzleDetails;
public User() {
}
public User(String id, String name, String contact, String email, String password, int score,
String dob, String profession, String random, String status, String facebookid, UserPuzzleDetails userPuzzleDetails1) {
this.id = id;
this.name = name;
this.contact = contact;
this.email = email;
this.password = password;
this.score = score;
this.dob = dob;
this.profession = profession;
this.random = random;
this.status = status;
this.fbId = facebookid;
this.userPuzzleDetails = userPuzzleDetails1;
}
public User(String id, String name, String contact, String email, String password, int score,
String dob, String profession, String random, String status, String facebookid) {
this.id = id;
this.name = name;
this.contact = contact;
this.email = email;
this.password = password;
this.score = score;
this.dob = dob;
this.profession = profession;
this.random = random;
this.status = status;
this.fbId = facebookid;
}
public User(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getContact() {
return contact;
}
public String getDob() {
return dob;
}
public String getProfession() {
return profession;
}
public String getRandom() {
return random;
}
public UserPuzzleDetails getUserPuzzleDetails() {
return userPuzzleDetails;
}
public void setUserPuzzleDetails(UserPuzzleDetails questions) {
this.userPuzzleDetails = questions;
}
public String getStatus() {
return status;
}
public String getFbId() {
return fbId;
}
public void setFbId(String fbId) {
this.fbId = fbId;
}
Now I have used this function to retrieve the data but it is not logging.
How should I go by this data iterate through it.
private void getAllRank() {
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
final Query query = databaseReference.orderByChild("score").limitToLast(10);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userlist = new ArrayList<>();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
User score = postSnapshot.getValue(User.class);
userlist.add(new User(score.getId(), score.getName(), score.getContact(), score.getEmail(),
score.getPassword(), score.getScore(), score.getProfession(), score.getDob(), score.getRandom(), score.getStatus(), score.getFbId(),score.getUserPuzzleDetails()));
Log.e(TAG, "onDataChange: "+userlist );
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Hibernate OneToOne relationship

I have 3 classes Appointment,Patient and Doctor.Appointment have 1to1 reletionship with both Patient and Doctor.
When i insert a appointment object in database everytime the new patient and doctor object is also inserted in the database.
Patient Class:
#Entity
#Table(name = "Patient")
public class Patient {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int patientId;
private String firstName;
private String lastName;
private int age;
private String cnic;
private String contactNumber;
private String homeNumber;
private String country;
private String city;
private String town;
private String streetNo;
private String houseNo;
private String email;
private String username;
private String password;
public int getPatientId() {
return patientId;
}
public void setPatientId(int patientId) {
this.patientId = patientId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCnic() {
return cnic;
}
public void setCnic(String cnic) {
this.cnic = cnic;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getHomeNumber() {
return homeNumber;
}
public void setHomeNumber(String homeNumber) {
this.homeNumber = homeNumber;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getStreetNo() {
return streetNo;
}
public void setStreetNo(String streetNo) {
this.streetNo = streetNo;
}
public String getHouseNo() {
return houseNo;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId(){
return patientId;
}
public Patient getPatient(){
return this;
}
}
Doctor Class :
#Entity
#Table(name = "Doctor")
public class Doctor extends Users {
private String specialization;
public String getSpecialization() {
return specialization;
}
public void setSpecialization(String specialization) {
this.specialization = specialization;
}
}
Appointment Class:
#Entity
public class AppointmentClass {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int appointmentId;
private int appointmentDay;
private int appointmentTime;
#OneToOne (cascade=CascadeType.ALL,fetch = FetchType.EAGER)
private Patient patient;
#OneToOne (cascade=CascadeType.ALL,fetch = FetchType.EAGER)
private Doctor doctor;
public int getAppointmentId() {
return appointmentId;
}
public void setAppointmentId(int appointmentId) {
this.appointmentId = appointmentId;
}
public int getAppointmentDay() {
return appointmentDay;
}
public void setAppointmentDay(int appointmentDay) {
this.appointmentDay = appointmentDay;
}
public int getAppointmentTime() {
return appointmentTime;
}
public void setAppointmentTime(int appointmentTime) {
this.appointmentTime = appointmentTime;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public Doctor getDoctor() {
return doctor;
}
public void setDoctor(Doctor doctor) {
this.doctor = doctor;
}
}
Service Class:
public class AppointmentPatientService {
private SessionFactory sessionFactory = null;
public AppoinmentPatient createNewAppointment(AppoinmentPatient appointment){
try{
sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Patient patient = new Patient();
Doctor doctor = new Doctor();
patient = (Patient)(appointment).getPatient();
AppointmentClass appointment1 = new AppointmentClass();
appointment1 = (AppointmentClass)(appointment).getAppointment();
doctor = (Doctor)appointment.getDoctor();
appointment1.setPatient(patient);
appointment1.setDoctor(doctor);
session.beginTransaction();
session.save(appointment1);
session.getTransaction().commit();
session.close();
}catch(Exception ex){
ex.printStackTrace();
}
return appointment;
}
}
Is there any way that when i save the appointment object the new objects of patient and doctor not save to the database.
I shall be thankful :)
I think your relationship type should not be OneToOne from neither the doctor or the patient, because one doctor can have many appointments and one patient can have many appointments. So it should be OneToMany from both sides, in which case a new doctor and a new patient won't be created for each new appointment if you supply the appointment with correct existing doctor and patient ID-s.
In the class AppointmentClass, change the cascade settings.
You can use cascade=CascadeType.NONE, This will make sure that the associated Patient and Doctor objects are not saved to database.
You can see all other values of CascadeType to find the right choice for you.

Referring path variable in jsp Spring framework

I pass couple of objects "Studentdetails" and String-"dept" to JSP.
Question-
How will I refer studentdetail.st.fname in my JSP file? ie; need to refer the firstname from the Student object.
I tried this and its failing -
<form:label path="s.studentdetail.st.fname" class="labels">First Name</form:label>
AND
<form:label path="studentdetail.st.fname" class="labels">First Name</form:label>
#RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("studentdetail", new Studentdetails());
model.put("department", "dept");
return new ModelAndView("student", "s", model);
}
Studentdetails:
public class Studentdetails {
public ContactInfo getCi() {
return ci;
}
public void setCi(ContactInfo ci) {
this.ci = ci;
}
public Student getSt() {
return st;
}
public void setSt(Student st) {
this.st = st;
}
ContactInfo ci;
Student st;
}
Student:
public class Student {
private Integer age;
private String fname;
private String mname;
private String lname;
private String dob;
private String gender;
private String birthplace;
private String nationality;
private String mothertongue;
private String religion;
private Integer id;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getBirthplace() {
return birthplace;
}
public void setBirthplace(String birthplace) {
this.birthplace = birthplace;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getMothertongue() {
return mothertongue;
}
public void setMothertongue(String mothertongue) {
this.mothertongue = mothertongue;
}
public String getReligion() {
return religion;
}
public void setReligion(String religion) {
this.religion = religion;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
COntactinfo
public class ContactInfo {
String addr1;
String addr2;
String city;
String state;
String pin;
String country;
String phone;
String mobile;
String email;
public String getAddr1() {
return addr1;
}
public void setAddr1(String addr1) {
this.addr1 = addr1;
}
public String getAddr2() {
return addr2;
}
public void setAddr2(String addr2) {
this.addr2 = addr2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Working code:---
<h2>Student Information</h2>
<form:form method="POST" action="/SpringMVC/addStudent" modelAttribute="studentdetail">
<br><br>
<form:label path="st.fname" class="labels">First Name</form:label>
<form:input path="st.fname" class="textbox" />
<br><br>
studentdetail:${studentdetail.st.fname}
<br>
Department:${department}
<br><br>
</form>
Controller:-
#RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("studentdetail", new Studentdetails());
model.put("department", "dept");
return new ModelAndView("student",model);
Try :
<form:label path="s['studentdetail'].st.fname" class="labels">First Name</form:label>
If you are using an array of Studentdetails then you have to use that array on your form declaration on the modelAndAttribute field, and then using a foreach to iterate everyone, and using the index.
<form:form
id=""
method="post"
action=""
modelAttribute="studentdetail">
<form:input type="text" id=""
path="studentdetail.st.fname"/>
</form:form>
First your construction of a ModelAndView is at least uncommon. You add an unnecessary level of indirection by putting in string model an only attribute s that contains the real model. In JSP you should have to use ${s["studentdetail"].st.fname} ... if you had initialized studentdetail.st ...
IMHO, you'd better change your method to :
public ModelAndView student() {
Map<String, Object> model = new HashMap<String, Object>();
Studentdetails studentdetail = new Studentdetails());
studentdetail = new Studentdetails());
studentdetail.setSt(new Student()); //put a Student in studentdetail
model.put("studentdetail", studentdetail);
model.put("department", "dept");
return new ModelAndView("student", model); // directly use model in ModelAndView
}
Then in the JSP, you simply use ${studentdetail.st.fname}

Strange mysql retrieve with hibernate criteria

In a web-service i have the following function which retreives some infos of a doctor and his patient based on patient's phone:
public String findDoctorOfPatient(String phone) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.configure("hibernate.cfg.xml");
SessionFactory factory = config.buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
Criteria query = session.createCriteria(doctor.class);
query.createCriteria("patients", "p");
query.add(Restrictions.eq("p.phone", phone));
List<doctor> doctorList = (ArrayList<doctor>) query.list();
session.getTransaction().commit();
String answear = "";
for (doctor d : doctorList) {
answear = answear.concat("docPhone" + d.getPhone() + "docEmail"
+ d.getEmail() + "patDia"
+ d.getPatients().iterator().next().getDiastolic()
+ "patSys"
+ d.getPatients().iterator().next().getSystolic());
}
if (doctorList.isEmpty()) {
session.close();
factory.close();
return "No Doctor!";
} else {
session.close();
factory.close();
return answear;
}
}
The problem is when i have one patient is ok , but when i add second patient it gives me the details of last patient despite i have set to criteria tha firt's patient phone!
I have 2 tables:
1.doctor(id,username,password,phone,email)
2.patient(id,name,surname,phone,systolic,diastolic,doctorid(FK refers to doctor.id))
I have configured properly the hibernate.cfg.xml.
And i have set the class for doctor and patient:
#Entity
public class doctor {
#Id
private int id;
private String username;
private String password;
private String phone;
private String email;
#OneToMany(targetEntity = patient.class, cascade = CascadeType.ALL, mappedBy = "doctor")
#Cascade(value = org.hibernate.annotations.CascadeType.ALL)
private Collection<patient> patients = new ArrayList<patient>();
public Collection<patient> getPatients() {
return patients;
}
public void setPatients(Collection<patient> patients) {
this.patients = patients;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
#Entity
public class patient {
#Id
private int id;
private String name;
private String surname;
private String phone;
private int systolic;
private int diastolic;
#ManyToOne
private doctor doctor;
public doctor getDoctor() {
return doctor;
}
public void setDoctor(doctor doctor) {
this.doctor = doctor;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getSystolic() {
return systolic;
}
public void setSystolic(int systolic) {
this.systolic = systolic;
}
public int getDiastolic() {
return diastolic;
}
public void setDiastolic(int diastolic) {
this.diastolic = diastolic;
}
}
In this web-service the response is always the same (given the mobile number) .
It gives me always the patSys=130 and patDia=80 which are the second's patient info!.Something must be wrong in the webservice but to me all seems ok!
You need to create Criteria object on Patient and no need to obtain transaction here.
Criteria query = session.createCriteria(Patient.class)
.add(Restrictions.eq("phone", phone));
List<Patient> patList = (ArrayList<Patient>) query.list();
String result="";
if(!patList.isEmpty()) {
Patient patient=patList.get(0);
result="Doc Phone : " + patient.getDoctor().getPhone();
}
return result;

How to display ArrayList in JSF page

I want to create editable h:panelGrid. I created this ArrayList:
public ArrayList<userdata> dataList = new ArrayList<>();
public class userdata
{
int userid;
int groupid;
String specialnumber;
String username;
String passwd;
Date datetochangepasswd;
String address;
String stateregion;
String country;
String userstatus;
String telephone;
Date dateuseradded;
Date userexpiredate;
Date dateuserlocked;
String city;
String email;
String description;
public userdata(int userid, int groupid, String specialnumber, String username, String passwd, Date datetochangepasswd,
String address, String stateregion, String country, String userstatus, String telephone, Date dateuseradded,
Date userexpiredate, Date dateuserlocked, String city, String email, String description)
{
this.userid = userid;
this.groupid = groupid;
this.specialnumber = specialnumber;
this.username = username;
this.passwd = passwd;
this.datetochangepasswd = datetochangepasswd;
this.address = address;
this.stateregion = stateregion;
this.country = country;
this.userstatus = userstatus;
this.telephone = telephone;
this.dateuseradded = dateuseradded;
this.userexpiredate = userexpiredate;
this.dateuserlocked = dateuserlocked;
this.city = city;
this.email = email;
this.description = description;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
public Date getDatetochangepasswd()
{
return datetochangepasswd;
}
public void setDatetochangepasswd(Date datetochangepasswd)
{
this.datetochangepasswd = datetochangepasswd;
}
public Date getDateuseradded()
{
return dateuseradded;
}
public void setDateuseradded(Date dateuseradded)
{
this.dateuseradded = dateuseradded;
}
public Date getDateuserlocked()
{
return dateuserlocked;
}
public void setDateuserlocked(Date dateuserlocked)
{
this.dateuserlocked = dateuserlocked;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public int getGroupid()
{
return groupid;
}
public void setGroupid(int groupid)
{
this.groupid = groupid;
}
public String getPasswd()
{
return passwd;
}
public void setPasswd(String passwd)
{
this.passwd = passwd;
}
public String getSpecialnumber()
{
return specialnumber;
}
public void setSpecialnumber(String specialnumber)
{
this.specialnumber = specialnumber;
}
public String getStateregion()
{
return stateregion;
}
public void setStateregion(String stateregion)
{
this.stateregion = stateregion;
}
public String getTelephone()
{
return telephone;
}
public void setTelephone(String telephone)
{
this.telephone = telephone;
}
public Date getUserexpiredate()
{
return userexpiredate;
}
public void setUserexpiredate(Date userexpiredate)
{
this.userexpiredate = userexpiredate;
}
public int getUserid()
{
return userid;
}
public void setUserid(int userid)
{
this.userid = userid;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getUserstatus()
{
return userstatus;
}
public void setUserstatus(String userstatus)
{
this.userstatus = userstatus;
}
}
// Getter for the data list
public ArrayList<userdata> getuserdata(){
return dataList;
}
I want to display the data into h:panelGrid. Can you tell me how I can do this?
I want to create this editable table but with h:panelGrid. I suppose that it's possible to use h:panelGrid instead h:dataTable?
Best wishes
While it may be actually possible to hack something with h:panelGrid, you probably would have to fiddle with a lot of unnecessary code in your MBs, just for creating and binding components.
If you want a finer grained control for your HTML table, what you want to do is probably to use ui:repeat, something like this:
<table>
<ui:repeat var="elem" value="#{yourMB.yourDataList}">
<tr>
<td>#{elem.userid}</td>
<td>
<h:outputText value="#{elem.name}"
rendered="#{not elem.editable}" />
<h:inputText value="#{elem.name}" rendered="#{elem.editable}" />
</td>
<td>
<h:outputText value="#{elem.telephone}"
rendered="#{not elem.editable}" />
<h:inputText value="#{elem.telephone}"
rendered="#{elem.editable}" />
</td>
<td>
<h:commandLink value="Edit" rendered="#{not elem.editable}"
action="#{yourMB.editAction(elem)}" />
</td>
</tr>
</ui:repeat>
</table>
<h:commandButton value="Save Changes" action="#{yourMB.saveAction}" />
For this to work you should have a backing bean looking like this:
#ManagedBean
#ViewScoped
public class YourMB {
private List<Elem> dataList;
#PostConstruct
public void init() {
// initialize dataList here
}
public void editAction(Elem e) {
e.setEditable(true);
}
public void saveAction() {
// do your thing here to update in the database,
// and then reset the editable property for all items:
for (Elem e : dataList) {
e.setEditable(false);
}
}
// getters and setters...
}
Check out the tutorials available here, which teaches how to use ui:repeat and also presents other options for looping in JSF.

Categories