Passing String from jsp to Controller in Spring - spring

I created a project with Spring + JPA + Hibernate. I want to pass a string from jsp to controller(removeUtente method). If I click on the link I delete the row from the database .. Where am I doing wrong? Excuse me for my english..The controller receives the string from jsp and calls the method to remove it.
Thanks
<%# 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"%>
<!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>Insert title here</title>
</head>
<body>
<h2>Lista utenti</h2>
<table border="1">
<c:forEach var="utente" items="${lista }">
<tr>
<td>
<c:out value="${utente.id}"/>
</td>
<td>
<c:out value="${utente.cognome}"/>
</td>
<td>
<c:out value="${utente.nome}"/>
</td>
<td>
<c:out value="${utente.eta}"/>
</td>
<td>
<c:url var="url" value="/remove">
<c:param name="id" value="${utente.id }"/>
</c:url>
click to delete
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
UtenteController.java
package controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.RequestParam;
import persistence.UtenteDAO;
import bean.Utente;
#Controller
public class UtenteController {
#Autowired
UtenteDAO utenteDAO;
#RequestMapping(value="/add",method=RequestMethod.POST)
public String addUtente(#ModelAttribute Utente u){
utenteDAO.inserisciUtente(u);
return "index";
}//addUtente
#RequestMapping(value="/show",method=RequestMethod.GET)
public String getUtenti(ModelMap model){
List<Utente> lista=utenteDAO.listaUtenti();
model.addAttribute("lista", lista);
return "showlista";
}//getUtenti
#RequestMapping(value="/remove",method=RequestMethod.GET)
public String removeUtente(#RequestParam String id){
utenteDAO.rimuovi(id);
return "showlista";
}//removeUtente
}//UtenteController
Utente.java
package bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="utente")
public class Utente {
#Id
#GeneratedValue
#Column(name="id")
private Integer id;
#Column(name="cognome")
private String cognome;
#Column(name="nome")
private String nome;
#Column(name="eta")
private Integer eta;
public Integer getId(){return id;}//getId
public void setId(Integer id){this.id=id;}//setId
public String getCognome(){return cognome;}//getCognome
public void setCognome(String cognome){this.cognome=cognome;}//setCognome
public String getNome(){return nome;}//getNome
public void setNome(String nome){this.nome=nome;}//setNome
public Integer getEta(){return eta;}//getEta
public void setEta(Integer eta){this.eta=eta;}//setEta
#Override
public String toString(){
return "id:"+id+" cogn:"+cognome+" nome:"+nome+" eta:"+eta;
}//toString
}//Utente
UtenteDAOImpl.java
package persistence;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
import bean.Utente;
#Transactional
public class UtenteDAOImpl implements UtenteDAO {
#PersistenceContext
EntityManager em;
public void inserisciUtente(Utente u){
em.persist(u);
}//inserisciUtente
#SuppressWarnings("unchecked")
public List<Utente> listaUtenti(){
Query q=em.createQuery("SELECT u FROM Utente u");
List<Utente> ris=q.getResultList();
return ris;
}//listaUtenti
public void rimuovi(String idUtente){
Query q=em.createQuery("DELETE FROM Utente AS u WHERE u.id =:id");
q.setParameter("id", idUtente);
q.executeUpdate();
}//rimuovi
}//inserisciUtente

Related

How to solve the error message: "Whitelabel Error Page" for Spring Boot

