I have NullException on login - spring

I'm trying to make a login, first time on mvc
I have this error on a proyect for university and I'm not able to see the error throw debug, I can't figure out why. When the debugger gets to line :
Empleado empleado = serviceEmpleado.correctLogin(loginFormDni, loginForm.getPassword());
on controller LoginController method checkLogin it just gives me the exception.
type Informe de Excepción
mensaje Request processing failed; nested exception is java.lang.NullPointerException
descripción El servidor encontró un error interno que hizo que no pudiera rellenar este requerimiento.
excepción
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
causa raíz
java.lang.NullPointerException
germanAcosta.electronicaDonPepe.controller.LoginController.checkLogin(LoginController.java:36)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
nota La traza completa de la causa de este error se encuentra en los archivos de diario de Apache Tomcat/8.0.36.
class LoginController
package germanAcosta.electronicaDonPepe.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import germanAcosta.electronicaDonPepe.DTO.Login;
import germanAcosta.electronicaDonPepe.dominio.Empleado;
import germanAcosta.electronicaDonPepe.service.ServicioException;
#Controller
//#SessionAttributes("resultado")
public class LoginController {
public ServiceEmpleado serviceEmpleado;
#RequestMapping("/login")
public String showLogin(Model model,
#ModelAttribute("resultado") String resultado, #ModelAttribute("error") String error) {
Login login = new Login();
model.addAttribute("login", login);
model.addAttribute("resultado", resultado);
model.addAttribute("error", error);
return "login";
}
#RequestMapping(value = "/login/check", method = RequestMethod.POST)
public String checkLogin(#ModelAttribute("login") Login loginForm, Model model, RedirectAttributes ra) {
try {
Integer loginFormDni = loginForm.getDni();
Empleado empleado = serviceEmpleado.correctLogin(loginFormDni, loginForm.getPassword());
model.addAttribute("loginForm", loginForm);
ra.addFlashAttribute("resultado", "El login es correcto bienvenido " + empleado.getNombre() + ".");
return "redirect:/login";
} catch (ServicioException e) {
ra.addFlashAttribute("resultado", e.getMessage());
return "redirect:/login";
} catch (Exception e) {
ra.addFlashAttribute("error", e.getCause()+ "error");
ra.addFlashAttribute("resultado", "El resultado no es el esperado");
return "redirect:/login";
}
}
}
Class ServiceEmpleado
package germanAcosta.electronicaDonPepe.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import germanAcosta.electronicaDonPepe.dominio.Empleado;
import germanAcosta.electronicaDonPepe.repository.IEmpleadoDAO;
import germanAcosta.electronicaDonPepe.service.ServicioException;
#Service
public class ServiceEmpleado {
#Autowired
private IEmpleadoDAO empleadoDAO;
public Empleado correctLogin(Integer dni, String password) throws ServicioException {
Empleado empleado = this.empleadoDAO.getById(dni);
if (empleado == null) {
throw new ServicioException("El usuario no existe");
} else if (empleado.getPassword() != password) {
throw new ServicioException("El password es incorrecto, por favor reintente nuevamente");
} else {
return empleado;
}
}
}
Login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Electronica Don Pepe</title>
</head>
<body>
<h1>login.jsp</h1>
<br>
<sf:form action="${pageContext.request.contextPath}/login/check"
method="post" commandName="login">
<table>
<tr>
<td><sf:label path="dni">Ingrese su dni</sf:label></td>
<td><sf:input path="dni" type="text" /></td>
</tr>
<tr>
<td><sf:label path="password">Ingrese su contraseña</sf:label></td>
<td><sf:input path="password" type="text" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Ingresar"></td>
</tr>
</table>
</sf:form>
<c:out value="${resultado}"></c:out>
<c:out value="${loginForm.password}"></c:out>
</body>
</html>
Thanks in advance

In LoginController class, public ServiceEmpleado serviceEmpleado; is not autowired. It is not injected with any instance, hence it is null.
Use
#Autowired
public ServiceEmpleado serviceEmpleado;

I use #Autowired on my ServiceEmpleado as #Yuva suggested, but I realized that the annotation it's for an interface and not for a class. So I changed the ServiceEmpleado name to ServiceEmpleadoImpl and add an interface implementation to that class called IServiceEmpleado.
Then I add #Transactional to ServiceEmpleadoImpl and configured the bean on my Config.java
That resolved the problem. Thanks

