Each role has its own accessible page - spring

I create a project where admin and user can log in. I have JSP pages, only the admin can enter there, because access is restricted to the user. The user can go to certain pages.
I have two pages "allStudents.jsp" - only admin can go there.
And on this page "allStudentsUser.jsp" - only the user can enter.
So this is how to write the code in the controller correctly so that Tomkat read my "allStudentsUser.jsp" page.
Student Controller
#Controller
public class StudentController {
#Autowired
private ServletContext servletContext;
// Constructor based Dependency Injection
private StudentService studentService;
public StudentController() {
}
#Autowired
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
#RequestMapping(value = "/allStudents", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUser() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudents");
return mv;
}
#RequestMapping(value = "/allStudentsUser", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUsers() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudentsUser");
return mv;
}
#RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public ModelAndView displayNewUserForm() {
ModelAndView mv = new ModelAndView("addStudent");
mv.addObject("headerMessage", "Add Student Details");
mv.addObject("student", new Student());
return mv;
}
#PostMapping(value = "/addStudent")
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:/allStudents";
}
#GetMapping(value = "/editStudent/{id}")
public ModelAndView displayEditUserForm(#PathVariable Long id) {
ModelAndView mv = new ModelAndView("editStudent");
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:/error";
}
return "redirect:/allStudents";
}
#GetMapping(value = "/deleteStudent/{id}")
public ModelAndView deleteUserById(#PathVariable Long id) {
studentService.deleteStudentById(id);
ModelAndView mv = new ModelAndView("redirect:/allStudents");
return mv;
}
}
Security Config
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password(passwordEncoder().encode("1234")).roles("ADMIN")
.and()
.withUser("user").password(passwordEncoder().encode("user1234")).roles("USER")
.and();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/allStudentsUser**").permitAll()
.antMatchers("/allStudents**").hasRole("ADMIN")
.antMatchers("/addStudent/**").hasAnyRole("USER", "ADMIN")
.antMatchers("/editStudent/**").hasRole("ADMIN")
.antMatchers("/deleteStudent/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/allStudents")
.failureUrl("/login?error=true")
.and()
.logout()
.logoutSuccessUrl("/login?logout=true")
.and()
.csrf().disable();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
AllStudents.jsp (for Admin)
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<!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=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>
<link href="../css/style.css" rel="stylesheet" type="text/css">
<style><%#include file="/css/style.css"%></style>
<title>Все студенты</title>
</head>
<body>
<br>
<br>
<br>
<br>
<div class="it">
<h3>Список всех студентов</h3>
${message}
<br>
<br>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Avatar</th>
</tr>
</thead>
<tbody>
<c:forEach var="student" items="${studentList}">
<tr>
<th scope="row">1</th>
<td>${student.name}</td>
<td>${student.surname}</td>
<td><img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}" style="max-height: 200px; max-width: 200px;" /></td>
<td>
<sec:authorize access="hasRole('ADMIN')">
<a href="${pageContext.request.contextPath}/editStudent/${student.id}">
<button type="button" class="btn btn-primary">Edit</button>
</a>
</sec:authorize>
</td>
<td>
<sec:authorize access="hasRole('ADMIN')">
<a href="${pageContext.request.contextPath}/deleteStudent/${student.id}">
<button type="button" class="btn btn-primary">Delete</button>
</a>
</sec:authorize>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
AllStudentsUser.jsp (For User)
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<!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=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>
<link href="../css/style.css" rel="stylesheet" type="text/css">
<style><%#include file="/css/style.css"%></style>
<title>Все студенты</title>
</head>
<body>
<br>
<br>
<br>
<br>
<div class="it">
<h3>Список всех студентов</h3>
${message}
<br>
<br>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Avatar</th>
</tr>
</thead>
<tbody>
<c:forEach var="student" items="${studentList}">
<tr>
<th scope="row">1</th>
<td>${student.name}</td>
<td>${student.surname}</td>
<td><img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}" style="max-height: 200px; max-width: 200px;" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
Student Controller (add Secured)
#RequestMapping(value = "/allStudents", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUser() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudents");
return mv;
}
#Secured("ROLE_ADMIN")
#RequestMapping(value = "/allStudentsAdmin", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUsers() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudentsUser");
return mv;
}
#Secured("ROLE_USER")
#RequestMapping(value = "/allStudentsUser", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUsers() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudentsUser");
return mv;
}

i recommend to use #Secured("ADMIN") or #Secured("USER").
if you want use it, add to #EnableGlobalMethodSecurity(securedEnabled = true) at SecurityConfig.java.
example for your code:
#Secured("ROLE_ADMIN")
#RequestMapping(value = "/allStudents", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUser() {
// ...
}
#Secured("ROLE_USER")
#RequestMapping(value = "/allStudentsUser", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUsers() {
// ...
}
guide link : https://docs.spring.io/spring-security/site/docs/5.2.0.M3/reference/htmlsingle/#jc-method

Related

What should I do to test the business layer using Mockito?

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>

Page in my project doesn't work (Tomcat Error)

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

http 404 error in j_security_check

