Getting forbidden error in Spring Security (spring boot) - java

package com.project.agro.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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 org.springframework.transaction.annotation.Transactional;
import com.project.agro.model.Role;
import com.project.agro.model.User;
import com.project.agro.repos.UserRepository;
import java.util.HashSet;
import java.util.Set;
#Service
public class UserDetailsServiceImpl implements UserDetailsService{
#Autowired
private UserRepository userRepository;
#Override
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) {
User user = userRepository.findByUsername(username);
if (user == null) throw new UsernameNotFoundException(username);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Role role : user.getRoles()){
grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
}
}
package com.project.agro.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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 org.springframework.transaction.annotation.Transactional;
import com.project.agro.model.Role;
import com.project.agro.model.User;
import com.project.agro.repos.UserRepository;
import java.util.HashSet;
import java.util.Set;
#Service
public class UserDetailsServiceImpl implements UserDetailsService{
#Autowired
private UserRepository userRepository;
#Override
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) {
User user = userRepository.findByUsername(username);
if (user == null) throw new UsernameNotFoundException(username);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Role role : user.getRoles()){
grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
}
}
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link href="${contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
<link href="${contextPath}/resources/css/style.css" rel="stylesheet">
<link href="${contextPath}/resources/css/fixed.css" rel="stylesheet">
</head>
<body>
<%# include file="common/navbar.jsp"%>
<div class="container-fluid">
<div class="row">
<div class="col-3">
<div class="side-nav">
<nav>
<ul>
<li> <span>Title</span></li>
<li> <span>Crops</span></li>
<li class="active"> <span>Fertilizer</span></li>
<li> <span>Agro News</span></li>
</ul>
</nav>
</div>
</div>
<div class="col-9">
<form class="form-horizontal" action="/admin/crop/addcrop"
method="post" enctype="multipart/form-data" style="margin-top:5rem;" >
<fieldset>
<legend class="center-block">
New crop Information
</legend>
<!-- title -->
<div class="form-group" style="display:flex;">
<label class="col-sm-2 control-label" for="title">Crop Name</label>
<div class="col-sm-8">
<input type="text" name="cName" class="form-control" id="cName"
required="required" placeholder="Title" />
</div>
</div>
<!-- author -->
<div class="form-group" style="display:flex;">
<label class="col-md-2 control-label" for="cScientificName">
Scientific Name</label>
<div class="col-md-8">
<input type="text" name="cScientificName" class="form-control"
id="cScientificName" required="required"
placeholder="Scientific Name" />
</div>
</div>
<!-- description -->
<div class="form-group" style="display:flex;">
<label class="col-md-2 control-label" for="description">Description</label>
<div class="col-md-8">
<textarea name="description" rows="5" class="form-control"
id="description" placeholder="Description"></textarea>
</div>
</div>
<!-- upload image -->
<div class="form-group" style="display:flex;">
<div class="col-md-2">
<label for="cImage">Upload crop image</label>
</div>
<div class="col-md-8">
<input id="cImage" type="file" name="cImage" value="cImage" />
</div>
</div>
<!-- description -->
<div class="form-group" style="display:flex;">
<label class="col-md-2 control-label" for="description">Associated
Disease</label>
<div class="col-md-8">
<input type="text" name="associatedDisease" class="form-control"
id="description"
placeholder="Associated Disease" />
</div>
</div>
<div class="form-group" style="display:flex;">
<div class="col-md-2"></div>
<div class="col-md-8">
<button type="submit" class="btn btn-success">Add Book</button>
<a class="btn btn-danger" href="">Cancel</a>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<script src="${contextPath}/resources/js/bootstrap.min.js" ></script>
<script src="${contextPath}/resources/js/jquery-3.3.1.min.js" ></script>
</body>
</html>
-
package com.project.agro;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasAuthority("ADMIN")
.antMatchers("/resources/**", "/registration","/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll().defaultSuccessUrl("/welcome")
.and()
.logout()
.permitAll();
}
#Bean
public AuthenticationManager customAuthenticationManager() throws Exception {
return authenticationManager();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
}
package com.project.agro.controller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import com.project.agro.model.Crop;
import com.project.agro.service.CropService;
#Controller
public class CropController {
#Autowired
private CropService cropService;
#RequestMapping(value="/admin/crop/addcrop" ,method = RequestMethod.GET)
public String addcrop(Model model) {
Crop crop = new Crop();
model.addAttribute("crop", crop);
return "addcrop";
}
#RequestMapping(value="/admin/crop/addcrop" , method = RequestMethod.POST)
public String addcroppost(#ModelAttribute(value="crop") Crop crop ,HttpServletRequest request){
cropService.save(crop);
MultipartFile cImage=crop.getcImage();
try {
byte[] bytes = cImage.getBytes();
String name = crop.getCropID() + ".png";
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(new File("src/main/webapp/image/crop/" + name)));
stream.write(bytes);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/cropList";
}
#RequestMapping("/cropList")
public String cropList(Model model) {
/*List<Book> bookList = bookService.findAll();*/
return "cropList";
}
}
I am trying to build an web application using Spring Boot and Spring Security.I am submitting a form with POST method as an admin to add some details into database but everytime I hit that submit button it shows the error page.I have added all the dependencies .The registration and login page works fine What am I suppose to do here?

