Referring path variable in jsp Spring framework - java

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}

Related

org.hibernate.QueryException: could not resolve property with where clause

I am trying to get customers data in database based on condition where status of each customer is "Actve" this is the default value at the time of insertion but I am setting it deactivated in some query ultimately I want only those who have status "Active"
I did this
#Override
public List<Customer> listCustomers() {
return this.sessionFactory.getCurrentSession().createQuery("from customer).list();
}
But I am getting all active and deactivated customer
Then I did this
#Override
public List<Customer> listCustomers() {
return this.sessionFactory.getCurrentSession().createQuery("from com.mphasis.bharathbank.bean.customer where status="+"'Active'").list();
}
Here I am getting Exception
SEVERE: Servlet.service() for servlet [dispatcher] in context with
path [/BharathBank] threw exception [Request processing failed; nested
exception is org.hibernate.QueryException: could not resolve property:
status of: com.mphasis.bharathbank.bean.Customer [from
com.mphasis.bharathbank.bean.Customer as c where c.status=Active]]
with root cause org.hibernate.QueryException: could not resolve
property: status of: com.mphasis.bharathbank.bean.Customer [from
com.mphasis.bharathbank.bean.Customer as c where c.status=Active]
Model Customer Class
#Entity(name="customer")
#Table(name="customer")
public class Customer implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
#Column(name="CustID")
private int CustID;
#Column(name="Mobile_No")
private String mobileno;
#Column(name="F_Name")
private String fname;
#Column(name="L_Name")
private String lname;
#Column(name="Email_Id")
private String emailid;
#Column(name="DOB")
private String dob;
#Column(name="Gender")
private String gender;
#Column(name="Acc_No")
private String accno;
#Column(name="Pwd")
private String Pwd;
#Column(name="present_address")
private String present_address;
#Column(name="permanent_address")
private String permanent_address;
#Column(name="occupation")
private String occupation;
#Column(name="marital_status")
private String marital_status;
#Column(name="adhaar_card_no")
private String adhaar_no;
#Column(name="pan")
private String pan;
#Column(name="Balance")
private String initial_bal;
#Column(name="status")
private String accstatus;
public String getAccstatus() {
return accstatus;
}
public void setAccstatus(String accstatus) {
this.accstatus = accstatus;
}
public int getCustID() {
return CustID;
}
public void setCustID(int custID) {
CustID = custID;
}
public String getMobileno() {
return mobileno;
}
public void setMobileno(String mobileno) {
this.mobileno = mobileno;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
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 getAccno() {
return accno;
}
public void setAccno(String accno) {
this.accno = accno;
}
public String getPwd() {
return Pwd;
}
public void setPwd(String pwd) {
Pwd = pwd;
}
public String getPresent_address() {
return present_address;
}
public void setPresent_address(String present_address) {
this.present_address = present_address;
}
public String getPermanent_address() {
return permanent_address;
}
public void setPermanent_address(String permanent_address) {
this.permanent_address = permanent_address;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getMarital_status() {
return marital_status;
}
public void setMarital_status(String marital_status) {
this.marital_status = marital_status;
}
public String getAdhaar_no() {
return adhaar_no;
}
public void setAdhaar_no(String adhaar_no) {
this.adhaar_no = adhaar_no;
}
public String getPan() {
return pan;
}
public void setPan(String pan) {
this.pan = pan;
}
public String getInitial_bal() {
return initial_bal;
}
public void setInitial_bal(String initial_bal) {
this.initial_bal = initial_bal;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}

How to map JSONObject in Java object

I have to map this JSONObject into a Java object.
This is my Json:
{"WALLET":{
"ID":"1234",
"BAL":"20.000",
"NAME":"Filomena",
"EMAIL":"filo#gmail.com",
"DOCS":[
{
"ID":"001",
"S":"0",
"TYPE":"CardId",
"VD":"2019"
}
],
"IBANS":[
{
"ID":"001",
"S":"1",
"DATA":"iban",
"SWIFT":"swiftCode",
"HOLDER":"holder"
}
],
"STATUS":"string",
"BLOCKED":"1",
"SDDMANDATES":[
{
"ID":"sddMandateId",
"S":"status",
"DATA":"iban",
"SWIFT":"swiftCode"
}
],
"LWID":"string",
"CARDS":[
{
"ID":"string",
"EXTRA":{
"IS3DS":"string",
"CTRY":"string",
"AUTH":"string",
"NUM":"string",
"EXP":"string",
"TYP":"string"
}
}
],
"FirstName":"string",
"LastName":"string",
"CompanyName":"string",
"CompanyDescription":"string",
"CompanyWebsite":"string"
}
}
This is my Java class:
public class Wallet {
private String id;
private String bal;
private String name;
private String email;
private List<Doc> docs;
private List<Iban> ibans;
private String status;
private String blocked;
private List<SddMandate> sddMandates ;
private String lwid;
private List<Card> cards;
private String firstName;
private String lastname;
private String companyName;
private String companyDescription;
private String companyWebSite;
public Wallet(){
}
public Wallet(String id, String bal, String name, String email, List<Doc> docs, List<Iban> ibans, String status,
String blocked, List<SddMandate> sddMandates, String lwid, List<Card> cards, String firstName,
String lastname, String companyName, String companyDescription, String companyWebSite) {
super();
this.id = id;
this.bal = bal;
this.name = name;
this.email = email;
this.docs = docs;
this.ibans = ibans;
this.status = status;
this.blocked = blocked;
this.sddMandates = sddMandates;
this.lwid = lwid;
this.cards = cards;
this.firstName = firstName;
this.lastname = lastname;
this.companyName = companyName;
this.companyDescription = companyDescription;
this.companyWebSite = companyWebSite;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBal() {
return bal;
}
public void setBal(String bal) {
this.bal = bal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Doc> getDocs() {
return docs;
}
public void setDocs(List<Doc> docs) {
this.docs = docs;
}
public List<Iban> getIbans() {
return ibans;
}
public void setIbans(List<Iban> ibans) {
this.ibans = ibans;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getBlocked() {
return blocked;
}
public void setBlocked(String blocked) {
this.blocked = blocked;
}
public List<SddMandate> getSddMandates() {
return sddMandates;
}
public void setSddMandates(List<SddMandate> sddMandates) {
this.sddMandates = sddMandates;
}
public String getLwid() {
return lwid;
}
public void setLwid(String lwid) {
this.lwid = lwid;
}
public List<Card> getCards() {
return cards;
}
public void setCards(List<Card> cards) {
this.cards = cards;
}
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 String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyDescription() {
return companyDescription;
}
public void setCompanyDescription(String companyDescription) {
this.companyDescription = companyDescription;
}
public String getCompanyWebSite() {
return companyWebSite;
}
public void setCompanyWebSite(String companyWebSite) {
this.companyWebSite = companyWebSite;
}
Now i'm trying to map the object with gson library.
Wallet walletDetails=gson.fromJson(rispostaGetWalletDetails.toString(), Wallet.class);
System.out.println("Balance: "+walletDetails.getBal());
Now when i try to call method on the object i have always null and not the real value.
How i can do?
You have a wrong root level.
Probably, you need to need to get one level down
JSONObject yourObject = json.get("WALLET");
Wallet walletDetails = gson.fromJson(yourObject.toString(), Wallet.class);
To have Gson handle the correct field name mapping while deserializing, you have to register a FieldNamingStrategy like this (using Java 8):
Gson gson = new GsonBuilder()
.setFieldNamingStrategy(field -> field.getName().toUpperCase())
.create();
The strategy will convert each Java field name to match those in your JSON.
This will cover almost all your fields except for those upper-camel-cased in the JSON response, such as "LastName", "CompanyName", etc. In order to map those too, your FieldNamingStrategy will have to become a little bit smarter, like:
field -> {
String fname = field.getName();
return "firstName".equals(fname) || "companyName".equals(fname) /*etc...*/ ? capitalize(fname) : fname.toUpperCase();
}
and so on, I think you got the idea.
The capitalize() method you can find in libraries like Apache Commons Lang or write your own, it's just for examplification here.
Your object variable name doesn't match the json attribute name. "EMAIL" in json should have same EMAIL in object. To overcome this, you could mention #JsonProperty before your attribute declaraction.
for eg:
#JsonProperty("EMAIL")
private String email;

How to move from login page to list page?

I am doing a project on project managment, so I have to show the project details of user once logged in. I'm taking down all the project details in a list so that after login validation, I can get to the project details. But don't know how to call that and plz can someone help me figure out how to store the ID in
//controller
public static Result login() {
User user = Form.form(User.class).bindFromRequest().get();
CommonService service = new CommonServiceImpl();
boolean response=service.login(user);
if(response){
return ok(welcome.render());
}
else{
return ok("not sucees");
}
}
how to call another method to show project details
//daoimpl
public boolean login(User user)
{
try {
con = JdbcUtil.getSqlConnection();
VERIFY_USER=select * from project_managment.t_user where email=? and password=?;
ps = con.prepareStatement(VERIFY_USER);
ps.setString(1, user.getEmail());
ps.setString(2, user.getPassword());
rs = ps.executeQuery();
if(rs.next()){
response=true;
}
}
catch (Exception e) {
}
finally {
JdbcUtil.dbResourceCleanUp(rs,ps,con);
}
return response;
}
how to call another method to show project details
//user is my model class
public class User {
int id;
String firstname;
String lastname;
String password;
String email;
int phone;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
//projectdetails modelclass
public class ProjectDetails {
String ProjectName;
String StartDate;
String endDate;
int hours;
String mngrName;
public String getProjectName() {
return ProjectName;
}
public void setProjectName(String projectName) {
ProjectName = projectName;
}
public String getStartDate() {
return StartDate;
}
public void setStartDate(String startDate) {
StartDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public String getMngrName() {
return mngrName;
}
public void setMngrName(String mngrName) {
this.mngrName = mngrName;
}
}
To get your answer have a look at ACTIVITY and ACTIVITY LIFECYCLE.
Once you are done with login task, you can finish that activity and start new activity having list.

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

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.

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