Related

Spring: Error Button Action on Form after add registration (Spring Security)

I do an example with login page - Spring Security.
Shortly:
There's root page ("localhost:8080/") - here's a link on the main page.
Click a link on the main page go to main.html(localhost:8080/main/
If User doesn't authorize he is redirected to login page
When the user authorizes the main page is opened
The main page show messages and filter by tag
I enter a tag in input and push the button Search(Найти), messages are filtered by tag
When I have added authorization filter has stopped work.
This is my source code:
root page - have link on Main page
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Gretting start: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div>Hello, user</div>
<a th:href="#{/main}">Main page</a>
</body>
</html>
Main page
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div>
<form method="post">
<input type="text" name="text" placeholder="Введите сообщение" />
<input type="text" name="tag" placeholder="Тэг">
<button type="submit">Добавить</button>
</form>
</div>
<div>Список сообщений</div>
<form method="post" action="filter">
<input type="text" name="filter">
<button type="submit">Найти</button>
</form>
<div th:each = "message : ${messages}">
<b th:text = "${message.id}"></b>
<span th:text = "${message.text}"></span>
<i th:text = "${message.tag}"></i>
</div>
</body>
</html>
Controller processes all mapping
package com.example.sweater;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.sweater.domain.Message;
import com.example.sweater.repos.MessageRepo;
#Controller
public class GreetingController {
#Autowired
private MessageRepo messageRepo;
#GetMapping("/")
public String greeting(Model model) {
return "greeting";
}
#GetMapping("/main")
public String main(Model model) {
Iterable<Message> messages = messageRepo.findAll();
model.addAttribute("messages", messages);
return "main";
}
#PostMapping("/main")
public String add(#RequestParam String text, #RequestParam String tag, Model model) {
Message message = new Message(text, tag);
messageRepo.save(message);
Iterable<Message> messages = messageRepo.findAll();
model.addAttribute("messages", messages);
return "main";
}
#PostMapping("/filter")
public String filter(#RequestParam String filter, Model model) {
Iterable<Message> messages;
if (filter != null && !filter.isEmpty()) {
messages = messageRepo.findByTag(filter);
} else {
messages = messageRepo.findAll();
}
model.addAttribute("messages", messages);
return "main";
}
}
WebSecurityConfig have one In Memory User. antMathcers("/") permitAll and anyRequest authenticated
package com.example.sweater.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Bean
#Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("u")
.password("p")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
My screenshots
root page
Main page
When I enter filter tag and push Button "Найти"(= Search), I've got an error:
#PostMapping("/filter") doesn't catch the action in the form. I checked in the debugger. I can't catch an error and don't know why does this happen.
I have GitHub repository: https://github.com/aalopatin/sweater
Commit with the comment "Add messages" - filter work
Commit with the comment "Add remote repository and Login" - filter doesn't work and add login
I found solving. In a form on the main page need to add 'th' attribute because I use Thymeleaf so template engine. It's needed for _csrf defending which auto insert token in a form if you use Thymeleaf:
<form method="post" th:action="filter">
<input type="text" name="filter">
<button type="submit">Найти</button>
</form>

Unable to Run the following Spring Boot Application that uses JDBC Template

I have created a simple Spring Boot Application that adds Dog information into the MySql database.
The controller class for this Application is DogController.java
package com.dog.resue.controller;
import com.dog.resue.dao.DodRepository;
import com.dog.resue.service.DogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Date;
#Controller
#RequestMapping(path="/")
public class DogController {
#Autowired
private DodRepository dodRepository;
#Autowired
private DogService dogService;
#RequestMapping(value ="/home",method = {RequestMethod.POST,RequestMethod.GET})
public String adddog(#RequestParam("name") String name,
#RequestParam("rescued") #DateTimeFormat(pattern = "yyyy-MM-dd") Date rescued,
#RequestParam("vaccinated") Boolean vaccinated, Model model)
{
dogService.addADog(name, rescued, vaccinated);
System.out.println("name = " + name + ",rescued = " + rescued + ", vaccinated = " + vaccinated);
return "index";
}
}
and the corresponding Service class is
package com.dog.resue.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import java.util.Date;
#Service
public class DogServiceImpl implements DogService {
#Autowired
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate=new JdbcTemplate(dataSource);
}
#Override
public void addADog(String name, Date rescued, Boolean vaccinated) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update("INSERT INTO dog(name,rescued,vaccinated) VALUES(?,?,?)",name,rescued,vaccinated );
}
}
And the thymeleaf HTML File is
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<!-- META SECTION -->
<title>Dog Rescue</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- END META SECTION -->
<!-- BEGIN STYLE -->
<style>
table, th, td {
border: 1px solid black;
padding: 1px;
}
</style>
<!-- END STYLE -->
</head>
<body>
<h2>Current Dogs In Rescue</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Rescue Date</th>
<th>Vaccinated</th>
</tr>
</thead>
<tbody>
<tr th:each="dogs : ${dogs}">
<td th:text="${dogs.id}">Text ...</td>
<td th:text="${dogs.name}">Text ...</td>
<td th:text="${dogs.rescued}">Text ...</td>
<td th:text="${dogs.vaccinated}">Text...</td>
</tr>
</tbody>
</table>
</div>
<h2>Add A Dog</h2>
<form action="#" th:action="#{/home}" >
<label>Name<input type="text" name="name" id="name"></input></label>
<label>Vaccinated<input type="text" name="vaccinated" id="vaccinated"></input></label>
<label>Rescued<input type="text" name="rescued" id="rescued"></input></label>
<input type="submit" value="Submit"></input>
</form>
</body>
</html>
While running this code i am getting following Error
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Jul 22 21:50:32 IST 2018
There was an unexpected error (type=Bad Request, status=400).
Required String parameter 'name' is not present
url is http://localhost:8080/home
Kindly help me to solve this issues
Your Request parameters are missing in URL( name,rescued,vaccinated)
Your url should be
http://localhost:8080/home?name=ARULSUJU&rescued=2012-12-12&vaccinated=true
because all the parameters are required
Looking at your controller
Why you have rescued as Date Type you can change it as String.
So your controller will be
#RequestMapping(value ="/home",method = {RequestMethod.POST,RequestMethod.GET})
public String adddog(#RequestParam("name") String name,
#RequestParam("rescued") String rescued,
#RequestParam("vaccinated") Boolean vaccinated, Model model)
{
dogService.addADog(name, rescued, vaccinated);
System.out.println("name = " + name + ",rescued = " + rescued + ", vaccinated = " + vaccinated);
return "index";
}
Now try this URL
http://localhost:8080/home?name=test&rescued=2014-12-12&vaccinated=true
in your thymeleaf html file add this xmlns :
xmlns:th="http://www.thymeleaf.org"

Neither BindingResult nor plain target object for bean name 'contact' available as request attribute

I am trying to create a simple project using spring mvc +maven+ jpa hibernate.
My jsp page is :
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<div>
<form:form action="contact.html" method="post" commandName="contact" >
<div>
<label for="firstname">First Name</label>
<form:input path="firstname"/>
<form:errors path="firstname" cssClass="error"/>
</div>
<div>
<label for="lastname">Last Name</label>
<form:input path="lastname"/>
<form:errors path="lastname" cssClass="error"/>
</div>
<div>
<label for="telephone">Telephone</label>
<form:input path="telephone"/>
<form:errors path="telephone" cssClass="error"/>
</div>
<div>
<label for="email">Email</label>
<form:input path="email"/>
<form:errors path="email" cssClass="error"/>
</div>
<div>
<form:button name="submit" value="submit">Add Contact</form:button>
</div>
My contact.html controller :
package com.corasent.contacts.controllers;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.corasent.contacts.form.Contact;
import com.corasent.contacts.service.ContactService;
#Controller
#RequestMapping("contact.html")
public class ContactManagerController {
#Autowired
ContactService cs;
#RequestMapping(method = RequestMethod.GET)
public String contactController()
{
System.out.println("In controller");
ModelMap map=new ModelMap();
Contact contact=new Contact();
map.addAttribute("contact", contact);
return "contacts";
}
#RequestMapping(method=RequestMethod.POST)
public ModelAndView getInfo(#ModelAttribute Contact contact, BindingResult result, HttpServletRequest req)
{
ModelAndView mv=new ModelAndView("contacts");
String name=contact.getFirstname();
System.out.println("name is="+name);
cs.validate(contact, result);
if(result.hasErrors())
{
return mv ;
}
System.out.println("in post method");
return mv;
}
public ContactService getCs() {
return cs;
}
public void setCs(ContactService cs) {
this.cs = cs;
}
}
I know that the commandName in jsp is the bean that has to be passed to the controller. the same bean is initiated in controller but seems to be not working. its giving me the above error. i am also pasting the stackTrace.
ERROR: org.springframework.web.servlet.tags.form.InputTag - Neither BindingResult nor plain target object for bean name 'contact' available as request attribute
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'contact' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:179)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:199)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:165)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:152)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:143)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:127)
at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:421)
at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:103)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
at org.apache.jsp.WEB_002dINF.views.jsp.contacts_jsp._jspx_meth_form_005finput_005f0(contacts_jsp.java:272)
at org.apache.jsp.WEB_002dINF.views.jsp.contacts_jsp._jspService(contacts_jsp.java:100)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1146)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:679)
12 Apr, 2013 12:36:53 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/contacts] threw exception [An exception occurred processing JSP page /WEB-INF/views/jsp/contacts.jsp at line 10
7:
8: <div>
9: <label for="firstname">First Name</label>
10: <form:input path="firstname"/>
11: <form:errors path="firstname" cssClass="error"/>
12: </div>
Thanks in advance
Try with:
#RequestMapping(method = RequestMethod.GET)
public String contactController(Model model)
{
System.out.println("In controller");
// ModelMap map=new ModelMap();
Contact contact=new Contact();
model.addAttribute("contact", contact);
return "contacts";
}
In your code, you're creating a ModelMap, but it's useless because is being destroyed at the end of the method. Passing the model as a parameter, spring will use it later to fill your JSP.
You have an example here.
Try something like this:
#RequestMapping(method = RequestMethod.GET)
public ModelAndView contactController()
{
System.out.println("In controller");
// First attribute is view name, second model name and last model object
return new ModelAndView("contacts","contact", new Contact());
}
Also, in your form i would change attribute commandName by modelAttribute, i think i have read that the first one is a kind of deprecated (don't fully trust me here)

Can't configure <form:input> within <foreach> tag

I am using the Spring form tag library in my JSP. My command object contains a List and i want to make bindings for each object of the list in my JSP. But STS gives me an Exception that tells that:
Bean property 'testList[0]' is not readable or has an invalid getter
method: Does the return type of the getter match the parameter type of
the setter?]
Here is full Exception code:
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/mvc] threw exception [org.springframework.beans.NotReadablePropertyException: Invalid property 'testList[0]' of bean class [java.util.ArrayList]: Bean property 'testList[0]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?] with root cause
org.springframework.beans.NotReadablePropertyException: Invalid property 'testList[0]' of bean class [java.util.ArrayList]: Bean property 'testList[0]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:729)
at org.springframework.beans.BeanWrapperImpl.getNestedBeanWrapper(BeanWrapperImpl.java:576)
at org.springframework.beans.BeanWrapperImpl.getBeanWrapperForPropertyPath(BeanWrapperImpl.java:553)
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:719)
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:147)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:178)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:198)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:164)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:151)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:142)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:126)
at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:421)
at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
at org.apache.jsp.WEB_002dINF.views.test_jsp._jspx_meth_form_005finput_005f0(test_jsp.java:217)
at org.apache.jsp.WEB_002dINF.views.test_jsp._jspx_meth_c_005fforEach_005f0(test_jsp.java:167)
at org.apache.jsp.WEB_002dINF.views.test_jsp._jspx_meth_form_005fform_005f0(test_jsp.java:122)
at org.apache.jsp.WEB_002dINF.views.test_jsp._jspService(test_jsp.java:82)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:262)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1180)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:950)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Here is my .jsp page :
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello!
</h1>
<form:form action="saveStudent" method="POST" modelAttribute = "testList">
<c:forEach items="${testList}" var="test" varStatus="pStatus">
Test Question: <form:input path = "testList[${pStatus.index}].testQuestion" value = "${test.testQuestion}"/>
Option one: <form:input path = "testList[${pStatus.index}].optionOne" value= "${test.optionOne}"/>
Option two: <form:input path = "testList[${pStatus.index}].optionTwo" value= "${test.optionTwo}"/>
Option three: <form:input path = "testList[${pStatus.index}].optionThree" value= "${test.optionThree}"/>
</c:forEach>
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
Here is my method code:
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String redactTest(Model model, HttpServletRequest request) {
List<Test> testList = db.getTests();
model.addAttribute("testList", testList);
return "test";
}
What i'm doing wrong? Any suggestions? Thanks!
OK, i have a solution: first i've added TestWrapper class which contains List with get and set:
public class TestWrapper {
private List<Test> testList = null;
public TestWrapper(List<Test> testList) {
this.testList = testList;
}
public void setTestList(List<Test> testList) {
this.testList = testList;
}
public List<Test> getTestList() {
return testList;
}
}
Then i've changed my method code:
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String redactTest(Model model, HttpServletRequest request) {
List<Test> testList = db.getTests();
TestWrapper testWrapper = new TestWrapper(testList);
model.addAttribute("testWrapper", testWrapper);
return "test";
}
and after i've changed my .jsp:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello!
</h1>
<form:form action="saveStudent" method="POST" modelAttribute = "testWrapper">
<c:forEach items="${testWrapper.testList}" var="test" varStatus="i">
Test Question: <form:input path = "testList[${i.index}].testQuestion" value = "${test.testQuestion}"/>
Option one: <form:input path = "testList[${i.index}].optionOne" value= "${test.optionOne}"/>
Option two: <form:input path = "testList[${i.index}].optionTwo" value= "${test.optionTwo}"/>
Option three: <form:input path = "testList[${i.index}].optionThree" value= "${test.optionThree}"/>
</c:forEach>
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
And now it works! Hope it will help someone :)