Related

Login doesn't work in custom login page for Spring Security

I am having an issue where the custom login page doesn't appear to be working properly. It sends me to the login?error url, rather than the index page. When using the default Spring Security page, it works exactly as intended. I have placed the code below for the html page and the code dealing with the security and custom page in general.
I'm also using a postgresql database if that's somehow involved here.
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:tiles="http://www.thymeleaf.org">
<head>
<title>Index</title>
<link href="webjars/bootstrap/5.1.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container col-xl-10 col-xxl-8 px-4 py-5">
<div class="row align-items-center g-lg-5 py-5">
<div class="col-lg-7 text-center text-lg-start">
<h1 class="display-4 fw-bold lh-1 mb-3">Twitter-Clone</h1>
<p class="col-lg-10 fs-4">You must sign in before accessing the website. THYMELEAF</p>
</div>
<div class="col-md-10 mx-auto col-lg-5">
<form class="p-4 p-md-5 border rounded-3 bg-light" th:action="#{/login}" method="post" name="f">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInput username" placeholder="username">
<label for="floatingInput">User Name</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="floatingPassword password" placeholder="Password" name="password">
<label for="floatingPassword">Password</label>
</div>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="w-100 btn btn-lg btn-info" type="submit">Login</button>
<hr class="my-4">
<small class="text-muted">If you don't have an account, sign up.</small>
</form>
</div>
</div>
</div>
<script src="webjars/jquery/3.6.0/jquery.min.js"></script>
<script src="webjars/bootstrap/5.1.0/js/bootstrap.min.js"></script>
</body>
</html>
SecurityConfiguration.java
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
#EnableWebSecurity
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Bean(name = "pwdEncoder")
public PasswordEncoder getPasswordEncoder() {
DelegatingPasswordEncoder delPasswordEncoder = (DelegatingPasswordEncoder) PasswordEncoderFactories
.createDelegatingPasswordEncoder();
BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
delPasswordEncoder.setDefaultPasswordEncoderForMatches(bcryptPasswordEncoder);
return delPasswordEncoder;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/webjars/**", "/signup").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
You forgot to include the name attribute on your username input.

Spring Thymeleaf - POST into ResponseEntity?

Been at this all day. I may be missing an annotation somewhere. I also cannot get this app to serve the index.html.
What am I missing here? The primary issue is not being able to get the form to submit anything to the backend. Is ModelAttribute correct?
Thanks in advance.
Controller:
package com.lms.application.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.lms.application.entity.Course;
import com.lms.application.service.CourseService;
#RestController
#RequestMapping("/courses")
public class CourseController {
#Autowired
private CourseService service;
#RequestMapping(method=RequestMethod.GET)
public ResponseEntity<Object> getCourses(){
return new ResponseEntity<Object>(service.getCourses(), HttpStatus.OK);
}
#RequestMapping(value="/submit", method=RequestMethod.POST)
public ResponseEntity<Object> createCourse(#ModelAttribute("course") Course course){
return new ResponseEntity<Object>(service.createCourse(course), HttpStatus.CREATED);
}
Form
<div class="container">
<form method="post" th:object="${course}" th:action="#{/courses/submit}">
<div class="row mb-3">
<label for="title" class="col-sm-2 col-form-label">Course Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="course.title" th:field="${course.title}"></input>
</div>
</div>
<div class="row mb-3">
<label for="credit" class="col-sm-2 col-form-label">Course
Credits</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="course.credits" th:field="${course.credits}"></input>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
Before demanding an Object from Thymeleaf you have to create and pass one there. Thymeleaf won't create an object for you.
You need to pass the object via Model to the Controller like so:
#ModelAttribute("course")
public Course course() {
return new Course();
}
You need to make sure Course object has getters, setters and default constructor for Thymeleaf to be able to work with it correctly.

DELETE operation returns ERROR: There was an unexpected error (type=Forbidden, status=403). Forbidden

I am working on a spring-boot project which includes thymeleaf, spring-security. It works fine when I perform - showing products-list, showing products-details, adding new product, updating existing product.
But when I perform - deleting an product, it gives the following ERROR:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Jul 18 16:59:16 BDT 2019
There was an unexpected error (type=Forbidden, status=403).
Forbidden
Here is my code:
product_list.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Product List</title>
<link rel="stylesheet" th:href="#{/css/bootstrap.css}">
</head>
<body>
<div class="container">
<h1>Product List</h1>
<hr>
<a class="btn btn-success" th:href="#{/products/add}">Create New Product</a>
<hr>
<table class="table">
<thead>
<tr>
<th>Product ID</th>
<th>Name</th>
<th>Brand</th>
<th>Made In</th>
<th>Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="theProduct:${theProducts}">
<td th:text="${theProduct.id}">Product ID</td>
<td th:text="${theProduct.name}">Name</td>
<td th:text="${theProduct.brand}">Brand</td>
<td th:text="${theProduct.madein}">Made In</td>
<td th:text="${theProduct.price}">Price</td>
<td>
<a class="btn btn-info" th:href="#{'/products/show/' + ${theProduct.id}}">View</a>
<a class="btn btn-warning" th:href="#{'/products/edit/' + ${theProduct.id}}">Edit</a>
<a class="btn btn-danger" th:data-the-product-id="${theProduct.id}" data-toggle="modal" data-target="#deleteConfirmationModal">Delete</a>
<div class="modal fade" id="deleteConfirmationModal" tabindex="-1" role="dialog" aria-labelledby="deleteConfirmationModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Delete Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you want to DELETE the Product.
<br>
<form id="deleteForm" action="#" th:method="DELETE">
<button type="submit" class="btn btn-danger">Delete Employee</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<script th:src="#{/js/jquery-3.3.1.js}"></script>
<script th:src="#{/js/popper.js}"></script>
<script th:src="#{/js/bootstrap.js}"></script>
<script>
$('#deleteConfirmationModal').on('show.bs.modal', function (event) {
var anchorLink = $(event.relatedTarget)
var theProductId = anchorLink.data('theProductId')
var modal = $(this)
$("#deleteForm").attr("action", "/products/delete/" + theProductId)
})
</script>
</body>
</html>
ProductController.java
package com.example.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.dao.ProductRepository;
import com.example.demo.entity.Product;
#Controller
#RequestMapping("/products")
public class ProductController {
#Autowired
private ProductRepository productRepository;
#GetMapping("/index")
public String index(Model theModel) {
List<Product> theProducts = productRepository.findAll();
theModel.addAttribute("theProducts", theProducts);
return "product/product_list";
}
#GetMapping("/add")
public String add(Model theModel) {
Product theProduct = new Product();
theModel.addAttribute("theProduct", theProduct);
return "product/product_add_form";
}
#GetMapping("/show/{productId}")
public String show(#PathVariable int productId, Model theModel) {
Product theProduct = productRepository.findById(productId).get();
if(theProduct == null) {
return null;
}
theModel.addAttribute("theProduct", theProduct);
return "product/product_detail";
}
#PostMapping("/create")
public String create(#ModelAttribute("theProduct") Product theProduct) {
theProduct.setId(0);
productRepository.save(theProduct);
return "redirect:/products/index";
}
#GetMapping("/edit/{productId}")
public String edit(#PathVariable(name="productId") int productId, Model theModel) {
Product theProduct = productRepository.findById(productId).get();
theModel.addAttribute("theProduct", theProduct);
return "product/product_edit_form";
}
#PutMapping("/update")
public String update(#ModelAttribute("theProduct") Product theProduct) {
productRepository.save(theProduct);
return "redirect:/products/index";
}
#DeleteMapping("/delete/{productId}")
public String delete(#PathVariable int productId) {
Product tempProduct = productRepository.findById(productId).get();
if(tempProduct == null) {
return null;
}
productRepository.deleteById(productId);
return "redirect:/products/index";
}
}
LoginController.java
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class LoginController {
#RequestMapping("/login")
public String login() {
return "login";
}
#GetMapping("/")
public String home(Model theModel) {
return "redirect:/products/index";
}
}
SecurityConfig.java
package com.example.demo.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
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.User;
import org.springframework.security.core.userdetails.User.UserBuilder;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication().withUser(users.username("admin").password("Admin.123").roles("EMPLOYEE", "ADMIN"));
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/css/**")
.permitAll()
.antMatchers("/js/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/authenticateTheUser")
.permitAll()
.and()
.logout()
.permitAll();
}
}
fortunately you add "modal" inside thymeleaf each loop, so edit your html from according my code ....
<form id="deleteForm" th:action="${'/products/delete/' + theProductId}" th:method="DELETE">
<button type="submit" class="btn btn-danger">Delete Employee</button>
</form>
this is tested code ...working fine ..
you just miss "th:action" for that it dose not work as thymeleaf form. so thymeleaf dose not provide hidden "_csrf" field;
Try disabling csrf token in your configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/css/**")
.permitAll()
.antMatchers("/js/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/authenticateTheUser")
.permitAll()
.and()
.logout()
.permitAll()
.and().csrf().disable();
}

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

I know there are many threads on this topic i have tried most of them, still cant fix my problem.I am using SpringMVC and MongoDB What i am trying to achieve is, I will Store some data in database and then i will retrieve it back from data base to a select options. here is my codes.
Jsp page..
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="f"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<!DOCTYPE html>
<html lang="en">
<title>Master Referral</title>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width= device-width, initial-scale=1">
<link type="text/css" rel="stylesheet" href='<spring:url value="/resources/css/bootstrap.min.css" />' >
<link type="text/css" rel="stylesheet" href='<spring:url value="/resources/css/stylesvitalbeat.css" />' >
</head>
<body>
<div class="container-fluid">
<div class="row">
<form action="http://localhost:8080/LoginMavenSpringMVC/admin/create" method="post">
<div class="col-md-2 col-sm-3">
<label class="control-label">Create Category:</label></div>
<div class="col-md-2 col-sm-4">
<input type="text" class="form-control input-sm field_color" name="categoryName" placeholder="Name of the Category">
</div>
<div class="col-md-1 col-sm-3">
<input type="submit" class="btn btn-primary btn-sm height_margin" name="create" value="Create">
</div>
</form>
<div>
<form class="form-horizontal" action="http://localhost:8080/LoginMavenSpringMVC/admin/saveReferral" method="post">
<div class="row margin_div">
<div class="col-sm-3 col-md-2">
<label class="control-label">Select Category</label>
</div>
<div class="col-sm-5 col-md-4">
<f:select path="categoryOptions">
<f:options items="${list}"/>
</f:select>
</div>
</div>
</div>
controller class
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.java.Dao.services.RegisterDao;
import com.java.Dao.services.RegisterDaoImplementaion;
#Controller
#RequestMapping("/admin")
public class ReferralController {
#Autowired
RegisterDao registerDao;
#RequestMapping(value="/create", method=RequestMethod.POST)
public ModelAndView create(#ModelAttribute("create") Category create){
ModelAndView model =new ModelAndView("referralPage");
System.out.println("Referral Controller.");
System.out.println( create.getCategoryName());
if((StringUtils.hasText(create.getId()))) {
registerDao.UpdateCategory(create);
} else {
registerDao.addCategory(create);
}
List<Category> list= registerDao.categoryList();
model.addObject("list", list);
return model;
}
#RequestMapping(value="/saveReferral", method=RequestMethod.POST)
public ModelAndView save(#ModelAttribute("saveReferral") Referrals referral){
ModelAndView model=new ModelAndView("referralPage");
return model;
}
}
Dao services
dao class...
package com.java.Dao.services;
import java.util.List;
import com.java.Package.Login.Category;
public interface RegisterDao {
public void addCategory(Category createCategory);
public void UpdateCategory(Category createCategory);
public List<Category> categoryList();
}
Dao Implementation
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;
import com.java.Package.Login.Category;
import com.mongodb.DBCollection;
#Repository
public class RegisterDaoImplementaion implements RegisterDao {
#Autowired
private MongoTemplate mongoTemplate;
public static final String Collection_Category="CategoryList";
public void addCategory(Category createCategory) {
// TODO Auto-generated method stub
createCategory.setId(UUID.randomUUID().toString());
System.out.println("Object in Repos::"+createCategory);
mongoTemplate.insert(createCategory, Collection_Category);
}
public void UpdateCategory(Category createCategory) {
// TODO Auto-generated method stub
mongoTemplate.insert(createCategory, Collection_Category);
}
#Override
public List<Category> categoryList() {
return mongoTemplate.findAll(Category.class, Collection_Category);
}
}
Class to map categoryOptions
public class Referrals {
private String categoryOptions;
public String getCategoryOptions() {
return categoryOptions;
}
public void setCategoryOptions(String categoryOptions) {
this.categoryOptions = categoryOptions;
}
}
and I am getting this error log
Servlet.service() for servlet [spring-dispatcher] in context with path [/LoginMavenSpringMVC] threw exception [An exception occurred processing JSP page /WEB-INF/views/referralPage.jsp at line 366
363: </div>
364: <div class="col-sm-5 col-md-4">
365:
366: <f:select path="categoryOptions">
367: <f:options items="${list}"/>
368: </f:select>
369: <!-- <select class="form-control input-sm" name="categoryOptions" >
Stacktrace:] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'categoryOptions' available as request attribute
Where I am getting wrong? I have tried solutions from different question but couldn't solve it.
You are missing adding Referrals object to model.
#RequestMapping(value="/saveReferral", method=RequestMethod.POST)
public ModelAndView save(#ModelAttribute("saveReferral") Referrals referral){
ModelAndView model=new ModelAndView("referralPage");
model.addAttribute("categoryOptions",new Referrals()); //or referral
return model;
}
Exception is occuring because of <f:select path="categoryOptions">,you have mentioned categoryOptions in path but no where you are returning to this jsp with categoryOptions.
Update : So this says whenever you are loading referral jsp, you have to load with categoryOptions bean
And in below lines list is added to model using model.addObject() but path variable categoryOptions is missing. So after the line model.addObject("list", list); add model.addAttribute("categoryOptions", new Referrals());
<f:select path="categoryOptions">
<f:options items="${list}"/>
</f:select>

Place the Index.html To Run

I am beginning to study AngularJS with Spring MVC and I wanted when I entered the system in the case http: // localhost: 8080 / he entered a home page that is called index.html, walked snooping on the Internet, most could not succeed in time to call the page.
This is my controller that just created to call the page as in the examples I've seen too.
package br.com.escconsultoria.standard.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
#RestController
#RequestMapping(value = "/")
public class IndexController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView getIndexPage() {
return new ModelAndView("/index");
}
}
Beauty of this fine examples simply doing: it returns index, worked over my could not for nothing there I saw talking about using Template: Thymeleaf only that I could not even now he does not think where's the page.
package br.com.escconsultoria.standard.configuration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"br.com.escconsultoria.standard.configuration",
"br.com.escconsultoria.standard.controller",
"br.com.escconsultoria.standard.repository",
"br.com.escconsultoria.standard.service",
"br.com.escconsultoria.imobiliario.controller",
"br.com.escconsultoria.imobiliario.repository",
"br.com.escconsultoria.imobiliario.service"})
public class AppConfiguration extends WebMvcConfigurerAdapter{
/*#Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/resources/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setOrder(1);
return resolver;
}*/
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/templates/");
viewResolver.setSuffix(".html");
viewResolver.setCache(false);
return viewResolver;
}
#Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(100000l);
return multipartResolver;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/app/**").addResourceLocations("/app/");
registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/templates/**").addResourceLocations("/templates/");
}
}
Does anyone have an idea how to implement it?
My index page is in the scr/main/resources/templates/index.html
Solution:
Good I managed to solve my problem and I am putting the solution here, first the first thing that kept me from work was the Controller noted with RestController and needed to be only Controller.
#Controller
#RequestMapping(value = "/")
public class IndexController {
#RequestMapping(method = RequestMethod.GET)
public String getIndexPage() {
return "index3";
}
}
And according to my App Configuration it looked like this.
package br.com.escconsultoria.standard.configuration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"br.com.escconsultoria.standard.configuration",
"br.com.escconsultoria.standard.controller",
"br.com.escconsultoria.standard.repository",
"br.com.escconsultoria.standard.service",
"br.com.escconsultoria.imobiliario.controller",
"br.com.escconsultoria.imobiliario.repository",
"br.com.escconsultoria.imobiliario.service"})
public class AppConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/templates/");
viewResolver.setSuffix(".html");
viewResolver.setCache(false);
return viewResolver;
}
#Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(100000l);
return multipartResolver;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/app/**").addResourceLocations("/app/");
registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/templates/**").addResourceLocations("/templates/");
}
}
Then I had a little problem in the index that I was trying to do more was because they were generating in Pingendo and he did not close the tag in the case of the target, input and some other was not close at hand and it worked. My Test HTML below.
<html>
<head>
<meta charset="utf-8"></meta>
<meta name="viewport" content="width=device-width, initial-scale=1"></meta>
<script type="text/javascript"
src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript"
src="http://netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link
href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"
rel="stylesheet" type="text/css"></link>
<link
href="http://pingendo.github.io/pingendo-bootstrap/themes/default/bootstrap.css"
rel="stylesheet" type="text/css"></link>
</head>
<body>
<div class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target="#navbar-ex-collapse">
<span class="sr-only">Toggle navigation</span><span
class="icon-bar"></span><span class="icon-bar"></span><span
class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><span>Brand</span></a>
</div>
<div class="collapse navbar-collapse" id="navbar-ex-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active">Home</li>
<li>Contacts</li>
</ul>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="col-sm-2">
<label for="inputEmail3" class="control-label">Email</label>
</div>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail3"
placeholder="Email"></input>
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<label for="inputPassword3" class="control-label">Password</label>
</div>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3"
placeholder="Password"></input>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label><input type="checkbox"> Remember me </input></label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>

Categories