Spring : Returning to index page after submitting the details - spring

I was trying to work on spring boot.
I created and a form and after submitting it , i have to return to index page. But i am getting error:
****Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Oct 18 20:48:04 IST 2022**
There was an unexpected error (type=Internal Server Error, status=500).**
I used the following code:
#PostMapping("/addStudent")
String addStudent(#ModelAttribute("student") Students student, Model model) {
studentsRepository.save(student);
return "index";
}
What is the problem here, what changes do i need to make??

Related

Laravel Livewire TypeError

I'm loading messages from the database. When first loaded, only the messages with the date of today are loaded.
public function mount() {
$this->today = Carbon::now()->format('Y/m/d');
$this->selectedDatum = $this->today;
}
And in the render method:
$logitems = Logmelding::where('datum',$this->selectedDatum)
->orderBy('datum','desc')
->paginate(10);
Works fine.
There is a Datepicker on the page to select other dates (with wire:model:"selectedDatum'). Works fine as long as I select dates that have entries in the database.
When I choose a date that has no entries in the database, of course nothing gets rendered in the foreach loop. However, when after that I choose a date that does have entries in the database, the messages are not loaded.
The console gives the following message:
Uncaught (in promise) TypeError: Illegal invocation

how to display bindingresult errors on JSP page

I have a requirement to display errors on JSP page.
User enters credentials in login screen and it goes to logincontroller once login success user will be redirected to AccountsummaryController it has some backend calls to fetch data and display those data on landing page that is AccountSummary page. There could be possibility that some of the data may not be fetched for various reasons. I want those errors to be passed to the JSP page to show on landing page after successful login. Below is the code snippet of controller method in accountsummary controller. Also I am planning to have some validations in modelattribute i.e. stmtForm. I hope form errors also goes as part of the result.
#RequestMapping(method = { RequestMethod.GET }, value = "stmtSummary")
public ModelAndView getStatementSummary(#ModelAttribute("stmtForm") StatementForm stmtForm, BindingResult result, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response)
throws Exception {
result.addError(new ObjectError("error1","unable to get account number"));
result.addError(new ObjectError("error2","unable to get routing number"));
if(result.hasErrors()){
System.out.println("Total errors are >>>>"+result.getErrorCount()); // *this is getting printed as 2*
}
}
Here is the tag I am using in JSP page.
<form:errors path="*"/>
I am not able to display errors on the UI. I am not able to find the what is wrong here. Please help
Since you havent posted model class or form, it is difficult to understand whether you have error1 or error2 as attribute in your StatementForm Bean. You are trying to show custom business errors with the spring mvc bindingResult. There are two options to do that:
Use custom errorObject and add it in modelMap and check that in jsp.
For using it with BindingResult, use:
result.rejectValue("property", "unable to get account number");
//or
result.reject("unable to get account number");

Neither BindingResult nor plain target object for bean in spring 3

Hi I am facing an issue and looked all over internet but still not able to find out the root cause. I am posting my code snippet please help me out as I am new to spring 3. I am using modelAttribute in form and what I want that in controller all the values from request should be backed in the object so that I can perform validation and other business logic.
I know there is mistake only in my controller.
1) index.jsp
<form:form action="login" method="POST" modelAttribute="login">
<table>
<tr><td>User Id:</td><td><form:input path="userId"/></td></tr>
<tr><td>Password:</td><td><form:password path="userPassword"/></td></tr>
<tr><td></td><td><input type="submit" value="Login"/></td></tr>
</table>
</form:form>
2) Controller
#RequestMapping(value="/login/", method=RequestMethod.POST)
public String login(#ModelAttribute("login") #Valid Login login,BindingResult result)
{
System.out.println("We have entered into controller class");
if(result.hasErrors())
{
System.out.println("Errors:"+result.getFieldError("userReject"));
return "redirect:/login";
}
else
{
return "home";}
}
}
3) JBoss Log
04:35:29,067 ERROR [org.springframework.web.servlet.tags.form.InputTag] (http--0.0.0.0-8090-1) Neither BindingResult nor plain target object for bean name 'login' available as request attribute: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'login' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141) [spring-webmvc-3.0.5.Release.jar:3.0.5.RELEASE]
The problem is not in the method you posted, which handles the login form submission. It's in the method used to display the form. The form needs to populate its fields from a bean named "login", and you didn't place any bean named "login" in the model, i.e. in a request attribute.
Side note: a login form should never use GET. It should use POST. You really don't want the password to appear in the browser address bar. And you don't want it to appear in the browser history, the server and proxy logs, etc.

In Spring 3.2, does RedirectAttributes really pass the attributes themselves? Losing elements