I'm new with spring boot and I'm trying to make a project with Spring MVC + Spring Boot2 + JSP + Spring Data + DB Oracle.
When I run the simple application, The first message error I was been:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Apr 17 10:20:05 CEST 2020
There was an unexpected error (type=Not Found, status=404).
No message available
I found a lot of documention about this error and I tested different solutions but nothing was fine for my problem. Below the tests I did:
1) I make sure that my main class was in the root package and I put the other packages int the sub level;
2) I used de #ComponentScan in the main class in this way #ComponentScan({"com.dashboard.demo.controller"});
3) in the application.properties I used this command server.servlet.context-path=/oee
This is my code:
Application.properties
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
server.servlet.context-path=/oee
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url= jdbc:oracle:thin:#serverIP:Port:DB11G
spring.datasource.username= Server name
spring.datasource.password= password
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.show-sql= true
server.port = 8091
Main
package com.dashboard.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class OeeApplication extends SpringBootServletInitializer{
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(OeeApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(OeeApplication.class, args);
}
}
OEEController
package com.dashboard.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.dashboard.demo.entities.OEE;
import com.dashboard.demo.service.OEEService;
#Controller
public class OEEController {
#Autowired
private OEEService oeeService;
#RequestMapping(value = "/oee}", method = RequestMethod.GET)
public String listAll(Model model)
{
List<OEE> oee = oeeService.SelDevice();
model.addAttribute("OEE",oee);
return "oee";
}
}
OEEServiceImpl
package com.dashboard.demo.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dashboard.demo.entities.OEE;
import com.dashboard.demo.repository.OEERepository;
#Service
#Transactional
public class OEEServiceImpl implements OEEService{
#Autowired
private OEERepository oeeRepository;
#Override
public List<OEE> SelDevice()
{
return oeeRepository.findAll();
}
}
OEERepository
package com.dashboard.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.dashboard.demo.entities.OEE;
import com.dashboard.demo.entities.OEEid;
#Repository
public interface OEERepository extends JpaRepository<OEE, OEEid>
{
}
I'm managing a composite key and I've create a class for the composite key and another to manage the entity. I'm catching the error int this package.
package com.dashboard.demo.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import org.springframework.format.annotation.DateTimeFormat;
import lombok.Data;
#Data
#Embeddable
public class OEEid implements Serializable{
/**
*
*/
private static final long serialVersionUID = 4512114330774744082L;
#DateTimeFormat(pattern = "dd-MM-yy HH:mm:ss")
#Column(name = "MSO_GIORNO_LAV")
private Date date;
#Column(name = "MSO_MACCHINA")
private String device;
public OEEid(Date date, String device) {
super();
this.date = date;
this.device = device;
}
}
package com.dashboard.demo.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.IdClass;
import javax.persistence.Table;
import lombok.Data;
#Entity
#Table(name = "MES_OEE")
#Data
public class OEE implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -7738922358421962399L;
#EmbeddedId
private OEEid oeeID;
#Basic(optional = false)
#Column(name = "MSO_QUANTITA")
private int amount;
#Basic(optional = false)
#Column(name = "MSO_OEE")
private float oee;
}
oee.jsp
<!DOCTYPE html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css"
href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />
<c:url value="/css/main.css" var="jstlCss" />
<link href="${jstlCss}" rel="stylesheet" />
</head>
<body>
<div class="container">
<header>
<h1>Spring MVC + JSP + JPA + Spring Boot 2</h1>
</header>
<div class="starter-template">
<h1>Users List</h1>
<table
class="table table-striped table-hover table-condensed table-bordered">
<tr>
<th>Date</th>
<th>Device</th>
<th>Amount</th>
<th>OEE</th>
</tr>
<c:forEach items="${OEE}" var="oee">
<tr>
<td>${oee.oeeID.date}</td>
<td>${oee.oeeID.device}</td>
<td>${oee.amount}</td>
<td>${oee.oee}</td>
</tr>
</c:forEach>
</table>
</div>
</div>
<script type="text/javascript"
src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
Can anyone give me any suggestions to solve this error message?
Thanks
This is my project directory
Can you please try by removing this server.servlet.context-path=/oee from properties file and try with localhost:8080/oeee

Spring boot authentication issue?

