Spring boot authentication issue? - spring

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

Related

failure of login page in thymeleaf

I create login page and it fetch username and password from database
but when i enter correct username and password it throw invalid
credential exception .I check every thing properly and define
everything. I want when user successful login he can see products and
search products. but my login not working .it crashed every time
login.html
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="/fragments/head"></head>
<body>
<nav th:replace="/fragments/nav :: nav-front"></nav>
<div class="container-fluid mt-5">
<div class="row">
<div th:replace="/fragments/categories"></div>
<div class="col"></div>
<div class="col-6 text-center">
<h3 class="display-4">Login</h3>
<div class="alert alert-danger" th:if="${param.error}">
Invalid credentials
</div>
<form method="post" th:action="#{/login}">
<div class="form-group">
<label>Username:</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Username">
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
<button class="btn btn-danger mb-5">Login</button>
<p>
Click <a th:href="#{/register}">here</a> to register.
</p>
</form>
</div>
<div class="col"></div>
</div>
</div>
<div th:replace="/fragments/footer"></div>
</body>
</html>
pagesController.kt
package com.nilmani.cmsshopingcart.controller
import com.nilmani.cmsshopingcart.model.Page
import com.nilmani.cmsshopingcart.repository.PageRepository
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.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
#Controller
#RequestMapping("/")
class PagesController {
#Autowired
private lateinit var pageRepository: PageRepository
#GetMapping
fun home(model: Model?):String{
val page: Page? = pageRepository.findBySlug("home")
if (model != null) {
model.addAttribute("page",page)
}
return "page"
}
#GetMapping("/login")
fun login():String{
return "login"
}
#GetMapping("/{slug}")
fun page(#PathVariable slug: String, model: Model): String? {
val page: Page = pageRepository.findBySlug(slug) ?: return "redirect:/"
model.addAttribute("page", page)
return "page"
}
}
UserRepositoryUserDetailsService.kt
package com.nilmani.cmsshopingcart.security
import com.nilmani.cmsshopingcart.model.Admin
import com.nilmani.cmsshopingcart.model.UserEntity
import com.nilmani.cmsshopingcart.repository.AdminRepository
import com.nilmani.cmsshopingcart.repository.UserRepository
import org.springframework.beans.factory.annotation.Autowired
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.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Service
#Service
class UserRepositoryUserDetailsService : UserDetailsService {
#Autowired
private lateinit var userRepo:UserRepository
#Autowired
private lateinit var adminRepo:AdminRepository
#Throws(UsernameNotFoundException::class)
override fun loadUserByUsername(email: String): UserDetails {
val user: UserEntity? = userRepo.findByUsername(email)
val admin: Admin? = adminRepo.findByUsername(email)
if (user != null) {
return User(user.username,user.password,ArrayList())
}
if (admin != null) {
return admin
}
throw UsernameNotFoundException("User: $email not found!")
}
}
UserEntity.kt
package com.nilmani.cmsshopingcart.model
import lombok.Data
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.UserDetails
import java.util.*
import javax.persistence.*
import javax.validation.constraints.Email
import javax.validation.constraints.Size
import kotlin.jvm.Transient
#Data
#Entity
#Table(name = "user")
data class UserEntity(
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
val id:Int=0,
#Size(min = 5,message = "Name must be attlist 5 character long")
private var username:String="",
#Size(min = 8,message = "Password contain above 8 character long")
private var password:String="",
#Transient
val confirmPassword:String="",
#Email(message = "please enter a valid email")
val email:String="",
#Size(min = 10,message = "phone number must be 10 digit")
val phoneNumber:String="",
):UserDetails{
override fun getAuthorities(): List<SimpleGrantedAuthority> {
return listOf(SimpleGrantedAuthority("ROLE_USER"))
}
override fun getPassword(): String {
return password
}
override fun getUsername(): String {
return username
}
override fun isAccountNonExpired(): Boolean {
return true
}
override fun isAccountNonLocked(): Boolean {
return true
}
override fun isCredentialsNonExpired(): Boolean {
return true
}
override fun isEnabled(): Boolean {
return true
}
}
UserRepository.kt
package com.nilmani.cmsshopingcart.repository
import com.nilmani.cmsshopingcart.model.UserEntity
import org.springframework.data.jpa.repository.JpaRepository
interface UserRepository : JpaRepository<UserEntity,Int> {
fun findByUsername(email:String):UserEntity?
}
SecurityConfig.kt
package com.nilmani.cmsshopingcart.security
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.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.UserDetailsService
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
#Service
#Configuration
#EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {
#Autowired
private lateinit var userDetailsService: UserDetailsService
#Bean
fun encoder(): PasswordEncoder {
return BCryptPasswordEncoder()
}
#Throws(java.lang.Exception::class)
override fun configure(auth: AuthenticationManagerBuilder?) {
auth
?.userDetailsService(userDetailsService)
?.passwordEncoder(encoder())
}
#Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http
.authorizeRequests()
.antMatchers("/category/**").hasAnyRole("USER", "ADMIN")
.antMatchers("/admin/**").hasAnyRole("USER")
.antMatchers("/").permitAll()
.and()
.formLogin()
.loginPage("/login")
.and()
.logout()
.logoutSuccessUrl("/")
.and()
.exceptionHandling()
.accessDeniedPage("/")
}
}
what is the region of failure of my loginPage
if you don't want to encrypt password spring automatically encrypted
password. so in that case use NoOpPasswordEncoder.getInstance()
instead BCryptPasswordEncoder()
so change the code
#Bean
fun encoder(): PasswordEncoder {
return BCryptPasswordEncoder()
}
To
#Bean
fun encoder(): PasswordEncoder {
return NoOpPasswordEncoder.getInstance()
}
and pass the instance of passwordEncoder in
AuthenticationManagerBuilder
this code works for me fine