NOTE: Ultimately my goal is simply to change the resulting URL from "/public/academy/register?param=blah" to a customized SEO-ified URL, as shown in the code. If I'm on the wrong path by trying to change from returning a "success view" JSP in the POST mapping to instead using post-redirect-get (which is good practice anyway), I'm open to suggestions.
Below are two methods: the POST request mapping to retrieve a registration form and process it, and the mapping method for the success page. I'm adding a flash attribute to redirect, which holds the form POSTed to the first method.
The form has a property hierarchy of Form -> Schedule -> Course -> Content -> Vendors, where each is its own class object except that Vendors is a SortedSet<Vendor>. When I load the success page, I get a Hibernate exception stating that the Vendors could not be lazily initialized. Why is it so far down the chain that it stops loading, or more basically, why is it losing this property value in the first place? When I set a breakpoint before the return, the RedirectAttributes object has the Vendors populated in the form I passed to it. What gives?
#RequestMapping(value = "/public/academy/register", method = RequestMethod.POST)
public String processSubmit(Site site, Section section, User user,
#ModelAttribute #Valid AcademyRegistrationForm form,
BindingResult result, Model model, RedirectAttributes redirectAttributes) {
validator.validate(form, result);
if (site.isUseStates()
&& StringUtils.isBlank(form.getBooker().getState())) {
result.rejectValue("booker.state",
"gui.page.academy.attendee.state");
}
if (result.hasErrors()) {
LOG.debug("Form has errors: {}", result.getAllErrors());
return "common/academy-registration";
}
// Form is valid when no errors are present. Complete the registration.
AcademyRegistration registration = form.toAcademyRegistration();
academyService.performRegistration(registration, site);
redirectAttributes.addFlashAttribute(form);
String redirectUrl = "redirect:/public/academy/register/"
+ registration.getSchedule().getCourse().getContent().getSeoNavTitle()
+ "-completed";
return redirectUrl;
}
#RequestMapping(value="/public/academy/register/**-completed", method=RequestMethod.GET)
public String displayRegistrationSuccess(#ModelAttribute("academyRegistrationForm") final AcademyRegistrationForm form)
{
SortedSet<Vendor> dummy = form.getSchedule().getCourse().getContent().getVendors();
return "common/academy-registration-success";
}
Here's the exception:
Oct 2, 2013 2:11:31 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet jsp threw exception
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.horn.cms.domain.Content.vendors, could not initialize proxy - no Session
Here's what I assume happens (until you update with the details):
AcademyRegistration registration = form.toAcademyRegistration();
academyService.performRegistration(registration, site);
does some Hibernate queries and retrieves some persisten entities lazily, ie. they haven't been initialized. The loading that did happen probably occurred in some Hibernate Session (do you have a #Transactional somewhere?). The Session is closed and dis-associated from the lazily loaded object.
You then add the form object, which has some nested reference to the lazily loaded entity (it'll be a hibernate proxy), to the RedirectAttributes. This in itself is not a problem because all you're doing is passing a reference.
The request handling completes by sending a 302 response. Your client will then make the new request that is handled by displayRegistrationSuccess() and hits this line
SortedSet<Vendor> dummy = form.getSchedule().getCourse().getContent().getVendors();
Here, the form object is the same as was added in the previous request. One of the objects in this reference chain is your Hibernate proxy that was lazily initialized. Because the object is no longer associated with a Session, Hibernate complains and you get the exception you get.
It's not a good idea to pass around (across request boundaries) objects that depend on persistent state. Instead, you should pass around an ID that you use to retrieve the entity. The alternative is to fully initialize your object inside your academyService method.

Spring mvc controller null return handler

#RequestMapping(method = RequestMethod.GET)
#ResponseBody
public List<Country> getListOfCountries() {
return countryService.listAll();
}
It displays a json view of the object but if the service return null, then I want to display an error message, Any suggestions pls?
First of all, even if this does not directly answer the question, your objects should never ever return null instead of empty collections - you can find the reasoning in Effective Java 2nd Edition, Item 43 / p.201
So, if the situation when no countries were found is normal it must be processed by the client JS code that will check the count and display the respective message.
If something has gone wrong you can throw an exception(as Biju has pointed out +1) - I believe that it's the service who should throw the exception because it knows the reason why it happened, and not to return null anyway.
I'd like to add that in Spring 3.2(in pre Spring 3.2 returning response body is complicated) you can set an #ExceptionHandler that will both return JSON and set the HTTP status code which can be later processed by the client. I think that returning a custom JSON response with some error code is most optimal here.
#RequestMapping("/test")
#ResponseBody
public List<Country> getListOfCountries() {
//assuming that your service throws new NoCountriesFoundException();
//when something goes wrong
return countryService.listAll();
}
#ExceptionHandler(NoCountriesFoundException.class)
ResponseEntity<String> test() {
return new ResponseEntity<String>(
"We are sorry, our server does not know any countries yet.",
HttpStatus.I_AM_A_TEAPOT );
}
Then in the JS code, you can do specific processing depending on the returned status code.
Also, to avoid declaration of the same #ExceptionHandler in different controllers, in Spring 3.2 you can put #ExceptionHandler inside a #ControllerAdvice annotated class.
For details, see http://static.springsource.org/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-exceptionhandlers and http://www.springsource.org/node/3738 for 3.2 specific things
You have a couple of options I think:
If you return a null back, it will be returned as an empty string "", you can probably look for that and handle it.
Return a wrapper type on top of your list, this way if the wrapped list is null something like this will be returned back to the client {"countries":null} which can be more easily handled at the javascript end.
Throw an exception, which will propagate as a 500 status code back to the client, you can then have an error handler on the javascript side to handle this scenario.

Resources