As you can see on : http://website-live-245110.appspot.com/ (gccloud hosted site) following the code logic, any username with 4 characters should be able to log in. Although this is not the case at the moment and i have trouble understanding why.
You should try logging in multiple times to grasp the issue.
CustomAuthenticationProvider.java
package com.spring.authprovider;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider{
#Autowired
private ThirdPartyAuthProviderClient thirdPartyAuthProviderClient;
// one a user logs in, the authentication variable is filled with the details of the authentication
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// when the user logs in to the application, our object will be filled by spring
String name = authentication.getName();
Object password = authentication.getCredentials(); //object that encapsulates password that user types
// not printing or storing password anyone
if(thirdPartyAuthProviderClient.shouldAuthenticate(name,password)) {
// the array list is for roles, because we are not using it now, we are sending it an empty one
return new UsernamePasswordAuthenticationToken(name, password, new ArrayList<>());
} else {
System.out.println("authentication failed for user: " + name);
}
return null;
}
#Override
public boolean supports(Class<?> authentication) {
// there are multiple ways of authentication, use use username and password
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
ThirdPartyAuthProviderClient.java
package com.spring.authprovider;
import org.springframework.stereotype.Component;
#Component
public class ThirdPartyAuthProviderClient {
//emulates request to third party application
public boolean shouldAuthenticate(String username, Object password) {
// 3rd party request to see if user is correct or no or should be logged in
// user with username with 4 digits can be logged in to the application
return username.length() == 4;
}
}
WebSecurityConfig.java
package com.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
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;
import com.spring.authprovider.CustomAuthenticationProvider;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private CustomAuthenticationProvider authProvider;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/home", "/time").permitAll() // any request matching /, /home, /time
// can be accessed by anyone
.anyRequest().authenticated() // any other request needs to be authenticated
.and().authorizeRequests().antMatchers("/admin/**") // only admin can access /admin/anything
.hasRole("ADMIN")
.and().formLogin().loginPage("/login") // permit all to form login--- we use loginPage to use custom page
.permitAll()
.and().logout() // permit all to form logout
.permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//specify auth provider
auth.authenticationProvider(authProvider);
}
// configuration of static resources
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/templates/**", "/assets/**");
}
}
MvcConfig.java
package com.spring;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
public class MvcConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}
Templates
hello.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="#{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
</body>
</html>
home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>
<p>Click <a th:href="#{/hello}">here</a> to see a greeting.</p>
</body>
</html>
login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="#{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
I expect it to either log me in when a username with 4 characters is entered, Or output Invalid username and password. Error.
Code is here : https://github.com/jeffpascal/Spring-and-springboot/tree/devs/SpringSecurity

Invalid property 'idUtilisateur' of bean class

I'm getting following error while running my Spring MVC web application:
Invalid property 'idUtilisateur' of bean class [com.model.Utilisateur_$$_jvstba9_0]: Getter for property 'idUtilisateur' threw exception; nested exception is java.lang.reflect.InvocationTargetException
org.springframework.beans.InvalidPropertyException: Invalid property 'idUtilisateur' of bean class [com.model.Utilisateur_$$_jvstba9_0]: Getter for property 'idUtilisateur' threw exception; nested exception is java.lang.reflect.InvocationTargetException
How can I fix it?
Utilisateur.java
package com.model;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="utilisateur")
public class Utilisateur implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="idutilisateur")
private Long idUtilisateur;
#Column(name="emailutilisateur")
private String emailUtilisateur;
#Column(name="motpasseutilisateur")
private String motPasseUtilisateur;
#Column(name="nomutilisateur")
private String nomUtilisateur;
#Column(name="dateinscriptionutilisateur")
private Timestamp dateInscriptionUtilisateur;
public Long getIdUtilisateur() {
return idUtilisateur;
}
public void setIdUtilisateur(Long idUtilisateur) {
this.idUtilisateur = idUtilisateur;
}
public String getEmailUtilisateur() {
return emailUtilisateur;
}
public void setEmailUtilisateur(String emailUtilisateur) {
this.emailUtilisateur = emailUtilisateur;
}
public String getMotPasseUtilisateur() {
return motPasseUtilisateur;
}
public void setMotPasseUtilisateur(String motPasseUtilisateur) {
this.motPasseUtilisateur = motPasseUtilisateur;
}
public String getNomUtilisateur() {
return nomUtilisateur;
}
public void setNomUtilisateur(String nomUtilisateur) {
this.nomUtilisateur = nomUtilisateur;
}
public Timestamp getDateInscriptionUtilisateur() {
return dateInscriptionUtilisateur;
}
public void setDateInscriptionUtilisateur(Timestamp dateInscriptionUtilisateur) {
this.dateInscriptionUtilisateur = dateInscriptionUtilisateur;
}
#Override
public String toString() {
return "Utilisateur [idUtilisateur=" + idUtilisateur + ", emailUtilisateur=" + emailUtilisateur
+ ", motPasseUtilisateur=" + motPasseUtilisateur + ", nomUtilisateur=" + nomUtilisateur
+ ", dateInscriptionUtilisateur=" + dateInscriptionUtilisateur + "]";
}
}
UtilisateurController
package com.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.model.Utilisateur;
import com.service.UtilisateurService;
#Controller
public class UtilisateurController {
#SuppressWarnings("unused")
private final static Logger logger = Logger.getLogger("UtilisateurController");
public UtilisateurController(){
System.out.println("spring_da_user_management_web_app");
}
#Autowired
private UtilisateurService service;
#RequestMapping(value="/newUtilisateur", method=RequestMethod.GET)
public ModelAndView newUtilisateur(ModelAndView model){
Utilisateur utilisateur = new Utilisateur();
model.addObject("utilisateur", utilisateur);
model.setViewName("utilisateurForm");
return model;
}
#RequestMapping(value = "/saveUtilisateur", method = RequestMethod.POST)
public ModelAndView saveUtilisateur(#ModelAttribute Utilisateur utilisateur) {
if (utilisateur.getIdUtilisateur() == 0) {
service.addUtilisateur(utilisateur);
} else {
service.updateUtilisateur(utilisateur);
}
return new ModelAndView("redirect:/");
}
#RequestMapping(value="/", method=RequestMethod.GET)
public ModelAndView listeUtilisateur(ModelAndView model) throws IOException{
List<Utilisateur> listeUtilisateur = service.getAllUtilisateur();
model.addObject("listeUtilisateur", listeUtilisateur);
model.setViewName("listeutilisateur");
return model;
}
#RequestMapping(value = "/editUtilisateur", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
Long idUtilisateur = Long.parseLong(request.getParameter("idUtilisateur"));
Utilisateur utilisateur = service.getUtilisateurById(idUtilisateur);
ModelAndView model = new ModelAndView("utilisateurForm");
model.addObject("utilisateur", utilisateur);
return model;
}
#RequestMapping(value="/deleteUtilisateur", method=RequestMethod.GET)
public ModelAndView deleteUtilisateur(HttpServletRequest request){
service.deleteUtilisateur(Long.parseLong(request.getParameter("idUtilisateur")));
return new ModelAndView("redirect:/");
}
}
UtilisateurDao
package com.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.model.Utilisateur;
#Repository
public class UtilisateurDaoImpl implements UtilisateurDao {
#Autowired
private SessionFactory sessionFactory;
public void addUtilisateur(Utilisateur utilisateur) {
sessionFactory.getCurrentSession().saveOrUpdate(utilisateur);
}
#SuppressWarnings("unchecked")
public List<Utilisateur> getAllUtilisateur() {
List<Utilisateur> listeUtilisateur = sessionFactory.getCurrentSession().createQuery("from Utilisateur").list();
return listeUtilisateur;
}
public Utilisateur getUtilisateurById(Long idUtilisateur) {
return (Utilisateur)sessionFactory.getCurrentSession().load(Utilisateur.class, idUtilisateur);
}
public Utilisateur updateUtilisateur(Utilisateur utilisateur) {
sessionFactory.getCurrentSession().update(utilisateur);
return utilisateur;
}
public void deleteUtilisateur(Long idUtilisateur) {
Utilisateur utilisateur = (Utilisateur)sessionFactory.getCurrentSession().load(Utilisateur.class, idUtilisateur);
if(utilisateur != null){
this.sessionFactory.getCurrentSession().delete(utilisateur);
}
}
}
utilisateurForm.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Edit / Save Utilisateur</title>
</head>
<body>
<div align="center">
<h1> Edit / Save Utilisateur</h1>
<form:form action="saveUtilisateur" method="post" modelAttribute="utilisateur">
<table>
<form:hidden path="idUtilisateur"/>
<tr>
<td>Adresse email</td>
<td><form:input path="emailUtilisateur"/></td>
</tr>
<tr>
<td>Mot de passe</td>
<td><form:password path="motPasseUtilisateur"/></td>
</tr>
<tr>
<td>Nom d'utilisateur</td>
<td><form:input path="nomUtilisateur"/></td>
</tr>
<tr>
<td>Date d'inscription</td>
<td><form:input path="dateInscriptionUtilisateur"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save"/></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>

Spring Boot - unable to resolve JSP page

application.yml
spring:
mvc.view:
prefix: /
suffix: .jsp
SampleController.java
package springboot_demo;
import javax.annotation.Resource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import springboot_demo.service.StudentService;
#Controller
#SpringBootApplication
public class SampleController extends SpringBootServletInitializer{
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SampleController.class);
}
#Resource
private StudentService studentService;
#RequestMapping("/")
public String home(Model model) {
model.addAttribute("data", studentService.list());
return "index";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}
The 'data' is correctly fetched from database, but the JSP page seems not compiled. I visit http://localhost:8080 and the browser shows me like this:
<%#page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<h2>Hello World!</h2>
<c:forEach items="${data }" var="i">
<h2>${i.id }${i.name }</h2>
</c:forEach>
</body>
</html>

Why is not null error message displaying before form submission?

I've created basic form validation in Spring using annotations. For unknown reason it is displaying the NotNull error message I specified in the User class before the form is submitted. Any ideas why?
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="springForm" %>
<%# page session="false" %>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title>Home</title>
</head>
<body>
<springForm:form method="POST" action="#" commandName="user" >
<table>
<tr>
<td>UserName:</td>
<td><springForm:input path="userName" /></td>
<td><springForm:errors path="userName" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="Save Changes" />
</td>
</tr>
</table>
</springForm:form>
</body>
</html>
package com.journaldev.spring;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
public class User {
private int id;
#NotNull #Size(min=2, max=30)
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public User(){
}
}
package com.journaldev.spring;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = {RequestMethod.GET, RequestMethod.POST})
public String home(Model model, #Valid User user,
BindingResult bindingResult) {
return "home";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(Locale locale, Model model) {
return "login";
}
#RequestMapping(value = "/home", method = RequestMethod.POST)
public String login(#Validated User user, Model model) {
model.addAttribute("userName", user.getUserName());
return "user";
}
}
You have same method on "/" for GET and POST with #Valid and BindingResult. Create separate method for GET without parameters you don't need there.

Resources