Unable load dropdown list when the page was loading in spring mvc

I trying to populate the dropdown list when page was loaded.But it is not loaded in UserPage.jsp from Controller.on submit method and also wrote referencedata method.
Controller:-
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
log.info("onSubmit handleRequest method"
+ request.getParameter("username"));
System.out.println("onSubmit handleRequest method"
+ request.getParameter("username"));
String username = "", password = "";
username = request.getParameter("username");
password = request.getParameter("password");
UserBean ubean = null;
System.out.println("After shownform method called");
HttpSession session = request.getSession(true);
try {
ubean = userservice.chkUsername(username, password);
System.out.println("Information" + ubean.getUsername());
} catch (DataException ex) {
ex.printStackTrace();
// throw ex;
}
session.setAttribute("User", ubean);
EmpPersonalBean personalBean = new EmpPersonalBean();
return new ModelAndView("jsp/UserPage", "EmpPersonalBean", personalBean);
}
protected Map referenceData(HttpServletRequest request) throws Exception {
log.info("UserDBBoardController======================referenceData");
Map referenceData = new HashMap();
List deparementList = new ArrayList();
deparementList = userservice.getDeparmentList();
referenceData.put("deparmentList", deparementList);
return referenceData;
}
UserPage.jsp
<%# page language="java" import="com.aims.bean.*,java.util.HashMap" contentType="text/html;charset=utf-8" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%#taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<html>
<head>
<title>AAI</title>
</head>
<body>
<form:form method="post" modelAttribute="EmpPersonalBean" action="userpage.htm">
<table>
<tr>
<td>Welcome <%=((UserBean)session.getAttribute("User")).getUsername()%></td>
</tr>
<tr>
<td>Department</td>
<td><form:select path="deparment">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${deparmentList}" />
</form:select>
</td>
</tr>
</tr>
</table>
</form:form>
</body>
</html>
public class DepartmentBean {
private String deptcode,deptname;
public String getDeptcode() {
return deptcode;
}
public void setDeptcode(String deptcode) {
this.deptcode = deptcode;
}
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
}
And also attached displaying dropdown list in the userpage.sjp
Please help me.How to resolve the issue.
You also need to specify itemLabel and itemValue attributes in <form:options/> tag.
UPDATE
Replace this line in your jsp page. I think it should resolve your problem.
<form:options items="${deparmentList}" itemLabel="deptname" itemValue="deptcode" />
Hope this helps you. Cheers.
<td>Department</td>
<td><form:select path="deparment">
<form:option value="NONE" label="--- Select ---" />
<c:forEach var="department" items="${deparmentList}">
<form:option value="${department}" label="${department}" />
</c:forEach>
</form:select>
</td>
ModelAndView mav = new ModelAndView("viewName");
mav.addObject("deparmentList", deparementList);
return mav;
return modelAndView object.

Resources