Simple Spring Security example not logging in

Morning!
Just started learning Spring Security with the help of the Baeldung tutorial at https://www.baeldung.com/spring-security-authentication-with-a-database.
However, it's not quite working. What I'm trying to do is connecting my simple H2 database, containing a User table with id, username and password (in plaintext for simplicity), with my secured web application.
I created WebSecurityConfig (extending WebSecurityConfigurerAdapter, see below), MyUserDetailsService (implementing UserDetailsService, see below) and LoggedInUser (implementing UserDetails, see below) classes.
WebSecurityConfig: This should secure all pages except home, login and register pages, which is working. Also, globalSecurityConfiguration should enable the login function by linking to the userDetailsService.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
#Configuration
#EnableWebSecurity
#ComponentScan(basePackageClasses = MyUserDetailsService.class)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private MyUserDetailsService userDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home", "/register").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Autowired
public void globalSecurityConfiguration(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
}
MyUserDetailsService: This gets the Repository injection to access my database. I check the database for the username, and if it's present, I return a new LoggedInUser.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class MyUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) {
List<User> users = userRepository.findByUsername(username);
if (users.size() == 0) {
throw new UsernameNotFoundException(username);
}
return new LoggedInUser(users.get(0));
}
}
And finally, the LoggedInUser class:
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
public class LoggedInUser implements UserDetails {
private User user;
public LoggedInUser(User user) {
this.user= user;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return AuthorityUtils.createAuthorityList("ROLE_USER");
}
#Override
public String getPassword() {
return user.getPassword();
}
#Override
public String getUsername() {
return user.getNickname();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
When I try to log in with some nonexistent username, the error message pops as it should. However, when I'm trying to log in with an existing username (with any password, right or wrong), it's not giving any error message but isn't logging me in either (at least I still can't access other secured pages of the app).
I'm omitting User and UserRepository classes since they're just pretty straightforward and well tested. My login page looks like that:
<html xmlns:th="http://www.thymeleaf.org" xmlns:tiles="http://www.thymeleaf.org">
<head>
<title>Spring Security Example</title>
</head>
<body>
<div class="container">
<form name="f" th:action="#{/login}" method="post">
<fieldset>
<legend>Please Login</legend>
<div th:if="${param.error}" class="alert alert-error">
Invalid username and password.
</div>
<div th:if="${param.logout}" class="alert alert-success">
You have been logged out.
</div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username"/>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</fieldset>
</form>
</div>
</body>
</html>
I know that the loadUserByUsername method isn't touching the password, but from what I've read, checking if the right password was entered happens automatically within the Security framework.
I also tried to implement my own AuthenticationProvider to use instead of the UserDetailsService to check if both username and password inputs match the database entries within the authenticate method, but then I encountered another problem - wrong credentials now get flagged right, but right credentials produced an error Cannot invoke "Object.toString()" because the return value of "org.springframework.security.core.Authentication.getCredentials()" is null. However the line the error mentioned was the one that reads the password from the user input - and since this only happens for passwords matching the correct one, this shouldn't be null. I'm not posting code here since probably this is a different issue though.
Thanks for any help! Remember, this is like the first time I touched any security framework, so better ELI5 :)

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.

Passing String from jsp to Controller in 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

Resources