select box using jstl spring 4 MVC, mongodb - java

I am trying to make a select box using jstl throgh model view and i am a pure noob, someone i have gone through this and created this can anyone help me to get the monngodb values in select box
here are my codes
Controller
#RequestMapping(value = "getSpeciality", method = RequestMethod.GET)
public ModelAndView getSpeciality(HttpServletRequest request) {
Map<String, Object> myModel = new HashMap<String, Object>();
myModel.put("myVar", getSpeciality( UtilsManagementService.getSpeciality() )); // here is showing error UtilsManagementService cannot be resolved
return new ModelAndView("view", myModel);
}
Management layer
package com.geniedoc.management.service;
import java.util.List;
import com.geniedoc.exception.BussniessException;
import com.geniedoc.exception.UserNotFoundException;
import com.geniedoc.vo.CityVo;
import com.geniedoc.vo.SpecialityVO;
public interface UtilsManagementService {
public List<SpecialityVO> getSpeciality(String key) throws BussniessException; }
DB
#Override
public Speciality getSpeciality(String specialityName) {
Query findSpecialityQuery = new Query();
findSpecialityQuery.addCriteria(Criteria.where(SPECIALITY_NAME).regex(specialityName));
Speciality speciality = null;
try{
speciality = this.specialityRepository.getDocument(Speciality.class, findSpecialityQuery, SPECIALITY_TABLE);
}catch(MongoDBDocumentNotFoundException e){
e.printStackTrace();
}
return speciality;
}
and jsp
<select id="Speciality" name=""Speciality"">
<c:forEach var="item" items="${myModel}">
<option value="${item.key}">${item.value}</option>
</c:forEach>
</select>
Speciality Vo
package com.geniedoc.vo;
public class SpecialityVO {
private int _id;
private String speciality_name;
private String speciality_description;
public String getSpeciality_name() {
return speciality_name;
}
public void setSpeciality_name(String speciality_name) {
this.speciality_name = speciality_name;
}
public String getSpeciality_description() {
return speciality_description;
}
public void setSpeciality_description(String speciality_description) {
this.speciality_description = speciality_description;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
}

You need to inject UtilsManagementService (which would have an Implementation) to your Controller. Define the bean and autowire it.
Then use the model which is return by the service.
I do not find any issues with your jstl code.

Related

Spring Boot error: Error creating bean with name 'albumController': Unsatisfied dependency expressed through field 'albumService'

I am new to Spring boot. I am trying to create the below service. Parent class is Artists. Child is Album. I am trying to fetch all the Albums corresponding to particular Artists. While creating custom method in crudRepository I am getting error. Can't able to identify the exact issue, help for the error will be greatly appreciated.
Artists.java (Bean class of Parent)
package com.org.Music_App.Artists;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
import com.org.Music_App.Albums.Album;
#Entity
public class Artists {
#Id
private int artists_Id;
private String artists_Name;
private int no_of_Albums;
private String debut_Album;
#OneToMany
#JoinColumn(name = "artists_id")
#Transient
private List<Album> album;
public Artists() {
}
public Artists(int artists_Id, String artists_Name, int no_of_Albums, String debut_Album) {
this.artists_Id = artists_Id;
this.artists_Name = artists_Name;
this.no_of_Albums = no_of_Albums;
this.debut_Album = debut_Album;
}
public int getArtists_Id() {
return artists_Id;
}
public void setArtists_Id(int artists_Id) {
this.artists_Id = artists_Id;
}
public String getArtists_Name() {
return artists_Name;
}
public void setArtists_Name(String artists_Name) {
this.artists_Name = artists_Name;
}
public int getNo_of_Albums() {
return no_of_Albums;
}
public void setNo_of_Albums(int no_of_Albums) {
this.no_of_Albums = no_of_Albums;
}
public String getDebut_Album() {
return debut_Album;
}
public void setDebut_Album(String debut_Album) {
this.debut_Album = debut_Album;
}
public List<Album> getAlbum() {
return album;
}
public void setAlbum(List<Album> album) {
this.album = album;
}
}
Album.java (Bean class of Child)
package com.org.Music_App.Albums;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import com.org.Music_App.Artists.Artists;
#Entity
public class Album {
#Id
private int album_Id;
private int artists_Id;
private String album_Name;
private int no_of_Songs;
private String artists_Name;
public Album()
{
}
public Album(int album_Id, int artists_Id, String album_Name, int no_of_Songs, String artists_Name) {
super();
this.album_Id = album_Id;
this.artists_Id = artists_Id;
this.album_Name = album_Name;
this.no_of_Songs = no_of_Songs;
this.artists_Name = artists_Name;
}
public int getAlbum_Id() {
return album_Id;
}
public void setAlbum_Id(int album_Id) {
this.album_Id = album_Id;
}
public int getArtists_Id() {
return artists_Id;
}
public void setArtists_Id(int artists_Id) {
this.artists_Id = artists_Id;
}
public String getAlbum_Name() {
return album_Name;
}
public void setAlbum_Name(String album_Name) {
this.album_Name = album_Name;
}
public int getNo_of_Songs() {
return no_of_Songs;
}
public void setNo_of_Songs(int no_of_Songs) {
this.no_of_Songs = no_of_Songs;
}
public String getArtists_Name() {
return artists_Name;
}
public void setArtists_Name(String artists_Name) {
this.artists_Name = artists_Name;
}
}
Custom method:
package com.org.Music_App.Repository;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import com.org.Music_App.Albums.Album;
import com.org.Music_App.Artists.Artists;
public interface AlbumRepository extends CrudRepository<Album, Integer> {
public List<Album> findByArtists_Id(Integer artists_id) ;
}
Error:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property artists found for type Album!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'albumRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property artists found for type Album!
Can you retry the same code removing all underscores?
Java naming convention use camelcase and Spring assumes conventions in order to wire things properly.
if you have
#Id
private int albumId;
you have:
public int getAlbumId;
public void setAlbumId(int albumId);
etc.
PS: you don't need to define the artistsId property in the Album entity only because there will be an "artistis_id" column in the "album" table.
The AlbumRepository's findByArtists_Id method thinks that it needs to look up data based on artists instead of artist_Id, because it seems to be considering the String after "By" upto the underscore.
Try removing underscore and it may solve your issue.
It seems underscores doesn't work with the entity field names. Here is a similar question, where you can find a detailed answer: Spring-Data-Jpa Repository - Underscore on Entity Column Name
Hope that helps!
You have to define your repository here propertly, add #Repository here
#Repository
public interface AlbumRepository extends CrudRepository<Album, Integer> {
public List<Album> findByArtists_Id(Integer artists_id) ;
}
then it will start working

Retrieve value from database in drop-down(<s:select>) using Struts 2 and Hibernate

I want to use dropdown and getting the value in drop down from database, dropdown should contain company code for saving purpose & company description for display purpose.
Below is my code:
Bean Class:
package com.ims.master.company.bean;
public class CompanyBean {
private String id;
private String cmpCode;
private String cmpDes;
private String cmpStatus;
private String cmpCreated;
public CompanyBean(String cmpCode, String cmpDes) {
super();
this.cmpCode = cmpCode;
this.cmpDes = cmpDes;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCmpCreated() {
return cmpCreated;
}
public void setCmpCreated(String cmpCreated) {
this.cmpCreated = cmpCreated;
}
public String getCmpCode() {
return cmpCode;
}
public void setCmpCode(String cmpCode) {
this.cmpCode = cmpCode;
}
public String getCmpDes() {
return cmpDes;
}
public void setCmpDes(String cmpDes) {
this.cmpDes = cmpDes;
}
public String getCmpStatus() {
return cmpStatus;
}
public void setCmpStatus(String cmpStatus) {
this.cmpStatus = cmpStatus;
}
}
DAO class:
package com.ims.master.company.DAO;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.ims.hibernate.HibernateUtil;
import com.ims.master.company.bean.CompanyBean;
public class CompanyDAO {
SessionFactory factory = HibernateUtil.getFactory();
Session session = factory.openSession();
ArrayList<CompanyBean> recList = new ArrayList<CompanyBean>();
#SuppressWarnings("unchecked")
public ArrayList<CompanyBean> retrieveCmpCode()
{
System.out.println("=====inside DAO======");
Query query = session.createQuery("select b.cmpCode,b.cmpDes from CompanyBean b where b.cmpStatus=:val");
query.setParameter("val", "Y");
recList = (ArrayList<CompanyBean>) query.list();
System.out.println("=====value====="+recList);
return recList;
}
}
Action Class:
package com.ims.master.masterData;
import java.util.ArrayList;
import com.ims.master.company.DAO.CompanyDAO;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
public class MasterLookUp extends ActionSupport {
ArrayList companyCode;
public String getCompany()
{
CompanyDAO companyCodeValue = new CompanyDAO();
companyCode = companyCodeValue.retrieveCmpCode();
return SUCCESS;
}
public ArrayList getCompanyCode() {
return companyCode;
}
public void setCompanyCode(ArrayList companyCode) {
this.companyCode = companyCode;
}
}
jsp:
<s:select name="companyName" list="companyCode" key="label.companyName" listKey="cmpCode" listValue="cmpDes"/>
Please suggest me how the value will come in drop down.
Also suggest that how the value in drop down will be displayed selected in edit part.
You can't cast returned value to ArrayList<CompanyBean>, because Hibernate in your case converts the data returned by the query to List<Object[]>. To return List<CompanyBean> you can use another query.
You need to open the Hibernate session to execute the query, and when you have done with it you should close the session. You don't have to close a session only if it's managed by other tool. You can find a detailed explanation how to use Hibernate session in How to display a list of database records (retrieved via Hibernate) to a JSP page in Struts 2, and linked answer.
The query could return List<CompanyBean> if you change the query and property type, so you can assign a value without casting.
public class CompanyDAO {
public List<CompanyBean> retrieveCmpCode() throws Exception
{
System.out.println("=====inside DAO======");
SessionFactory factory = HibernateUtil.getFactory();
Session session = factory.openSession();
List<CompanyBean> recList;
try {
Query query = session.createQuery("from CompanyBean b where b.cmpStatus=:val");
query.setParameter("val", "Y");
recList = query.list();
System.out.println("=====value====="+recList);
return recList;
} finally {
session.close();
}
}
}
Note: #SuppressWarnings("unchecked") no longer needed.
In the JSP you should bind the select tag to the action property that returns a List<CompanyBean>, similar like you have done already.
<s:select name="companyName" list="companyCode" key="label.companyName" listKey="cmpCode" listValue="cmpDes"/>
The action
public class MasterLookUp extends ActionSupport {
private List<CompanyBean> companyCode;
public List<CompanyBean> getCompanyCode() {
return companyCode;
}
public void setCompanyCode(List<CompanyBean> companyCode) {
this.companyCode = companyCode;
}
private String cmpCode;
public String getCmpCode() {
return cmpCode;
}
public void setCmpCode(String companyCode) {
this.cmpCode = cmpCode;
}
public String getCompany() throws Exception
{
CompanyDAO companyCodeValue = new CompanyDAO();
companyCode = companyCodeValue.retrieveCmpCode();
return SUCCESS;
}
}
Note: to get/set default/selected value of the select tag you should provide cmpCode property.
you can use below code in your JSP
<html:select property ="cmpDes">
<html:optionsCollection name ="cmpDes" />
</html:select>
When above code is added in ur JSP , your dropdown will have the cmp description which is fetched from DB.
And below is site which has perfect example to learn struts-1 and is also related to your question for getting some ideas to go on.
http://www.javabeat.net/struts-html-optionscollection-tag-htmloptionscollection/

form creation in spring mvc issue

I've two classes
public class User {
private int id;
priavte List<Hobby> hobbies;
//setter getter
}
public class Hobby {
private int id;
private String hobbyName;
//setter getter
}
now i want to create form for User.java
my form.jsp is
<form:form method="POST" action="saveEmployee.html" commandName="user" name="register-form" id="register-form" cssClass="smart-green">
<form:select path="hobbies" multiple="true" size="3">
<form:option value="1">Cricket</form:option>
<form:option value="2">Computer Games</form:option>
<form:option value="3">Tennis</form:option>
<form:option value="4">Music</form:option>
</form:select>
</form:form>
myController.java
#RequestMapping(value = "/saveEmployee.html", method = RequestMethod.POST)
public ModelAndView addEmployee(
#ModelAttribute("user") User user BindingResult result) {
System.out.println(user.getChoice()); // giving null
// usrDao.saveUser(user);
return new ModelAndView("redirect:add.html", model);
}
How could i get the value for List from my form so that i could get the value?
The Solution to Bind your multi select value to the POJO Object list is done under CustomCollectionEditor class. This is important when binding complex data types such as in your case.
Add this below code in your controller class myController.java :
#InitBinder
protected void initBinder(WebDataBinder binder)
{
binder.registerCustomEditor(List.class, "hobbies", new CustomCollectionEditor(List.class)
{
#Override
protected Object convertElement(Object element)
{
Long id = null;
String name = null;
if(element instanceof String && !((String)element).equals(""))
{
//From the JSP 'element' will be a String
try{
id = Long.parseLong((String) element);
}
catch (NumberFormatException e) {
e.printStackTrace();
}
}
else if(element instanceof Long)
{
//From the database 'element' will be a Long
id = (Long) element;
}
// Here you can get Hobby object from database based on the id you have got.
//You any other way you can get hobbyName and set in hobby object and return it
Hobby h = new Hobby();
h.setId(Integer.parseInt(String.valueOf(id)));
h.setHobbyName(name);
return h;
}
});
}
Reference Link for more details :
SpringMVC bind Multi Select with object in Form submit
Multiple Select in Spring 3.0 MVC.

Cant instantiate class when using managed property

I'm learning Java 6 EE and I have a simple web app.
I have UserBean class that uses CurrencyManager class. CurrencyManager is application scoped and is a managed bean. UserBean is managed bean and session scoped.
Here is my UserBean:
#ManagedBean
#SessionScoped
public class UserBean implements Serializable{
private String username;
private ArrayList<Money> ownedMoney;
private CurrencyManager currencyManager;
private BigDecimal credits;
public UserBean() {
currencyManager = new CurrencyManager();
username = "User";
ownedMoney = new ArrayList<>();
ownedMoney.add(new Money(new BigDecimal(15000), currencyManager.getCurrency("CZK")));
ownedMoney.add(new Money(new BigDecimal(100), currencyManager.getCurrency("USD")));
credits = new BigDecimal(150);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public BigDecimal getCredits() {
return credits;
}
public void setCredits(BigDecimal credits) {
this.credits = credits;
}
public ArrayList<Money> getOwnedMoney() {
return ownedMoney;
}
public void setOwnedMoney(ArrayList<Money> ownedMoney) {
this.ownedMoney = ownedMoney;
}
public CurrencyManager getCurrencyManager() {
return currencyManager;
}
public void setCurrencyManager(CurrencyManager currencyManager) {
this.currencyManager = currencyManager;
}
}
And here my CurrencyManager:
#ManagedBean(name = "currencyManager")
#ApplicationScoped
public class CurrencyManager {
private HashMap<String, Currency> currencies;
public CurrencyManager() {
this.currencies = new HashMap<>();
currencies.put("CZK", new Currency("CZK", new BigDecimal("0.0503")));
currencies.put("GBP", new Currency("GBP", new BigDecimal("0.59")));
currencies.put("EUR", new Currency("EUR", new BigDecimal("1.38")));
currencies.put("USD", new Currency("USD", new BigDecimal("1.0")));
}
public Currency getCurrency(String name){
return currencies.get(name);
}
public java.util.Collection<Currency> getCurrencies() {
return currencies.values();
}
public void setCurrencies(HashMap<String, Currency> currencies) {
this.currencies = currencies;
}
}
The code I posted works fine as is. However I don't want to instantiate CurrencyManager in my UserBean class - that's is why I made it ApplicationScoped, since it should be available at all times.
If I remove the instantiation (first line in UserBean constructor) and change declaration to:
#ManagedProperty(value = "#{currencyManager}")
private CurrencyManager currencyManager;
then the first page that queries ownedMoney property in UserBean throws javax.servlet.ServletException: Cant instantiate class: model.UserBean. with root cause of NullPointerException. GlassFish log showed that the NullPtr occurs in UserBean constructor, when I call getCurrency on currencyManager, here:
ownedMoney.add(new Money(new BigDecimal(15000), currencyManager.getCurrency("CZK")));
Can you tell me what I'm doing wrong?
I just came across the same problem, and found out by chance, that it is not working, if I try with firefox (actually icedove under linux), but well working, if I try with the eclipse build-in browser.
Even so this does not make sense to me, have you tried with different browsers already?

Hibernate automatic versioning not working (with Spring)

I am trying to use the automatic versioning of Hibernate but when the update method f of the Session is called I do not see the version field in the where clause of the query nor is the version incremented in the database. I am doing something fundamentally wrong probably, but what? Is calling getCurrentSession of sesssionFactory an issue?
I have the following entity class:
package dslibweb.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;
#Entity
#Table(name = "dsXCT_Recalls")
public class DsXCT_Recalls {
#Id
public String recallId;
public int version;
public String status;
//...... more properties.....
#Version
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getRecallId() {
return recallId;
}
public void setRecallId(String recallId) {
this.recallId = recallId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
My controller:
package recalls.controller;
#Controller
public class RecallsDataController {
#Autowired
RecallsService recallsManager;
#Autowired
AuthenticationService authService;
private static final Logger logger = Logger.getLogger(RecallsDataController.class);
private static final String SAVE_RECALLS = "MODIFY XCT RECALLS";
RecallsGrid recalls;
#RequestMapping(value = "/showRecallsGrid")
#ResponseBody
public RecallsGrid showRecallsGrid( HttpSession session, HttpServletResponse response) {
recalls = recallsManager.getRecallsDataGrid((String) session.getAttribute("socketToken"), new GridFilters(0, 0, "", "", "", "", ""));
if (recalls.getError() == null || recalls.getError().equals("")) { // no error
return recalls;
} else {
try {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, recalls.getError());
} catch (IOException e) {
e.printStackTrace();
}
return recalls;
}
}
#RequestMapping(value = "/saveRecalls" , method= RequestMethod.POST)
#ResponseBody
public String saveRecalls( HttpSession session, #RequestParam(value="ids[]", required = false) String [] ids, #RequestParam(value="statuses[]", required = false) String [] statuses){
boolean result = authService.validateUserAction((String) session.getAttribute("socketToken"), SAVE_RECALLS);
if(result)
return recallsManager.saveRecalls(ids, statuses, recalls);
else
return "You do not have authority to perform this action.";
}
}
Where I retrieve a collection of DsXCT_Recalls and show them to the user. The collection is stored in the controller. The user then changes status in one or more entities and I call the saveRecalls method of the recallManager which creates a list of only the changed entities (comparing with the collection stored in the controller).
The recallsManager (service layer) is:
package recalls.service.defaultimpl;
#Service("recallManager")
public class HibernateRecallsDataService implements RecallsService {
#Autowired
JsonRpcRequest jsonReq;
#Autowired
JsonRpcSocketWriterReader socketWriterReader;
#Autowired
JsonRpcRequestConstructor reqConstructor;
#Autowired
RecallsDao hibernateRecallsDao;
private static final Logger logger = Logger.getLogger(HibernateRecallsDataService.class);
#Transactional
public RecallsGrid getRecallsDataGrid(String socketToken, GridFilters filters) {
List<DsXCT_Recalls> recalls = hibernateRecallsDao.findRangeOfRecordsFiltered(filters);
return new RecallsGrid(recalls);
}
#Transactional()
public String saveRecalls(String[] ids, String[] statuses, RecallsGrid recalls) {
List<DsXCT_Recalls> recallList = recalls.getRecalls();
List<DsXCT_Recalls> updatedRecallList = new ArrayList<DsXCT_Recalls>();
for (int i = 0; i < ids.length; i++) {
for (DsXCT_Recalls recall : recallList) {
if (recall.recallId.equals(ids[i])) { // recall is found in the list
if (!statuses[i].equals(recall.getStatus())) { // status has changed
recall.setStatus(statuses[i]);
updatedRecallList.add(recall);
}
}
}
}
return hibernateRecallsDao.saveAll(updatedRecallList);
}
}
The saveAll method of my DAO calls one update method of hibernate session by entity changed:
package recalls.dao.hibernate;
#Repository
public class HibernateRecallsDao implements RecallsDao {
#Autowired(required = true)
#Resource(name = "mySessionFactory")
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public List<DsXCT_Recalls> findRangeOfRecordsFiltered(GridFilters filters) {
return sessionFactory.getCurrentSession().createQuery("from DsXCT_Recalls r WHERE SID = 0 ORDER BY Org, Bank, BIC, SetlDate").list();
}
public String saveAll(List<DsXCT_Recalls> recallList){
int count = 0;
for(DsXCT_Recalls recall:recallList){
sessionFactory.getCurrentSession().update(recall);
count++;
}
return count + " recalls were modified.";
}
}
So apparently the #Version must be above the attribute declaration and not above the getter method.. I am sure I saw this somewhere though. So much time wasted :(

Categories