I am stuck with this persistent error while creating my spring 4 app. Here's my code:
Initializer.java:
public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer implements WebApplicationInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class[] { RootConfig.class, SecurityConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class[] { WebAppConfig.class };
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[] { "/" };
}
// I have tried adding the following but it doesn't seem to work also:
#Override
protected Filter[] getServletFilters() {
// TODO Auto-generated method stub
return new Filter[] { new DelegatingFilterProxy("springSecurityFilterChain") };
}
}
WebAppConfig.java:
#Configuration
#EnableWebMvc
#ComponentScan("com.myco.controller")
public class WebAppConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
RootConfig.java:
#Configuration
#EnableTransactionManagement
#ComponentScan("com.mycompany")
#PropertySource("classpath:application.properties")
public class RootConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
}
SecurityConfig.java:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Autowired
private UserDetailsService userDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().userDetailsService(userDetailsService)
.authorizeRequests()
.antMatchers("/sec/moderation.html").hasRole("MODERATOR")
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/user-login.html")
.defaultSuccessUrl("/success-login.html")
.failureUrl("/error-login.html")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/index.html");
}
}
And lastly, my login jsp (login-form.jsp):
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Login page</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h1>Login page</h1>
<p>
<c:if test="${error == true}">
<b class="error">Invalid login or password.</b>
</c:if>
</p>
<form method="post" action="<c:url value='j_spring_security_check'/>" >
<table>
<tbody>
<tr>
<td>Login:</td>
<td><input type="text" name="j_username" id="j_username"size="30" maxlength="40" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="j_password" id="j_password" size="30" maxlength="32" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login" /></td>
</tr>
</tbody>
</table>
</form>
<p>
Home page<br/>
</p>
</body>
</html>
My error:
If you are using Spring Security 3.2 the login url is changed to /login from /j_spring_security_check also the username and password paremeters are changed.
username : from j_username to username
password : from j_password to password
So your form will be.
<form method="post" action="<c:url value='login'/>" >
<table>
<tbody>
<tr>
<td>Login:</td>
<td><input type="text" name="username" id="username"size="30" maxlength="40" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="password" size="30" maxlength="32" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login" /></td>
</tr>
</tbody>
</table>
</form>

Spring MVC : unable to display drop down

I am not getting the drop down value in Profession. Actually I am getting exception
javax.servlet.ServletException: Type [java.lang.String] is not valid for option items
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:848)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:781)
org.apache.jsp.WEB_002dINF.views.Registration_jsp._jspService(org.apache.jsp.WEB_002dINF.views.Registration_jsp:85)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:263)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:697)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)
root cause
javax.servlet.jsp.JspException: Type [java.lang.String] is not valid for option items
org.springframework.web.servlet.tags.form.OptionWriter.writeOptions(OptionWriter.java:142)
org.springframework.web.servlet.tags.form.SelectTag.writeTagContent(SelectTag.java:223)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:103)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
org.apache.jsp.WEB_002dINF.views.Registration_jsp._jspx_meth_form_select_0(org.apache.jsp.WEB_002dINF.views.Registration_jsp:283)
org.apache.jsp.WEB_002dINF.views.Registration_jsp._jspx_meth_form_form_0(org.apache.jsp.WEB_002dINF.views.Registration_jsp:144)
I understand something wrong with select tag .
please help
RegisterController
package net.codejava.spring.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.codejava.spring.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.servlet.ModelAndView;
#Controller
#RequestMapping(value = "/register")
public class RegisterController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView initForm() {
User user = new User();
user.setUsername("Anukul");
ModelAndView mav = new ModelAndView("Registration");
//=== default user name======
//model.addAttribute("userNameDefault", "Enter Name");
mav.addObject("userNameDefault", "Enter Name");
//==== creating drop down list =====
Map<String,String> profDropDown = new HashMap<String, String>();
profDropDown.put("Lecturer", "Lecturer");
profDropDown.put("proff", "proff");
// //==== adding drop down to user ====
mav.addObject("ProffesionList", profDropDown);
mav.addObject("user",user);
//==== user added to model =========
return mav;
}
#RequestMapping(method = RequestMethod.POST)
public String submitForm(Model model,#ModelAttribute User user) {
model.addAttribute(user);
// implement your own registration logic here...
return "RegistrationSuccess";
}
}
Registration.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration</title>
</head>
<body>
<div align="center">
<h1>reached here</h1>
<form:form action="register" method="POST" commandName="user">
<table border="0">
<tr>
<td colspan="2" align="center"><h2>Spring MVC Form Demo - Registration</h2></td>
</tr>
<tr>
<td>User Name:</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>E-mail:</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Birthday (mm/dd/yyyy):</td>
<td><form:input path="birthDate" /></td>
</tr>
<tr>
<td>Profession:</td>
<td><form:select path="profession" items="${ProffesionList}" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</div>
</body>
User.java
package net.codejava.spring.model;
import java.util.Date;
public class User {
private String username;
private String password;
private String email;
private Date birthDate;
private String profession;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
}
----------------
does this works for you
<form:select id="profession" path="profession">
<form:options items="${ProffesionList}"/>
</form:select>
or try with this
<form:select id="profession" path="profession">
<c:forEach var="prof" items="${ProffesionList}">
<form:option value="${prof.key}" label="${prof.value}" />
</c:forEach>
</form:select>
Controller
#RequestMapping(method = RequestMethod.POST)
public String submitForm(Model model,#ModelAttribute User user) {
//==== creating drop down list =====
Map<String,String> profDropDown = new HashMap<String, String>();
profDropDown.put("Lecturer", "Lecturer");
profDropDown.put("proff", "proff");
// //==== adding drop down to user ====
mav.addObject("ProffesionList", profDropDown);
model.addAttribute(user);
// implement your own registration logic here...
return "RegistrationSuccess";
}
or add #ModelATtribute
#ModelAttribute("ProffesionList")
public Map<String,String> getProfessions(){
Map<String,String> profDropDown = new HashMap<String, String>();
profDropDown.put("Lecturer", "Lecturer");
profDropDown.put("proff", "proff");
return profDropDown;
}

customizing date format using spring

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

Resources