Controller:
#RequestMapping(value="/balance.html",method=RequestMethod.GET)
public ModelAndView balance_navigation(#ModelAttribute("command") NetBean netBean,BindingResult result){
System.out.println("controller balance");
//int bal= netservice.displaybalance(cid);
Map<String, Object> model = new HashMap<String, Object>();
System.out.println("controller Map object balance");
model.put("balance", netservice.displaybalance(cid));
System.out.println("controller put() balance");
return new ModelAndView("balance", model);
Dao:
`#Override
public int displaybalance(int cid) {
Session session=sessionFactory.openSession();
System.out.println("query before executed in balance");
Query query=session.createQuery("select accbal from Account as se where se.cid=cid");
////select ACCBAL from Account a join Customer s on a.cid=s.cid where s.cid=cid
System.out.println("query executed in balance");
query.setParameter(0,cid);
return (int) query.list().get(0);`
**org.springframework.web.bind.annotation.support.HandlerMethodInvocationException: Failed to invoke handler method [public org.springframework.web.servlet.ModelAndView com.controller.Netcontroller.balance_navigation(com.bean.NetBean,org.springframework.validation.BindingResult)]; nested exception is java.lang.IllegalStateException: No data type for node: org.hibernate.hql.ast.tree.IdentNode
**
replace your #ModelAttribute("command") to #ModelAttribute("netBean")
same thing jsp also ModelAttribute="netBean"
Related
I'm trying to test the creation of an entity with incomplete data as follows:
#Test
public void postVisitor_withIncompleteData_shouldFailWithBadRequest() throws Exception {
Visitor emptyVisitor = new Visitor();
mockMvc.perform(post("/visits")
.contentType(APPLICATION_JSON)
.content(objectMapper.writeValueAsString(visitor))
).andExpect(status().isBadRequest());
}
But my test fails with this error:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.ConstraintViolationException: Validation failed for classes [com.reweb.Visitor] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='cannot be empty', propertyPath=email, rootBeanClass=class com.reweb.Visitor, messageTemplate='{javax.validation.constraints.NotEmpty.message}'}
]
How can I test this is a bad request?
Adding #Test(expected = ConstraintViolationException.class) wouldn't work either.
If you have already configured #Valid with #ResponseBody in controller , then you need to create ExceptionHandlerInterceptor just like below:
#RestControllerAdvice
#Slf4j
public class ApplicationExceptionInterceptor extends ExceptionHandlerExceptionResolver {
#ExceptionHandler(Throwable.class)
public
ResponseEntity<Response<?>>
handleControllerException(final HttpServletRequest request, final Throwable ex) {
if (ex instanceof MethodArgumentNotValidException) {
log.error(ex.getMessage());
final MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
final List<ObjectError> errors = exception.getBindingResult().getAllErrors();
final List<FaultDetail> faultDetailsList = new ArrayList<>();
final List<String> error = new ArrayList<>();
errors.forEach(action -> error.add(action.getDefaultMessage()));
faultDetailsList.add(new FaultDetail(error));
}
return ResponseEntity.body(faultList).status(HttpStatus.BAD_REQUEST).build();
}
You also need to provide to provide this ExceptionHandler to MockMvc just like below ,I am providing for RestAssuredMockMvc there should be similiar configuation for MockMvc as well:
#BeforeMethod
public void initializeMockMvcWithControllerAdvice(Object controller, Object controllerAdvice, ContentType contentType) {
RestAssuredMockMvc.reset();
RestAssuredMockMvc.mockMvc(MockMvcBuilders.standaloneSetup(new Object[]{controller}).setControllerAdvice(new Object[]{controllerAdvice}).build());
RestAssuredMockMvc.requestSpecification = (new MockMvcRequestSpecBuilder()).setContentType(contentType).build();
}
In the following code I want to return a list of users from their training using ResponseEntity :
public Utilisateur initUserByFormation(Integer idFrormation) {
Utilisateur user = new Utilisaateur() ;
user = userService.getuserByIdFormation(idFrormation) ;
return user;
}
and the controller call this method :
#RequestMapping(value = "/test/{idFrormation}", method=RequestMethod.GET)
public ResponseEntity <List<Utilisateur>> test(#PathVariable("idFrormation") Integer idFrormation) {
List<Utilisateur> utilisateurs = (List<Utilisateur>) userService.initUserByFormation(idFrormation);
return new ResponseEntity <List<Utilisateur>> (utilisateurs, HttpStatus.ACCEPTED);
}
However, I get the following error:
500 Internal Server Error ERROR Unique id: 1736346060 Request processing failed; nested exception is java.lang.ClassCastException: org.c3.unedicbase.domain.Demandeur cannot be cast to java.util.List
Can you help me to find the origin of this error?
Thank you in advance.
While implementing a global exception handler in Spring, I noticed that in case of a not recognized Accept header, Spring would throw it's own internal error. What I need is to return a custom JSON error structure instead. Works fine for application specific exceptions and totally fails for Spring HttpMediaTypeNotAcceptableException.
This code tells me "Failed to invoke #ExceptionHandler method: public java.util.Map RestExceptionHandler.springMalformedAcceptHeaderException()" when I try to request a page with incorrect Accept header. Any other way to return custom JSON for spring internal exceptions?
#ControllerAdvice
public class RestExceptionHandler {
#ExceptionHandler(value = HttpMediaTypeNotAcceptableException.class)
#ResponseBody
public Map<String, String> springMalformedAcceptHeaderException() {
Map<String, String> test = new HashMap<String, String>();
test.put("test", "test");
return test;
}
}
Eventually figured that the only way is to do the json mapping manually.
#ExceptionHandler(value = HttpMediaTypeNotAcceptableException.class)
#ResponseBody
public String springMalformedAcceptHeaderException(HttpServletResponse response) {
// populate errorObj, set response headers, etc
ObjectWriter jsonWriter = new ObjectMapper().writer();
try {
return jsonWriter.writeValueAsString(errorObj);
} catch(Exception e){}
return "Whatever";
}
this example is useful when I want to validate the existence of an object.
#ResponseStatus(value=HttpStatus.NOT_FOUND)
public class CustomGenericException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String errCode;
private String errMsg;
#Controller
public class MainController {
#RequestMapping(value = "/units/{id}", method = RequestMethod.GET)
public ModelAndView getPages(Integer id)
throws Exception {
if ( service.getUnidad(id) == null) {
// go handleCustomException
throw new CustomGenericException("E888", "This is custom message");
}
}
#ExceptionHandler(CustomGenericException.class)
public ModelAndView handleCustomException(CustomGenericException ex) {
ModelAndView model = new ModelAndView("error/generic_error");
model.addObject("errCode", ex.getErrCode());
model.addObject("errMsg", ex.getErrMsg());
return model;
}
URL : /units/85
The unit 85 does not exist.
But I want to custime exception when I enter a URL invalid (For example /thisurlnoexists),
and the output should be THIS URL IS INCORRECT.
So I want to know if there is any way to intercept url exepcion customize without having to type throw new EXAMPLEEXCEPTION in the method. The same would like to know if I get an SQL error.
Thanks in advance
UPDATE
For 404 page not found , its work fine. The code is
web.xml
<error-page>
<error-code>404</error-code>
<location>/error</location>
</error-page>
controller
#RequestMapping("error")
public String customError(HttpServletRequest request, HttpServletResponse response, Model model) {
model.addAttribute("errCode", "324");
model.addAttribute("errMsg", "PAGE NOT FOUND");
return "error";
}
But for Database this code not found
#ControllerAdvice
public class GeneralExceptionController {
#ExceptionHandler({SQLException.class,DataAccessException.class})
public String databaseError(ModelMap model, Exception exception) {
model.addAttribute("errCode", "ERROR");
model.addAttribute("errMsg", "SQL");
return "error";
}
#ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception exception) {
ModelAndView mav = new ModelAndView();
mav.addObject("errCode", exception);
mav.addObject("errMsg", req.getRequestURL());
mav.setViewName("error");
return mav;
}
}
Controller
#RequestMapping(value = "/sites", method = RequestMethod.GET)
public String getSites(#RequestParam(required = false) String error, ModelMap modelMap) {
List sites = siteBusiness.getAllSites(); //assume that the database is offline, at this point the exception originates
modelMap.put("sites", sites);
return "sites";
}
Spring controller has different notions for inexistant, and invalid Urls.
Taking your example :
/uuuunits/* : NoSuchRequestHandlingMethodException (at DispatcherServlet level) -> 404
/units/foo : (you asked for an Integer ) : TypeMismatchException -> 400
/units/85 : to be dealt with by controller.
You will find references on Spring Reference Manual/ Web MVC framework / Handling Exceptions
If you're looking for Urls that are invalid, it means those URL don't Exist. Hence, all that you need is a 404-Page not Found handler, and you can easily set up that in spring.
About connection error to database, The same applies to it also.
You can make your application container handle such exceptions.
Uncaught exceptions within an application can be forwarded to an error page as defined in the deployment descriptor (web.xml).
<error-page>
<exception-type>Your-exception-here</exception-type>
<location>/error</location>
</error-page>
You can a common page for all your DB errors using the following code snippet.
I want to insert a record to database so this is my controller :
#RequestMapping(value="/ajouter_activite",method = RequestMethod.POST)
public String AddActivity(#ModelAttribute Movement movement, ModelMap model,BindingResult result){
AddActivityValidator actvalidator = new AddActivityValidator();
actvalidator.validate(movement, result);
if(!result.hasErrors()){
boolean n;
n=actservice.addMovement(movement);
if(n==true){model.addAttribute("success","true");}
else {model.addAttribute("echec","true");}
return "/FicheService";}
else{return "/FicheService";
}
}
When i send my form i get this exception :
Etat HTTP 500 - Request processing failed; nested exception is org.springframework.web.bind.annotation.support.HandlerMethodInvocationException: Failed to invoke handler method [public java.lang.String gestion.delegation.controller.FicheServiceController.AddActivity(gestion.delegation.domaine.Movement,org.springframework.ui.ModelMap,org.springframework.validation.BindingResult)]; nested exception is java.lang.IllegalStateException: Errors/BindingResult argument declared without preceding model attribute. Check your handler method signature!
Where is the wrong with that ?
Try with
public String AddActivity(#ModelAttribute Movement movement, BindingResult result, ModelMap model)
method signature.
see example 17.1 in http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-methods for more info.