Hey I got this problem when running my application in jetty.
I create some application web base on java with spring framework and maven.
When I want to try to login into my site, i got an error.
This error log from jetty:
javax.el.PropertyNotFoundException: /screens/login.xhtml #30,138 value="#{securityBean.userId}": Target Unreachable, identifier 'securityBean' resolved to null
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:97)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:91)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1023)
at javax.faces.component.UIInput.validate(UIInput.java:953)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1204)
at javax.faces.component.UIInput.processValidators(UIInput.java:693)
at javax.faces.component.UIForm.processValidators(UIForm.java:240)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1081)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1081)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1159)
This my login.xhtml:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.prime.com.tr/ui">
<f:view contentType="text/html">
<h:head>
<title>igate web admin</title>
<meta content='text/html; charset=UTF-8' http-equiv="Content-Type"/>
<link type="text/css" rel="stylesheet" href="#{request.contextPath}/themes/bootstrap/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="#{request.contextPath}/themes/bootstrap/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="#{request.contextPath}/themes/bootstrap/bootstrap-theme.css" />
<link type="text/css" rel="stylesheet" href="#{request.contextPath}/themes/bootstrap/bootstrap-theme.min.css" />
<ui:insert name="head"></ui:insert>
</h:head>
<h:body>
<div class="container">
<h:form class="form-signin" role="form">
<div class="logo"></div>
<h2 class="form-signin-header" style="text-align: center; color: white"> LOGIN I-GATE</h2>
<h:inputText class="form-control" required="true" requiredMessage="Username harus diisi" id="uname" value="#{securityBean.userId}"/>
<br></br>
<h:inputSecret class="form-control" required="true" requiredMessage="Password harus diisi" value="#{securityBean.password}"/>
<button class="btn btn-lg btn-primary btn-block" type="submit" action="#{securityBean.login}" ajax="false">Sign in</button>
<h4 style="text-align: center; color: white;">Please login with your Username and Password</h4>
</h:form>
</div>
</h:body>
And this my securityPage.java:
#ManagedBean( name="securityBean" )
#SessionScoped
public class SecurityPage {
private String userId;
private String password;
private UserDao userDao;
private Logger log = Logger.getLogger( SecurityPage.class );
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* use to clear properties in this class
*
*/
private void clearPage() {
this.userId = null;
this.password = null;
}
/**
* Executed to validate username and password
*
* #return String
*/
public String login() {
userDao = ( UserDao ) ServiceLocator.getService( "userDao" );
try {
String pass = Secure.digest( password );
MUser user = userDao.login( userId, pass );
if( user != null ) {
SessionUtil.setUserSession( user );
SessionUtil.setObject( Constant.LOGIN_ROLENAME, user.getRoleName() );
}
else {
FacesContext.getCurrentInstance().addMessage(
"msgs",
new FacesMessage( FacesMessage.SEVERITY_WARN,
"User ID atau Password anda tidak valid.",
"User ID atau Password anda tidak valid." ) );
clearPage();
return "login_failed";
}
}
catch( Exception e ) {
FacesContext.getCurrentInstance().addMessage(
"msgs",
new FacesMessage( FacesMessage.SEVERITY_WARN,
"User ID atau Password anda tidak valid.",
"User ID atau Password anda tidak valid." ) );
clearPage();
return "login_failed";
}
clearPage();
return "login_success";
}
/**
* Logout Action
*
* Executed to invalidate session and logout user
*
* #return String
*/
public String logout() {
log.info( "user logout from application" );
try {
SessionUtil.invalidate();
}
catch( Exception e ) {
log.error( e );
}
return "/screens/login.jsf?faces-redirect=true";
}
}
I stuck on this problem. I've tried to follow another suggestion from stackoverflow. but no one can fixed this. Please help :)
Thanks.
Related
I have a problem using mockito in my spring boot project. What should I do to test the business layer? (I only have the builder test).
public class ProductBuilder {
private Product product;
private Collection<Product> products;
public static ProductBuilder mockProductBuilder() {
ProductBuilder builder = new ProductBuilder();
builder.product = new Product("Beer", "Alcholic", "20,99", "Montez");
return builder;
}
public static ProductBuilder mockCollectionProductBuilder() {
ProductBuilder builder = new ProductBuilder();
builder.products = new ArrayList<Product>();
for (int i = 0; i < 10; i++) {
Product product = new Product("Beer " + i, "Alcholic", "20,99" + i, "Montez");
builder.products.add(product);
}
return builder;
}
// Methods
public Product getProduct() {
return this.product;
}
public Collection<Product> getProducts() {
return this.products;
}
You need to have test for your classes controllers, repositories and services. Your builder is fine, your controller should like something like
#SpringBootTest
public class ProductControllerTest {
#InjectMocks
private ProductController productController;
#Mock
private ProductService productService;
#Mock
private BindingResult bindingResult;
private Model model;
private Product productOptional;
private List<Product> products;
private Product product;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
this.productOptional = ProductBuilder.mockProductBuilder().getProduct();
this.products = (List<Product>) ProductBuilder.mockCollectionProductBuilder().getProducts();
this.product = ProductBuilder.mockProductBuilder().getProduct();
this.model = new ConcurrentModel();
}
#Test
public void index() {
Mockito.when(this.productService.searchAll()).thenReturn(this.products);
Assert.assertEquals(this.productController.index(this.model), "product/index");
Assert.assertEquals(this.model.containsAttribute("products"), true);
}
#Test
public void create() {
Assert.assertEquals(this.productController.add(product, this.model), "product/addProduct");
}
#Test
public void update() {
Mockito.when(this.productService.searchById((long) 1)).thenReturn(this.productOptional);
Assert.assertEquals(this.productController.edit((long) 0, this.model), "product/editProduct");
Assert.assertEquals(this.model.containsAttribute("product"), false);
}
#Test
public void save() {
Mockito.when(this.productService.inserir(this.product)).thenReturn(this.product);
Mockito.when(this.bindingResult.hasErrors()).thenReturn(true);
Assert.assertEquals(this.productController.save(this.product, this.bindingResult, this.model), "product/addProduct");
}
#Test
public void saveError() {
Mockito.when(this.productService.inserir(this.product)).thenReturn(this.product);
Mockito.when(this.bindingResult.hasErrors()).thenReturn(true);
Assert.assertEquals(this.productController.save(this.product, this.bindingResult, this.model), "product/addProduct");
}
#Test
public void delete() {
Assert.assertEquals(this.productController.delete((long) 1, this.model), "product/index");
Mockito.verify(this.productService, Mockito.times(1)).deletar((long) 1);
}
}
For repositories
#RunWith(SpringRunner.class)
#SpringBootTest
public class ProductRepositoryTest {
#Autowired
private ProductRepository productRepository;
private Product product;
#Before
public void setUp() {
this.product = ProductBuilder.mockProductBuilder().getProduct();
}
#After
public void after() {
this.productRepository.deleteAll();
}
#Test
public void findAll() {
Assert.assertThat(this.productRepository.findAll(), instanceOf(List.class));
}
#Test
public void findById() {
Assert.assertThat(this.productRepository.findById((long) 2), instanceOf(Optional.class));
}
#Test
public void saveCreate() {
this.product.setId((long) 1);
this.product = this.productRepository.save(this.product);
//Assert.assertNotEquals(this.product.getId(), 1);
}
#Test
public void saveUpdate() {
this.product.setId((long) 0);
this.product = this.productRepository.save(this.product);
this.product.setNome("Jonas");
Product productAtualizado = this.productRepository.save(this.product);
Assert.assertEquals(productAtualizado.getNome(), this.product.getNome());
}
#Test
public void deleteById() {
this.product = this.productRepository.save(this.product);
this.productRepository.deleteById(this.product.getId());
Assert.assertEquals(this.productRepository.findAll().size(), 0);
}
For Services
#SpringBootTest
public class ProductServiceTest {
#InjectMocks
private ProductService productService;
#Mock
private ProductRepository productRepository;
private Product productTest;
private List<Product> products;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
this.productTest = ProductBuilder.mockProductBuilder().getProduct();
this.products = (List<Product>) ProductBuilder.mockCollectionProductBuilder().getProducts();
}
#Test
public void buscarTodosTest() {
Mockito.when(this.productRepository.findAll()).thenReturn(this.products);
List<Product> productsBd = this.productService.buscarTodos();
assertEquals(productsBd, this.products);
}
#Test
public void buscarPeloId() {
Optional<Product> productOptional = Optional.of(this.productTest);
Mockito.when(this.productRepository.findById(this.productTest.getId())).thenReturn(productOptional);
Product product = this.productService.buscarPeloId(this.productTest.getId());
assertEquals(product, productOptional.get());
}
#Test
public void inserirTest() {
Mockito.when(this.productRepository.save(this.productTest)).thenReturn(this.productTest);
Product productSalvo = this.productService.inserir(this.productTest);
assertEquals(productSalvo, this.productTest);
}
#Test
public void atualizarTest() {
Optional<Product> productOptional = Optional.of(this.productTest);
this.productTest.setId((long) 1);
Mockito.when(this.productRepository.save(this.productTest)).thenReturn(this.productTest);
Mockito.when(this.productRepository.findById(this.productTest.getId())).thenReturn(productOptional);
Product productAtualizado = this.productService.atualizar(this.productTest);
assertEquals(productAtualizado, this.productTest);
}
#Test
public void deletarTest() {
Optional<Product> productOptional = Optional.of(this.productTest);
Mockito.when(this.productRepository.findById(this.productTest.getId())).thenReturn(productOptional);
this.productService.deletar(this.productTest.getId());
Mockito.verify(this.productRepository, Mockito.times(1)).findById(this.productTest.getId());
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="MyMusic">
<meta name="author" content="Victoria Brandt">
<title>Users - MyMusic</title>
</head>
<body>
<nav>
<ul>
<li>User</li>
<li>Music</li>
<li>Playlist</li>
</ul>
</nav>
<div>
<div >
<div>
<strong><h2>Users</h2></strong>
</div>
</br>
<div >
<a th:href="#{/users/addUser}" >Add new user</a>
</div>
</br>
<div>
<div >
<table >
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.location}"></td>
<td >
<div >
<a th:href="#{/users/editUser/{id}(id=${user.id})}" >Edit</a>
<a class="delete btn btn-sm btn-danger" th:href="#{/users/deleteUser/{id}(id=${user.id})}">Delete</a>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="MyMusic">
<meta name="author" content="Victoria Brandt">
<title>Users - MyMusic</title>
</head>
<body>
<nav>
<ul>
<li>User</li>
<li>Music</li>
<li>Playlist</li>
</ul>
</nav>
<div>
<div>
<div>
<strong><h2>Create new user</h2></strong>
</div>
</br>
<div>
<div>
<form th:object="${user}" th:action="#{/users/saveUser}"
method="POST">
<div>
<fieldset>
<div>
<div th:if="${#fields.hasAnyErrors()}">
<div th:each="detailedError : ${#fields.detailedErrors()}">
<span th:text="${detailedError.message}"></span>
</div>
</div>
</div>
<div>
<div>
<input type="text" id="id" th:field="*{id}" readOnly="readonly" />
</div>
</div>
<div>
<div th:classappend="${#fields.hasErrors('name')}? 'has-error'">
<label>Name</label> <input type="text" th:field="*{name}"
autofocus="autofocus" />
</div>
</div>
<div>
<div
th:classappend="${#fields.hasErrors('location')}? 'has-error'">
<label>Location</label> <input type="text"
th:field="*{location}" />
</div>
</div>
</fieldset>
</div>
<div >
<button type="submit" >Save</button>
<a th:href="#{/users}">Cancel</a>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
I am a newbie in spring boot. I'm using basic thymeleaf form login. But when I login it returns "localhost:8080/login?error=true". I don't know why. My username and password in the database are correct. Maybe I must add a new controller with post method? please help me
And here, this is my security config class
protected void configure(HttpSecurity http) throws Exception {
logger.info("-----configure(HttpSecurity http)");
http.authorizeRequests()
.antMatchers("/**").permitAll()
.antMatchers("/user/**").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.permitAll()
.and().csrf().disable();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
logger.info("-----configureGlobal(AuthenticationManagerBuilder auth)");
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
login form page
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Stacked form</h2>
<form th:action="#{/login}" method="post">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control input-lg"
placeholder="UserName" required="true" autofocus="true"/>
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-lg"
placeholder="Password" required="true"/>
</div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" type="checkbox" name="remember"> Remember me
</label>
</div>
<a class="btn btn-success" th:href="#{'/register'}" role="button">Register</a>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>
My controller
#GetMapping("/login")
public String login() {
return "/login";
}
The entity
#Entity(name = "dbo_user")
public class User {
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
#Id
private int id;
private String email;
private String password;
private String username;
}
First of all, User class has to implement UserDetails interface like this:
// userdetails methods
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.roles.stream().map(SimpleGrantedAuthority::new).collect(toList());
}
#Override
public String getUsername() {
return this.getEmail();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
#Transient
private List<String> roles = Arrays.asList("ROLE_USER");
public List<String> getRoles() {
return roles;
}
2nd you need a class that implements UserDetailsService like this:
#Service("customCustomerDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private CredentialRepository users;
#Override
public UserDetails loadUserByUsername(String email) {
return this.users.findByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException("Username: " + email + " not found"));
}
}
Then you autowire that class into your security config class
#Autowired
CustomUserDetailsService customCustomerDetailsService;
You need to implement DAO DaoAuthenticationProvider in your security config class like this:
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(encoder());
return authProvider;
I'm quite sure this question would have been answered on this platform.
Are you using thymeleaf security extras? If so, then you need to have dependency included with maven/gradle and thymeleaf namespaces on the login page.
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
and
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5" lang="en">
My page doesn’t open. On this page I can create a user and give him a username and password + role (admin or user). Why does page doesn t work. You can look at the code, it seems to have written correctly. Maybe somewhere I made a mistake in the code.Tomcat gives error 404. I just need him to open this page, you can see the controller
Admin Controller
#Controller
#RequestMapping("/admin")
public class AdminController {
#Autowired
private StudentService studentService;
#GetMapping("/allStudentsAdmin")
public ModelAndView allStudentsForUser() {
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudentsAdmin");
return mv;
}
#GetMapping(value = "/deleteStudent/{id}")
public ModelAndView deleteUserById(#PathVariable Long id) {
studentService.deleteStudentById(id);
ModelAndView mv = new ModelAndView("redirect:/admin/allStudentsAdmin");
return mv;
}
#GetMapping(value = "/editStudent/{id}")
public ModelAndView displayEditUserForm(#PathVariable Long id) {
ModelAndView mv = new ModelAndView("adminEditStudent");
Student student = studentService.getStudentById(id);
mv.addObject("headerMessage", "Редактирование студента");
mv.addObject("student", student);
return mv;
}
#PostMapping(value = "/editStudent")
public String saveEditedUser(
#RequestParam("id") Long id,
#RequestParam("name") String name,
#RequestParam("surname") String surname,
#RequestParam("avatar") MultipartFile file) {
try {
studentService.updateStudent(name, surname, file, studentService.getStudentById(id));
} catch (FileSystemException ex) {
ex.printStackTrace();
} catch (IOException e) {
return "redirect:/errors";
}
return "redirect:/admin/allStudentsAdmin";
}
#GetMapping(value = "/addStudentAdmin")
public ModelAndView displayNewUserForm() {
ModelAndView mv = new ModelAndView("addStudentAdmin");
mv.addObject("headerMessage", "Add Student Details");
mv.addObject("student", new Student());
return mv;
}
#PostMapping(value = "/addStudentAdmin")
public String saveNewStudent(#RequestParam("name") #NonNull String name,
#RequestParam("surname") #NonNull String surname,
#RequestParam("avatar") MultipartFile file)
throws IOException {
Student student = new Student();
student.setSurname(surname);
student.setName(name);
if (file != null && !file.isEmpty()) {
student.setAvatar(studentService.saveAvatarImage(file).getName());
}
studentService.saveStudent(student);
return "redirect:/admin/allStudentsAdmin";
}
#GetMapping(value = "/addUser")
public ModelAndView displayAddUserForm() {
ModelAndView mv = new ModelAndView("addStudentAdmin");
mv.addObject("headerMessage", "Add Student Details");
mv.addObject("student", new Student());
return mv;
}
#PostMapping(value = "/addUser")
public String saveNewUser(#RequestParam("name") #NonNull String name,
#RequestParam("surname") #NonNull String surname,
#RequestParam("role") #NonNull String role)
throws IOException {
Student student = new Student();
student.setSurname(surname);
student.setName(name);
studentService.saveStudent(student);
return "redirect:/admin/allStudentsAdmin";
}
}
Admin Decorator
<body>
<div id="container">
<div id="header">
</div>
<div id="nav">
<ul>
<li><span>Главная</span></li>
<li class="dropdown"><span>Студенты</span>
<ul>
<li><span>Список студентов</span></li>
<sec:authorize access="hasRole('ADMIN') || hasRole('USER')">
<li><span>Добавить студента</span></li>
</sec:authorize>
<sec:authorize access="hasRole('ADMIN')">
<li><span>Добавить юзера</span></li>
</sec:authorize>
</ul>
</li>
<li><a><span>О нас </span></a></li>
<sec:authorize access="!isAuthenticated()">
<li><span>Выйти</span></li>
</sec:authorize>
</ul>
</div>
</div>
<sitemesh:write property='body'/>
<jsp:include page="/WEB-INF/template/admintemplate.jsp"/>
</body>
</html>
AddUser.JSP
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<title>Home</title>
</head>
<body>
<div class="add">
<br>
<br>
<br>
<br>
<center>
<h1>${headerMessage}</h1>
<form:form method="POST" action="${pageContext.request.contextPath}/admin/addUser" enctype="multipart/form-data">
<table>
<tr>
<td><label path="Name">Name</label></td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td><label path="Surname">Surname</label></td>
<td><input type="text" name="surname"/></td>
</tr>
<tr>
<td><select name="select" size="3" multiple>
<option selected value="s1">Admin</option>
<option value="s2">User</option>
</select></td>
<td>
<input type="text" name="Role"/>
</td>
</tr>
<tr>
<td><input class="btn btn-primary" type="submit" value="Добавить"></td>
</tr>
</table>
</form:form>
</center>
</div>
</body>
</html>
Change URL to admin/addUser
because in your controller you have added a root level admin
#RequestMapping("/admin")
ex .http://localhost:8080/SchoolMaven/admin/addUser
I'm trying to set username as Http session attribute when user loging in but it gives me an error
Required String parameter 'username' is not present
This is my controller class, getLoginForm method. Here I'm trying to get username string from input and puting it to httpSession (because i will need this username to use in other requests).
package com.vandh.app.controller;
import javax.servlet.http.HttpSession;
#Controller
#SessionAttributes("username")
public class LoginController {
#RequestMapping(value = { "/", "/home" })
public String getUserDefault() {
return "home";
}
#RequestMapping("/login")
public ModelAndView getLoginForm(#ModelAttribute Users users,
#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout,
#RequestParam(value="username") String username,
HttpSession httpSession) {
String message = "";
if (error != null) {
message = "Incorrect username or password !";
} else if (logout != null) {
message = "Logout successful !";
}
else
if(error==null)
{
httpSession.setAttribute("username", username);
}
return new ModelAndView("login", "message", message);
}
#RequestMapping("/admin**")
public String getAdminProfile() {
return "admin";
}
#RequestMapping("/403")
public ModelAndView getAccessDenied() {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
String username = "";
if (!(auth instanceof AnonymousAuthenticationToken)) {
UserDetails userDetail = (UserDetails) auth.getPrincipal();
username = userDetail.getUsername();
}
return new ModelAndView("403", "username", username);
}
}
Here is my DAO class of finding users in DB (MySQL)
#Repository("loginDao")
public class LoginDaoImpl implements LoginDao {
#Autowired
SessionFactory sessionFactory;
//public String userLogIn; // checking username in auth. process
Session session = null;
Transaction tx = null;
#Override
public Users findByUserName(String username ) {
String login = username;
session = sessionFactory.openSession();
tx = session.getTransaction();
session.beginTransaction();
Users user = (Users) session.load(Users.class, new String(username));
tx.commit();
return user;
}
}
And this is my login.jsp page
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login </title>
</head>
<body>
<br /> <br /> <br />
<div style="border: 1px solid black; width: 300px; padding-top: 10px;">
<br /> Please enter your username and password to login ! <br /> <span
style="color: red">${message}</span> <br />
<form:form method="post" action="j_spring_security_check"
modelAttribute="users">
<table>
<tr>
<td>Username:</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><form:input path="password" type="password" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" /></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
i m encountering the date problem in UI using spring , when i fetch query from database the data format is shown in my UI is 1987-02-12 00:00:00.0 when i submit the values null is going in database . I have used the
return getJdbcTemplate().update(
QUERY_CREATE_PROJECT,
new Object[] { employeeProject.getEmployeeNumber(),
employeeProject.getProjectCode(),
employeeProject.getStartDate(),
employeeProject.getEndDate(),
employeeProject.getProjectRole() }) != 0 ? true : false;
} method of spring , my reqiurement is to show date in format (dd/MM/yyyy) and insert the date in same format .How to convert the format of date in our custom date plz help me and also tell me where to use customization of date , should i customize date in controller layer ,DAO layer or in service layer
my controller method of creating is
package com.nousinfo.tutorial.controllers;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
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.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.nousinfo.tutorial.model.ProjectForm;
import com.nousinfo.tutorial.service.impl.ProjectServiceImpl;
import com.nousinfo.tutorial.service.model.EmployeeProjectBO;
/**
*
* #author ankurj
*
*/
#Controller
#RequestMapping("projectController")
public class ProjectController {
private ProjectServiceImpl projectServiceImpl;
public ProjectServiceImpl getProjectServiceImpl() {
return projectServiceImpl;
}
public void setProjectServiceImpl(ProjectServiceImpl projectServiceImpl) {
this.projectServiceImpl = projectServiceImpl;
}
/**
* Used to set the view
* #param id
* #return
* #throws Exception
*/
#RequestMapping(value = "/projectForm", method = RequestMethod.GET)
public ModelAndView view(#RequestParam("id") int id) throws Exception {
ModelAndView modelAndView = new ModelAndView();
System.out.println(id);
ProjectForm projectForm = new ProjectForm();
projectForm.setEmployeeNumber(id);
modelAndView.addObject("projectForm", projectForm);
modelAndView.setViewName("projectForm");
return modelAndView;
}
/**
* Create the project for an employee
* #param projectForm
* #param bindingResult
* #param model
* #return
* #throws Exception
*/
#RequestMapping(value = "/createProject", method = RequestMethod.POST)
public String createEmployee(#Valid ProjectForm projectForm,
BindingResult bindingResult, Map<String, ProjectForm> model)
throws Exception {
String form = null;
if (bindingResult.hasErrors()) {
return "projectForm";
}
model.put("projectForm", projectForm);
projectForm.setUpdateStatus("A");
if (projectForm.getUpdateStatus().charAt(0) == 'A') {
boolean flag = projectServiceImpl
.actionDecider(convertprojectFormToprojectBO(projectForm));
if (flag == false)
form = "DBError";
else
form = "Success";
}
return form;
}
/**
* This method update the existing detail of project
* #param projectForm
* #param bindingResult
* #return
*/
#RequestMapping(value = "/updateProject", method = RequestMethod.POST)
public String updateDepartment(
#ModelAttribute("projectForm") ProjectForm projectForm,
BindingResult bindingResult) {
String form = null;
projectForm.setUpdateStatus("M");
if (projectForm.getUpdateStatus().charAt(0) == 'M') {
boolean flag = projectServiceImpl
.actionDecider(convertprojectFormToprojectBO(projectForm));
if (flag == false)
form = "DBError";
else
form = "Success";
}
return form;
}
and this is my model class
package com.nousinfo.tutorial.model;
import java.util.Date;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.NumberFormat;
public class ProjectForm {
#NotNull
#NumberFormat
#Min(1)
private Integer employeeNumber;
#NotEmpty(message = "project code can't be blank")
private String projectCode;
private Date startDate;
private Date endDate;
private String role;
private String updateStatus;
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Integer getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(Integer employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getUpdateStatus() {
return updateStatus;
}
public void setUpdateStatus(String updateStatus) {
this.updateStatus = updateStatus;
}
}
this is my jsp for date
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%# 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/functions" prefix="fn"%>
<!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></title>
<script>
function actionChange(url) {
if (url == 'Save') {
document.form.action = "/EmployeeWebSpring/projectController/updateProject";
}
if (url == 'Delete') {
document.form.action = "/EmployeeWebSpring/projectController/deleteProject";
}
}
function home() {
window.location.href = "/EmployeeWebSpring/search/searchspring";
}
</script>
</head>
<body background="../images/flower.jpg">
<img src="../images/Header.png" width="1500"/>
<hr width="1500">
<form:form name='form' commandName="projectForm">
<fmt:message key="project.searchResult.header" />
<c:choose>
<c:when test="${empty requestScope.projectBO}">
<fmt:message key="searchResult.noresult" />
</c:when>
<c:otherwise>
<table align="center">
<form:hidden path="updateStatus" />
<tr align="center">
<th><fmt:message key="employeeNumber" /></th>
<td><form:input path="employeeNumber"
value="${requestScope.projectBO.employeeNumber}" /></td>
</tr>
<tr align="center">
<th><fmt:message key="projectCode" /></th>
<td><form:input path="projectCode"
value="${requestScope.projectBO.projectCode}" /></td>
</tr>
<tr>
<tr align="center">
<th><fmt:message key="startDate" /></th>
<td><form:input path="startDate"
value="${requestScope.projectBO.startDate}" /></td>
</tr>
<tr>
<tr align="center">
<th><fmt:message key="endDate" /></th>
<td><form:input path="endDate"
value="${requestScope.projectBO.endDate}" /></td>
</tr>
<tr>
<tr align="center">
<th><fmt:message key="role" /></th>
<td><form:input path="role"
value="${requestScope.projectBO.role}" /></td>
</tr>
</table>
<br>
<center>
<table>
<tr>
<td><input type="submit" name="method" value="Save"
onclick="actionChange(this.value)" /></td>
<td><input type="submit" name="method" value="Delete"
onclick="actionChange(this.value)" /></td>
<td><input type="button" onclick="home" value="Cancel" /></td>
</tr>
</table>
</center>
</c:otherwise>
</c:choose>
<br />
<fmt:message key="searchResult.searchAgain" />
<a href="/EmployeeWebSpring/search/searchspring"> <fmt:message
key="searchResult.click" />
</a>
</form:form>
</body>
</html>
All you need is the custom editor for Date type, through which you can format the incoming & outgoing date object.This was already explained in the post
Spring MVC - Binding a Date Field