AdminController.java
#Controller
public class AdminController {
#Autowired
HttpServletRequest request;
#Autowired
AdminDao adminDao;
#RequestMapping("/deletebatch")
public String deletebatch(){
int batchid = Integer.parseInt(request.getParameter("id"));
adminDao.deletebatch(batchid);
return "redirect:/viewbatch";
}
#AdminDaoImpl.java
#Repository("adminDao")
public class AdminDaoImpl implements AdminDao {
#Autowired
SessionFactory sessionFactory;
#Transactional
public void deletebatch(int batchid){
// Batch batch = (Batch) sessionFactory.getCurrentSession().load(Batch.class,batchid);
// if(batch!=null){
sessionFactory.getCurrentSession().delete(batchid);
//}
}
}
#viewbatch.jsp
<form >
<table border="1">
<tr>
<th>BATCH id</th>
<th>BATCH name</th>
<th>edit/delete</th>
</tr>
<c:forEach items="${batchlist}" var="batchlist">
<tr>
<td>${batchlist.batchid}</td>
<td>${batchlist.batchname}</td>
<td>edit/delete</td>
</tr>
</c:forEach>
When i try to delete i got the error :
HTTP Status 500 - Request processing failed; nested exception is
org.hibernate.MappingException: Unknown entity: java.lang.Integer"
and
i try putting the admincontroller as "/delete?id=${batchid}" also.
While i did this i got the problem like can't convert to string
Session.delete(Object); takes the entity you want to delete as parameter, i.e. a Batch object in your example.
In getCurrentSession().delete(batchid); you're passing an Integer - Hibernate tries to delete the Entity Integer from the database but can't find a mapping and therefore throws a MappingException.
The code you commented out in AdminDaoImpl.java is actually what you need to get an entity!
Hibernate Session.delete() an object if exists has examples on how to delete entities in Hibernate. There are also some hints on whether you should use Session.get(Batch.class, batchid) instead of Session.load().
Related
i am trying to get question and it's multiple options. i am getting successfully Question but its options getting null.
<c:forEach begin="0" end="${optionsCount}" varStatus="loop">
<form:input path="options[${loop.index}].mcq"/>
</c:forEach>
public class OnlineTestQuestionBean {
private String optionsCount;
private Long questionId;
private String question;
private Set<QuestionOptionBean> options;
//setter getter
}
public class QuestionOptionBean {
private Long optionId;
private String mcq;
//setter getter
}
following is Controller Code :-
#Controller
public class OnlineTestController {
#RequestMapping(value = "/savequestion", method = RequestMethod.GET)
public String addQuestion(Model model) {
model.addAttribute("OnlineTestQuestionBean", onlineTestQuestionBean);
return "addquestion";
}
#RequestMapping(value = "/savequestion", method = RequestMethod.POST)
public String saveQuestion(#ModelAttribute("OnlineTestQuestionBean")OnlineTestQuestionBean onlineTestQuestionBean, Model model) {
return null;
}
}
Following is Spring Form code :-
<c:forEach begin="0" end="${optionsCount}" varStatus="loop">
<form:input path="options[${loop.index}].mcq"/>
</c:forEach>
When i submit that time i get "Cannot get element with index 0 from Set of size 0, accessed using property path" this Exception,
suppose i used following code i get null set value.
<input type="text" path="options.mcq"/>
Try using the following in the form :
<c:forEach
<c:forEach items="${options}" var="option">
<form:input path="option.mcq"/>
</c:forEach>
First I am getting a list of objects on JSP page, each has an hyperlink(anchor), then on click of anchor I have to send index of the list(surveyId which is also originally coming in surveyList) to controller but the controller is not getting called. It returns 404.
<body>
Create a new survey
<table border="1" cellpadding="5" cellspacing="5">
<tr>
<td><b>Existing Surveys</b></td>
</tr>
<c:forEach var="survey" items="${surveyList}" varStatus="status">
<tr>
<td>${survey.surveyTitle}</td>
<td><a id="byParameter"
href="<c:url value='/home.htm/${surveyList[status.index].surveyId}' />">Share</a>
</td>
</tr>
</c:forEach>
</table>
</body>
URL getting generated is what is need, for example: /project/home.htm/15
This is how the controller looks, I have tried with both #RequestParam and #PathVariable annotations, both return 404. Controller is not getting called.
#Controller
#RequestMapping("/home.htm/parameter/surveyId=1")
public class UserHomeController {
#RequestMapping(value = "/home.htm/{surveyId}", method = RequestMethod.GET)
protected String doSubmit(#PathVariable("surveyId") int surveyId, HttpServletRequest request,
HttpServletResponse response, #ModelAttribute("userSurvey") UserSurvey userSurvey, BindingResult result)
throws AdException {
System.out.println("inside home controller, surveyId:"+surveyId");
return null;
}
}
Could anyone please help me out.
im implementing a java web client which connects to two web services. so basically i have a table listing the status of these two web services. example:
<table>
<tr>
<th>webservice</th>
<th>status</th>
</tr>
<tr>
<td>webservice 1</td>
<td>connected</td>
</tr>
<tr>
<td>webservice 2</td>
<td>connected</td>
</tr>
</table>
my java controller:
class test {
#autowired
private WebServiceTemplate webservice1;
#autowired
private WebServiceTemplate webservice2;
public String mycontroller(...) {
webserviceReq request = new ObjectFactory().createwebserviceReq();
webserviceRes response = new ObjectFactory().createwebserviceRes();
try {
response = (webserviceRes)this.webservice1.marshalSendAndReceive(webserviceReq);
//...set all the data
}
catch(Exception e) {
}
try {
response = (webserviceRes)this.webservice2.marshalSendAndReceive(webserviceReq);
//...set all the data
}
catch(Exception e) {
}
}//end of function
}
if the connection to either webservice fails (mayb the webserivce crash or wat), show the status as disconnected.
currently the problem im facing is if either one connection fail, im getting http status 500, request processing failed.
how can i capture the connection failure for each webservice and print it into the status column?
In each of the catch blocks, extract relevant parts of the Exception in order to determine the specific error. Add them to the returned String.
Things might get easier by not catching Exception, but a subclass that is specifically thrown by your webservices. These might contain the relevant error information.
I'm trying to update a Spring controller to use annotations for a relatively simple 'change password' page. The only fields on the page are 'password' and 'confirm password'. When the form is submitted, it calls to a webservice to do the actual changing of the password. That webservice may return a InvalidPasswordException based upon password rules run within that service. So I want to catch the exception, then add an error message to the view to show up next to the 'password' field. The velocity code is already written using #springShowErrors, so I want to add the error in a way that in can be read in by that tag.
Here is my controller:
#Controller
#RequestMapping("/edit-password.ep")
public class EditPasswordFormControllerImpl {
#Autowired
private CustomerService customerService;
#Autowired
private CustomerSessionService customerSessionService;
#RequestMapping(method = RequestMethod.POST)
protected ModelAndView onSubmit(#ModelAttribute("editPasswordFormBean") EditPasswordFormBeanImpl editPasswordFormBean, BindingResult errors, HttpServletRequest request) throws EpWebException {
String nextView = "redirect:/manage-account.ep";
final CustomerSession customerSession = (CustomerSession) request.getSession().getAttribute(WebConstants.CUSTOMER_SESSION);
final Customer customer = customerSession.getShopper().getCustomer();
try {
CustomerInfo customerInfo = new CustomerInfo();
customerInfo.setCustomerId(customer.getUserId());
customerInfo.setPassword(editPasswordFormBean.getPassword());
UpdateAccountServiceRequest updateRequest = new UpdateAccountServiceRequest();
updateRequest.setClientId(CLIENT_ID);
updateRequest.setCustomerInfo(customerInfo);
//this is the webservice call that could throw InvalidPasswordException
customerService.updateUserAccount(updateRequest);
} catch (InvalidPasswordException e) {
// This is where I'm not sure what to do.
errors.addError(new ObjectError("password", e.getMessage()));
nextView = "edit-password.ep";
} catch (ServiceException e) {
throw new EpWebException("Caught an exception while calling webservice for updating user", e);
}
return new ModelAndView(nextView);
}
#RequestMapping(method = RequestMethod.GET)
protected String setupForm(ModelMap model) {
EditPasswordFormBean editPasswordFormBean = new EditPasswordFormBeanImpl();
model.addAttribute("editPasswordFormBean", editPasswordFormBean);
return "account/edit-password";
}
}
And here is a snippet of my velocity template:
<fieldset>
<legend>#springMessage("editPassword.editPasswordTitle")</legend>
<table border="0" cellspacing="0" cellpadding="3">
<colgroup>
<col width="150">
<col width="*">
</colgroup>
<tr>
<td colspan="2">
<br />
<strong>#springMessage("editPassword.changePassword")</strong>
</td>
</tr>
<tr>
<td align="right">#springMessage("editPassword.password")</td>
<td>
#springFormPasswordInput("editPasswordFormBean.password" "maxlength='100'")
#springShowErrors("<br>" "req")
</td>
</tr>
<tr>
<td align="right">#springMessage("editPassword.confirmPassword")</td>
<td>
#springFormPasswordInput("editPasswordFormBean.confirmPassword" "maxlength='100'")
#springShowErrors("<br>" "req")
</td>
</tr>
</table>
</fieldset>
I'm not quite sure what I should do when I catch the exception. What I currently have doesn't work. It returns to the edit-password page, but no error displays. I've read about HandleExceptionResolver, but even if I use that, I'm still not sure how to get the error to display on the view.
Any help is greatly appreciated!
Jeff, its just a guess, if you see the controller you have the RequestMapping("/edit-password.ep"), so when there is an error scenario your next view is "edit-password.ep", so it will come to this controller and it will be consdiered as a get request to the controller. But in your GET mapping method you are always creating a new EditPasswordBean and sending back to the back. If you run the server in debug mode and keep a break point in setUpForm method you will why the errors have been swallowed. Try to give specific mappings for get and post to avoid such issues. Ideally you should a Validator defined and it should be registered in your initBinder method. Check out this link http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html
Hope it helps.
I'm going to try to explain my problem as completely and shortly as I can...
A web application, made on Spring MVC 2.5 + Hibernate + Java 6 (not using annotation!).
I've got a controller extending SimpleFormController and a jsp page that is its formView and successView.
This controller should help me to insert into db an entity PracticeT that has connected (many to one) a lookup entity PracticeConfT (think about it as a "typology"). I need to choose that "typology" through a drop-down menu. In my webapp I need to be able to save data inserted and when I want, to submit the request for approval.
The page has some text fields and that drop-down menu. The bean called as default "command" is NewPracticeBean that has within a reference to an object PracticeT.
THE PROBLEM IS: I fill the form, I select a typology from the drop-down menu, I submit form and save data on DB but when I come back to the view, every property is there but the drop-down menu it is not: it has all the options allowed but no one selected. Some checks revealed that the entity PracticeConfT is null (but it has been recorded on db correctly and debugging it is still there in the model until the very end of the method onSubmit!!!).
I hope someone can help me. Thank you in advance!
Bye,
Dolfiz
Here some useful code:
(I don't think that hibernate config can be the problem, but if you need it, I can post it too)
newPractice.jsp
<form:form id="newPracticeForm" commandName="command">
<input type="hidden" name="action"/>
<spring:nestedPath path="practiceT">
<table class="table-data-form">
<tr>
<td class="left"><spring:message code="" text="Practice type" /></td>
<td>
<form:select path="practiceConfT" multiple="false">
<form:option value="" label="- seleziona -"/>
<form:options items="${practiceTypeList}" itemValue="idPracticeConf" itemLabel="practiceName"/>
</form:select>
</td>
</tr>
<tr>
<td class="left">
<spring:message code="" text="Opzione divisa" />
<br/><form:errors cssClass="errors" path="opzioneDivisa" />
</td>
<td><form:input path="opzioneDivisa" /></td>
</tr>
<tr>
<td colspan="1">
<input type="submit" name="submit" id="submit" value="Save" class="buttonEMS" style="width:100px;" />
</td>
</tr>
</table>
</spring:nestedPath>
</form:form>
NewPracticeBean.java
public class NewPracticeBean implements Serializable{
private PracticeT practiceT;
private String action;
private boolean typeSelected;
public NewPracticeBean(){
super();
this.practiceT = new PracticeT();
}
// getters & setters...
}
PracticeT.java
public class PracticeT implements java.io.Serializable {
private long idPractice;
private PracticeConfT practiceConfT;
private String opzioneDivisa;
// getters & setters...
}
PracticeConfT.java
public class PracticeConfT implements java.io.Serializable {
public static final String PRACTICE_NAME = "practiceName";
private long idPracticeConf;
private String practiceName;
// getters & setters...
}
NewPracticeController.java
public class NewPracticeController extends SimpleFormController{
protected SmartLogger log = SmartLogger.getLogger(this.getClass());
private PracticeSu practiceSu;
private ConfigurationSu configurationSu;
private HibernateEntityDataBinder practiceConfTBinder;
private HibernateEntityDataBinder practiceTBinder;
public NewPracticeController() {
setCommandClass(NewPracticeBean.class);
setCommandName("command");
}
#Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
log.trace("NewPracticeController -- initBinder");
super.initBinder(request, binder);
binder.registerCustomEditor(PracticeT.class, "practiceT", practiceTBinder);
binder.registerCustomEditor(PracticeConfT.class, "practiceT.practiceConfT", practiceConfTBinder);
}
#Override
protected Map referenceData(HttpServletRequest request) throws Exception {
log.trace("NewPracticeController -- referenceData");
Map model = new HashMap();
RetrieveAllEntitiesReq req = new RetrieveAllEntitiesReq();
req.setEntity(PracticeConfT.class);
req.setOrderProperty(PracticeConfT.PRACTICE_NAME);
RetrieveAllEntitiesResp resp = configurationSu.retrieveAllEntities(req);
List entitiesList = resp.getEntitiesList();
model.put("practiceTypeList", entitiesList);
return model;
}
#Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
NewPracticeBean practiceBean = (NewPracticeBean)command;
Map model = errors.getModel();
CreateNewPracticeReq req = new CreateNewPracticeReq();
req.setPracticeT(practiceBean.getPracticeT());
CreateNewPracticeResp resp = practiceSu.createNewPractice(req);
practiceBean.setPracticeT(resp.getPracticeT());
model.putAll(referenceData(null));
model.put(getCommandName(), practiceBean);
return new ModelAndView(getSuccessView(), model);
}
// setters and getters...
}
After spending some time with OptionsTag, OptionWriter and SelectValueComparator, I would say, then output of "selected" is based on Object.equals.
So if for any reason (Lazyloading...) the Object PracticeT.practiceConfT and the according Objects of model.put("practiceTypeList", entitiesList) are not the SAME (==) then forms:options will not select them as long as the equals method is not correct implemented.
So I guess you need to implement a correct equals method, even if this did not fix this problem, it is always better to have a correct equals method than a wrong or none.
Correct implemented means that it must pay attention to the fact that is used with Hibernate. (for example use if (Hibernate.getClass(this) != Hibernate.getClass(other)) instead of `if (this.getClass() != other.getClass() )