Why my Spring boot application does not validate form - spring

I have a bit of a problem. So I'm trying to make a form validation. I enter incorrect data and it doesn't show any problems and saves user even it should not do that. If I don't select any country, it crashes becouse it gets null. Binding result method .getAllErrors() shows nothing. The question is why binding result doesn't get any errors and validating all the fields even if they are incorrect?
What I'm missing?
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.0.Final</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
#Entity
#Table(name="users")
public class User {
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "country_id", referencedColumnName = "id")
#NotBlank(message = "Country is mandatory")
#NotNull
private Country country;
#Column(name = "password")
#Pattern(regexp = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&-+=()])(?=\\\\S+$).{8,20}$",
message = "At least one digit, upper and lower case letters at least once, special character, 8 to 20 characters and no white spaces")
#NotBlank(message = "Password is mandatory")
private String password;
#Column(name = "first_name")
#Size(min = 2, max= 20, message = "Not less then 2")
#NotBlank(message = "First name is mandatory")
private String firstName;
#Column(name = "last_name")
#Size(min = 2, max= 20, message = "Not less then 2")
#NotBlank(message = "Last name is mandatory")
private String lastName;
#Column(name = "mail")
#Email(message = "Enter valid email")
#NotBlank(message = "Email is mandatory")
private String mail;
#Column(name = "phone")
#Pattern(regexp = "^(\\+\\d{1,2}\\s)?\\(?\\d{3}\\)?[\\s.-]\\d{3}[\\s.-]\\d{4}$",
message = "Enter valid phone like:\n123-456-7890\n(123) 456-7890\n123 456 7890\n123.456.7890\n+91 (123) 456-7890")
#NotBlank(message = "Phone is mandatory")
private String phone;
#Column(name = "last_login_date")
private String lastLoginDate;
#Column(name = "register_date")
private String registerDate;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(
name = "user_roles",
joinColumns = #JoinColumn(name = "users_id"),
inverseJoinColumns = #JoinColumn(name = "roles_id")
)
#NotNull
private Set<Roles> roles = new HashSet<>();
#Controller
public class LoginController {
#Autowired
private UserService userService;
#Autowired
CountryRepository countryRepo;
#Autowired
UserRepository userRepo;
#GetMapping("/login")
public String openLogin(Model theModel) {
User user = new User();
List<Country> countryList = new ArrayList<Country>();
countryList = countryRepo.findAll();
theModel.addAttribute("user", user);
theModel.addAttribute("country_list", countryList);
return "login";
}
#PostMapping("/register")
public String registerUser(#Valid #ModelAttribute User user,
HttpServletRequest request, BindingResult result) {
if(result.hasErrors()) {
return "login";
} else {
String userRole = request.getParameter("role_value");
String selectedCountry= request.getParameter("country_value");
userService.setUserCountry(selectedCountry);
userService.setUserRole(userRole);
userService.saveUserWithRole(user);
return "redirect:/";
}
}
}
#Service
public class UserService {
private String userCountry;
private String userRole;
#Autowired
private UserRepository userRepo;
#Autowired
private RoleRepository roleRepo;
#Autowired
private CountryRepository countryRepo;
public void saveUserWithRole(User user) {
Country userCountry = countryRepo.findById(getUserCountry(this.userCountry));
user.addCountry(userCountry);
Roles userRole = roleRepo.findUsingId(getUserRole(this.userRole));
user.addRole(userRole);
userRepo.save(user);
}
public void setUserCountry(String userCountry) {
this.userCountry = userCountry;
}
public Long getUserCountry(String userCountry) {
return Long.parseLong(userCountry);
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
public Long getUserRole(String userRole) {
return Long.parseLong(userRole);
}
}
<form th:action="#{/register}" th:object="${user}" id="register-form-user"
method="post" style="display: none">
<input type="text" id="firstName" th:field="*{firstName}" name="firstName" th:errorclass="is-invalid" placeholder="Your name">
<span th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}">Error</span>
<input type="text" id="last-name" th:field="*{lastName}" name="last-name" th:errorclass="is-invalid" placeholder="Your last name">
<span th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}">Error</span>
<input type="password" id="password" th:field="*{password}" name="password" th:errorclass="is-invalid" placeholder="Password">
<span th:if="${#fields.hasErrors('password')}" th:errors="*{password}">Error</span>
<input type="password" id="rep-password" name="rep-password" placeholder="Repeat password">
<input type="text" id="mail" th:field="*{mail}" name="mail" th:errorclass="is-invalid" placeholder="Mail">
<span th:if="${#fields.hasErrors('mail')}" th:errors="*{mail}">Error</span>
<input type="text" id="phone" th:field="*{phone}" name="phone" th:errorclass="is-invalid" placeholder="Phone">
<span th:if="${#fields.hasErrors('phone')}" th:errors="*{phone}">Error</span>
<select class="form-control" name="role_value" id="role-name">
<option th:value="0">Select role</option>
<!-- Role options -->
</select>
<span th:if="${#fields.hasErrors('roles')}" th:errors="*{roles}">Error</span>
<select class="form-control" name="country_value" id="country-name">
<option value="0">Select country</option>
<option th:each="country : ${country_list}" th:value="${country.id}" th:text="${country.countryName}"></option>
</select>
<span th:if="${#fields.hasErrors('country')}" th:errors="*{country}">Error</span>
<button class="btn-form">REGISTER</button>
</form>
Thanks for help.

The BindingResult needs to follow immediately after the model attribute you want to validate. Change:
#PostMapping("/register")
public String registerUser(#Valid #ModelAttribute User user,
HttpServletRequest request, BindingResult result)
to
#PostMapping("/register")
public String registerUser(#Valid #ModelAttribute User user,
BindingResult result, HttpServletRequest request)

Related

Thymeleaf template not connecting correctly to Java POJO

I am following the Spring in Action (5th Edition) by Craig Walls, and I am stuck trying to figure out why the form element my Thymeleaf view isn't passing on the correct data type to my pojo object.
Short of it is: When visiting localhost:8080/design, I should be able to select whatever checkboxes from a Thymeleaf html view which should then add those ingredients to a Taco object's List<Ingredient> ingredients parameter.
However, when I select the ingredients in the form and hit the submit button, I get the following error:
Fri Oct 28 14:07:37 EDT 2022
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='taco'. Error count: 1
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'taco' on field 'ingredients': rejected value [FLTO,GRBF,CHED,TMTO,SLSA]; codes [typeMismatch.taco.ingredients,typeMismatch.ingredients,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [taco.ingredients,ingredients]; arguments []; default message [ingredients]]; default message [Failed to convert property value of type 'java.lang.String[]' to required type 'java.util.List' for property 'ingredients'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'FLTO'; nested exception is java.lang.NumberFormatException: For input string: "FLTO"]
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:175)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:122)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:179)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:146)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1071)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)
Is someone able to offer some guidance on why this issue is happening?
Below is the my code that makes up the above workflow:
Dependencies
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.4</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>sia</groupId>
<artifactId>taco-cloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>taco-cloud</name>
<description>Taco Cloud Example Project from Spring In Action</description>
<properties>
<java.version>15</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>htmlunit-driver</artifactId>
<scope>test</scope>
</dependency>
<!-- Installed as a dependency as well as installed
on Eclipse IDE: https://projectlombok.org/setup/eclipse -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- For JavaBean Validation Annotations -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
<!-- For JDBCTemplate and embedded H2 database -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- For Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Database
I am using the H2 embedded database so the schema and accomponying data is loaded at runtime
src/main/resources/schema.sql
create table if not exists Ingredient (
id varchar(10) not null,
name varchar(25) not null,
INGREDIENT_TYPE ENUM('WRAP', 'PROTEIN', 'VEGGIES', 'CHEESE', 'SAUCE') NOT NULL
);
create table if not exists Taco (
id identity,
name varchar(50) not null,
createdAt timestamp not null
);
create table if not exists Taco_Ingredients (
taco bigint not null,
ingredient varchar(4) not null
);
alter table Ingredient
add constraint Ingredient_PK primary key (id);
alter table Taco_Ingredients
add foreign key (taco) references Taco(id);
alter table Taco_Ingredients
add foreign key (ingredient) references Ingredient(id);
create table if not exists Taco_Order (
id identity,
deliveryName varchar(50) not null,
deliveryStreet varchar(50) not null,
deliveryCity varchar(50) not null,
deliveryState varchar(2) not null,
deliveryZip varchar(10) not null,
ccNumber varchar(16) not null,
ccExpiration varchar(5) not null,
ccCVV varchar(3) not null,
placedAt timestamp not null
);
create table if not exists Taco_Order_Tacos (
tacoOrder bigint not null,
taco bigint not null
);
alter table Taco_Order_Tacos
add foreign key (tacoOrder) references Taco_Order(id);
alter table Taco_Order_Tacos
add foreign key (taco) references Taco(id);
src/main/resources/data.sql
delete from Taco_Order_Tacos;
delete from Taco_Ingredients;
delete from Taco;
delete from Taco_Order;
delete from Ingredient;
insert into Ingredient(id, name, INGREDIENT_TYPE )
values ('FLTO', 'Flour Tortilla', 'WRAP' );
insert into Ingredient(id, name, INGREDIENT_TYPE )
values('COTO','Corn Tortilla', 'WRAP');
insert into Ingredient(id, name, INGREDIENT_TYPE )
values('GRBF', 'Ground Beef', 'PROTEIN');
insert into Ingredient(id, name, INGREDIENT_TYPE )
values('CARN', 'Carnitas', 'PROTEIN');
insert into Ingredient(id, name, INGREDIENT_TYPE )
values('TMTO', 'Diced Tomatoes', 'VEGGIES');
insert into Ingredient(id, name, INGREDIENT_TYPE )
values('LETC', 'Lettuce', 'VEGGIES');
insert into Ingredient(id, name, INGREDIENT_TYPE )
values('CHED', 'Cheddar', 'CHEESE');
insert into Ingredient(id, name, INGREDIENT_TYPE )
values('JACK', 'Monterrey Jack', 'CHEESE');
insert into Ingredient(id, name, INGREDIENT_TYPE )
values('SLSA', 'Salsa', 'SAUCE');
insert into Ingredient(id, name, INGREDIENT_TYPE )
values('SRCR', 'Sour Cream', 'SAUCE');
POJOs
src/main/java/tacos/domain/Taco
#Data
#Entity
public class Taco {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String id;
private Date createdAt;
#NotNull
#Size(min=4, message="Name must be at least 4 characters long")
private String name;
#ManyToMany(targetEntity=Ingredient.class)
#Size(min=1, message="You must choose at least 1 ingredient")
private List<Ingredient> ingredients;
#PrePersist
void createdAt() {
this.createdAt = new Date();
}
}
src/main/java/tacos/domain/Ingredient
#Data
#RequiredArgsConstructor
#NoArgsConstructor(access=AccessLevel.PRIVATE, force=true)
#Entity
public class Ingredient {
#Id
private final String id;
private final String name;
#Enumerated(EnumType.STRING)
private final Type ingredientType;
public static enum Type {
WRAP, PROTEIN, VEGGIES, CHEESE, SAUCE
}
}
src/main/java/tacos/domain/Order
#Data
#Entity
#Table(name="Taco_Order")
public class Order implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private Date placedAt;
#NotBlank(message="Name is required")
private String name;
#NotBlank(message="Street is required")
private String street;
#NotBlank(message="City is required")
private String city;
#NotBlank(message="State is required")
private String state;
#NotBlank(message="Zip Code is required")
private String zip;
#CreditCardNumber(message="Not a valid credit card number")
private String ccNumber;
#Pattern(regexp="^(0[1-9]|1[0-2])([\\/])([1-9][0-9])$", message="Must be formatted MM/YY")
private String ccExpiration;
#Digits(integer=3, fraction=0, message="Invalid CVV")
private String ccCVV;
#ManyToMany(targetEntity=Taco.class)
private List<Taco> tacos = new ArrayList<>();
public void addTaco(Taco taco) {this.tacos.add(taco);}
#PrePersist
void placedAt() {this.placedAt = new Date();}
}
Controllers
src/main/java/tacos/controllers/DesignTacoController
#Slf4j
#Controller
#RequestMapping("/design")
#SessionAttributes("order")
public class DesignTacoController {
private final IngredientRepository ingredientRepo;
private TacoRepository tacoRepo;
#Autowired
public DesignTacoController(IngredientRepository ingredientRepo, TacoRepository tacoRepo) {
this.ingredientRepo = ingredientRepo;
this.tacoRepo = tacoRepo;
};
#ModelAttribute(name = "order")
public Order order() {
return new Order();
}
#ModelAttribute(name = "taco")
public Taco taco() {
return new Taco();
}
#GetMapping
public String showDesignForm(Model model) {
List<Ingredient> ingredients = new ArrayList<>();
ingredientRepo.findAll().forEach(i -> ingredients.add(i));
log.info(ingredients.toString());
Type[] types = Ingredient.Type.values();
for (Type type : types) {
model.addAttribute(type.toString().toLowerCase(),
filterByType(ingredients, type));
}
model.addAttribute("taco", new Taco());
return "design";
}
#PostMapping
public String processDesign(
#Valid Taco design,
#ModelAttribute Order order,
Errors errors) {
log.info("design: " + design);
log.info("order: " + order);
log.warn("errors: " + errors);
if(errors.hasErrors()) return "design";
Taco savedTaco = tacoRepo.save(design);
order.addTaco(savedTaco);
return "redirect:orders/current";
}
private List<Ingredient> filterByType(
List<Ingredient> ingredients,
Type type) {
return ingredients
.stream()
.filter(x -> x.getIngredientType().equals(type))
.collect(Collectors.toList());
}
}
src/main/java/tacos/controllers/OrderController
#Slf4j
#Controller
#RequestMapping("/orders")
#SessionAttributes("order")
public class OrderController {
private OrderRepository orderRepo;
public OrderController(OrderRepository orderRepo) {this.orderRepo = orderRepo;}
#GetMapping("/current")
public String orderForm(Model model) {
log.info(model.toString());
return "orderForm";
}
#PostMapping
public String processOrder(#Valid Order order, SessionStatus sessionStatus, Errors error) {
if(error.hasErrors()) return "orderForm";
orderRepo.save(order);
sessionStatus.setComplete();
return "redirect:/";
}
}
Views
src/main/resources/templates/design.html
<body>
<h1>Design Your Taco</h1>
<img th:src="#{/images/TacoCloud.jpeg}" />
<form method="POST" th:object="${taco}">
<div class="grid">
<div class="ingredient-group" id="wraps">
<h3>Design Your Wrap:</h3>
<div th:each="ingredient : ${wrap}">
<!-- <input name="ingredients" type="checkbox" th:value="${ingredient.id}" /> -->
<!-- <input name="ingredients" type="checkbox" th:value="${ingredient.getId()}" /> -->
<input name="ingredients" type="checkbox" th:value="${ingredient.getId()}" th:field="*{ingredients}" />
<span th:text="${ingredient.getName()}">INGREDIENT</span>
<br>
</div>
</div>
<div class="ingredient-group" id="proteins">
<h3>Pick Your Protein:</h3>
<div th:each="ingredient : ${protein}">
<!-- <input name="ingredients" type="checkbox" th:value="${ingredient.id}" /> -->
<!-- <input name="ingredients" type="checkbox" th:value="${ingredient.getId()}" /> -->
<input name="ingredients" type="checkbox" th:value="${ingredient.getId()}" th:field="*{ingredients}" />
<span th:text="${ingredient.getName()}">INGREDIENT</span>
<br>
</div>
</div>
<div class="ingredient-group" id="cheeses">
<h3>Pick Your Cheese:</h3>
<div th:each="ingredient : ${cheese}">
<!-- <input name="ingredients" type="checkbox" th:value="${ingredient.id}" /> -->
<!-- <input name="ingredients" type="checkbox" th:value="${ingredient.getId()}" /> -->
<input name="ingredients" type="checkbox" th:value="${ingredient.getId()}" th:field="*{ingredients}" />
<span th:text="${ingredient.getName()}">INGREDIENT</span>
<br>
</div>
</div>
<div class="ingredient-group" id="veggies">
<h3>Pick Your Veggies:</h3>
<div th:each="ingredient : ${veggies}">
<!-- <input name="ingredients" type="checkbox" th:value="${ingredient.id}" /> -->
<!-- <input name="ingredients" type="checkbox" th:value="${ingredient.getId()}" /> -->
<input name="ingredients" type="checkbox" th:value="${ingredient.getId()}" th:field="*{ingredients}" />
<span th:text="${ingredient.getName()}">INGREDIENT</span>
<br>
</div>
</div>
<div class="ingredient-group" id="sauces">
<h3>Pick Your Sauces:</h3>
<div th:each="ingredient : ${sauce}">
<!-- <input name="ingredients" type="checkbox" th:value="${ingredient.id}" /> -->
<!-- <input name="ingredients" type="checkbox" th:value="${ingredient.getId()}" /> -->
<input name="ingredients" type="checkbox" th:value="${ingredient.getId()}" th:field="*{ingredients}" />
<span th:text="${ingredient.getName()}">INGREDIENT</span>
<br>
</div>
</div>
</div>
<div>
<h3>Name Your Taco Creation:</h3>
<input type="text" th:field="*{name}" /> <br>
<button>Submit Your Taco</button>
</div>
</form>
</body>
src/main/resources/templates/orderForm.html
<body>
<form method="POST" th:action="#{/orders}" th:object="${order}">
<h1>Order Your Taco Creations!</h1>
<img th:src="#{/images/TacoCloud.jpeg}" /> <a th:href="#{/design}"
id="another"> Design Another Taco</a> <br>
<div th:if="${#fields.hasErrors()}">
<span class="validationError">Please correct the problems below and resubmit</span>
</div>
<h3>Deliver my taco masterpieces to ...</h3>
<label for="name">Name: </label> <input type="text" th:field="*{name}" />
<span class="validationError" th:if="${#fields.hasErrors('name')}" th:errors="*{name}"> Name Can't be Empty </span>
<br>
<label for="street"> Street Address: </label>
<input type="text" th:field="*{street}" />
<span class="validationError" th:if="${#fields.hasErrors('street')}" th:errors="*{street}"> Street Can't be Empty </span>
<br>
<label for="city"> City: </label>
<input type="text" th:field="*{city}" />
<span class="validationError" th:if="${#fields.hasErrors('city')}" th:errors="*{city}"> City Can't be Empty </span>
<br>
<label for="state"> State:</label>
<input type="text" th:field="*{state}" />
<span class="validationError" th:if="${#fields.hasErrors('state')}" th:errors="*{state}"> State Can't be Empty </span>
<br>
<label for="zip"> Zip Code: </label>
<input type="text" th:field="*{zip}" />
<span class="validationError" th:if="${#fields.hasErrors('zip')}" th:errors="*{zip}"> Zip Code Can't be Empty </span>
<br>
<h3>Here's How I'll Pay ...</h3>
<label for="ccNumber"> Credit Card #: </label>
<input type="text" th:field="*{ccNumber}" />
<span class="validationError" th:if="${#fields.hasErrors('ccNumber')}" th:errors="*{ccNumber}"> CC Number Error </span>
<br>
<label for="ccExpiration"> Expiration: </label>
<input type="text" th:field="*{ccExpiration}" />
<span class="validationError" th:if="${#fields.hasErrors('ccExpiration')}" th:errors="*{ccExpiration}"> CC Expiration Date Invalid </span>
<br>
<label for="ccCVV">CVV: </label>
<input type="text" th:field="*{ccCVV}" />
<span class="validationError" th:if="${#fields.hasErrors('ccCVV')}" th:errors="*{ccCVV}"> CVV Invalid </span>
<br>
<input type="submit" value="Submit Order" />
</form>
</body>
I have tried changing the schema for my sql file but this didn't work.

springMVC 5.1.6 validation not working (BindingResult errors are 0 ?)

I am facing an issue with my "User" Object being Validated before being registered into a database
Used Technologies :
- Spring Web MVC with Hibernate Validator
- Spring Data (JDBC)
- Maven
Here is a snippet from my Controller Code :
#RequestMapping(method = RequestMethod.POST,params = "add")
public ModelAndView add(#Valid #ModelAttribute("user") User user, BindingResult result) throws Exception {
if (!result.hasErrors()) { // ERRORS NEVER HAPPEN ??
userDao3.insertUser(user);
}
return returnHome();
}
my User Validation is as follows :
#Size(min = 3, max = 20, message = "{required.name}")
String name;
#Min(value = 25, message = "{min.age}")
int age;
#Min(value = 2000, message = "{invalid.salary}")
float salary;
my jsp layout as follows :
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<div class="container">
<form:form method="post" action="${contextPath}/?add" modelAttribute="user">
<div class="row">
<div class="col-15">
<tags:message code="field.username"/>
</div>
<div class="col-50">
<form:input cssClass="field" path="name"/>
</div>
<div class="col-25">
<form:errors path="name"/>
</div>
</div>
<div class="row">
<div class="col-15">
<tags:message code="field.age"/>
</div>
<div class="col-50">
<form:input cssClass="field" path="age"/>
</div>
<div class="col-25">
<form:errors path="age"/>
</div>
</div>
<div class="row">
<div class="col-15">
<tags:message code="field.salary"/>
</div>
<div class="col-50">
<form:input cssClass="field" path="salary"/>
</div>
<div class="col-25">
<form:errors path="salary"/>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form:form>
my Spring mvc Configuration xml file :
<mvc:annotation-driven/>
<bean name="homeController" class="Controllers.HomeController">
<property name="userDao2" ref="userDao2"/>
<property name="userDao3" ref="userDao3"/>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>naming</value>
<value>ValidationMessages</value>
</list>
</property>
</bean>
and my pom's dependencies are :
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.5.Final</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
the issue is : that on debugging found that errors are always equal to 0 in the BindingResult Object.
Debugging results:
Please help me understand the issue.

sec:authorize always returning same view in browser for both isAuthenticated() and isAnonymous() in thymeleaf view

home Controller
package com.book.controller;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
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.bind.annotation.RequestParam;
import com.book.entity.User;
import com.book.security.entity.PasswordResetToken;
import com.book.security.entity.Role;
import com.book.security.entity.UserRole;
import com.book.security.impl.MailConstructor;
import com.book.security.impl.SecurityUtility;
import com.book.security.impl.UserSecurityService;
import com.book.security.repo.UserService;
#Controller
public class HomeController {
#Autowired
private JavaMailSender mailSender;
#Autowired
private MailConstructor mailConstructor;
#Autowired
private UserService userService;
#Autowired
private UserSecurityService userSecurityService;
#RequestMapping("/")
public String index() {
return "index";
}
#RequestMapping("/login")
public String login(Model model) {
model.addAttribute("classActiveLogin", true);
return "myAccount";
}
#RequestMapping("/forgetPassword")
public String forgetPassword(HttpServletRequest request, #ModelAttribute("email") String email, Model model) {
model.addAttribute("classActiveForgetPassword", true);
User user = userService.findByEmail(email);
if (user == null) {
model.addAttribute("emailNotExist", true);
return "myAccount";
}
String password = SecurityUtility.randomPassword();
String encryptedPassword = SecurityUtility.passwordEncoder().encode(password);
user.setPassword(encryptedPassword);
userService.save(user);
String token = UUID.randomUUID().toString();
userService.createPasswordResetTokenForUser(user, token);
String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
SimpleMailMessage emails = mailConstructor.constructResetTokenEmail(appUrl, request.getLocale(), token, user,
password);
mailSender.send(emails);
model.addAttribute("emailSent", "true");
return "myAccount";
}
#RequestMapping(value = "/newUser", method = RequestMethod.POST)
public String newUserPost(HttpServletRequest request, #ModelAttribute("email") String userEmail,
#ModelAttribute("username") String username, Model model) throws Exception {
model.addAttribute("classActiveNewAccount", true);
model.addAttribute("email", userEmail);
model.addAttribute("username", username);
if (userService.findByUsername(username) != null) {
model.addAttribute("usernameExists", true);
return "myAccount";
}
if (userService.findByEmail(userEmail) != null) {
model.addAttribute("emailExists", true);
return "myAccount";
}
User user = new User();
user.setUsername(username);
user.setEmail(userEmail);
String password = SecurityUtility.randomPassword();
String encryptedPassword = SecurityUtility.passwordEncoder().encode(password);
user.setPassword(encryptedPassword);
Role role = new Role();
role.setRoleId(1);
role.setName("ROLE_USER");
Set<UserRole> userRoles = new HashSet<>();
userRoles.add(new UserRole(user, role));
userService.createUser(user, userRoles);
String token = UUID.randomUUID().toString();
userService.createPasswordResetTokenForUser(user, token);
String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
SimpleMailMessage email = mailConstructor.constructResetTokenEmail(appUrl, request.getLocale(), token, user,
password);
mailSender.send(email);
model.addAttribute("emailSent", "true");
return "myAccount";
}
#RequestMapping("/newUser")
public String newUser(Locale locale, #RequestParam("token") String token, Model model) {
PasswordResetToken passToken = userService.getPasswordResetToken(token);
if (passToken == null) {
String message = "Invalid Token.";
model.addAttribute("message", message);
return "redirect:/badRequest";
} else {
User user = passToken.getUser();
String username = user.getUsername();
UserDetails userDetails = userSecurityService.loadUserByUsername(username);
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails,
userDetails.getPassword(), userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
model.addAttribute("user", user);
model.addAttribute("classActiveEdit", true);
return "myProfile";
}
}
}
Header.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head th:fragment="common-header">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Le's Bookstore</title>
<!-- Bootstrap core CSS -->
<link href="/css/bootstrap.min.css" rel="stylesheet" />
<link href="/css/non-responsive.css" rel="stylesheet" />
<!-- Custom styles for this template -->
<link href="/css/style.css" rel="stylesheet" />
<link rel="icon" href="/image/applie-touch-icon.png" />
</head>
<body>
<div th:fragment="navbar">
<div class="page-top"
style="width: 100%; height: 20px; background-color: #f46b42;"></div>
<!-- Static navbar -->
<nav class="navbar navbar-default navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">LE'S BOOKSTORE</a>
</div>
<div id="navbar">
<ul class="nav navbar-nav navbar-left">
<li class="dropdown"><a href="#" class="dropdown-toggle"
data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">BOOKS <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>Browse the bookshelf</li>
<li>Store hours & Directions</li>
<li>FAQ</li>
</ul></li>
<form class="navbar-form" role="search">
<div class="form-group">
<input type="text" name="keyword" class="form-control"
placeholder="Book title" />
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>SHOPPING CART</li>
<li sec:authorize="isAnonymous()"><a th:href="#{/login}">MY ACCOUNT</a></li>
<li sec:authorize="isAuthenticated()"><a th:href="#{/myProfile}">MY ACCOUNT</a></li>
<li sec:authorize="isAuthenticated()"><a th:href="#{/logout}">LOGOUT</a></li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
<!--/.container-fluid -->
</nav>
</div>
<div th:fragment="body-bottom-scripts">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</div>
</body>
</html>
SecurityConfig
package com.book.security.config;
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.method.configuration.EnableGlobalMethodSecurity;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import com.book.security.impl.SecurityUtility;
import com.book.security.impl.UserSecurityService;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserSecurityService userSecurityService;
private BCryptPasswordEncoder passwordEncoder() {
return SecurityUtility.passwordEncoder();
}
private static final String[] PUBLIC_MATCHERS = {
"/css/**",
"/js/**",
"/image/**",
"/",
"/newUser",
"/forgetPassword",
"/login",
"/fonts/**"
};
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(PUBLIC_MATCHERS).permitAll()
.anyRequest().authenticated()
.and()
.csrf().disable().cors().disable()
.formLogin().failureUrl("/login?error")
.defaultSuccessUrl("/")
.loginPage("/login").permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/?logout").deleteCookies("remember-me").permitAll()
.and()
.rememberMe();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.rakib.springboot</groupId>
<artifactId>book-shop</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>book-shop</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr-complete</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Problem:
sec:authorize returning true for both isAuthenticated() and isAnonymous() in thymeleaf view. i try to hide my_Profile, Log in when user log in and when log out then show only Log in.
BUT ITS not working ....
enter image description here
not working in both condition. please help me sir to continue the project.
SHOPPING CART
MY ACCOUNT
MY ACCOUNT
LOGOUT
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
When you upgrade your security version 5 and it will be fixed.
Try changing this
<li sec:authorize="isAnonymous()"><a th:href="#{/login}">MY ACCOUNT</a></li>
For this
<li sec:authorize="!isAuthenticated()"><a th:href="#{/login}">MY ACCOUNT</a></li>

Getting AJAX HTTP 500 in SpringMVC response

I am trying to get the list of users from Mongodb with ajax it works without ajax. I did this with MySQL and it worked so I don't understand what is wrong with my code.
I can send the request and go to the method and return the List<User>.
But when I put it in map can't get that map as a response in the success function.
My Console Output:
free.js:31 Uncaught TypeError: Cannot read property 'action' of null
at window.onmessage (free.js:31)
window.onmessage # free.js:31
jquery.min.js:2 POST http://localhost:8080/UserManagementMongoDB/list 500
send # jquery.min.js:2
ajax # jquery.min.js:2
load # submitedform:342
onload # submitedform:25
submitedform:355 Uncaught ReferenceError: response is not defined
at Object.error (submitedform:355)
at u (jquery.min.js:2)
at Object.fireWith [as rejectWith] (jquery.min.js:2)
at k (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
Here is my Controller method
#RequestMapping(value="/list", method=RequestMethod.POST)
public #ResponseBody Map<String,Object> getAll(User user) {
Map<String,Object> map = new HashMap<String,Object>();
List<User> list = mainPageService.getAllUsers();
if (list != null){
map.put("status","200");
map.put("message","Data found");
map.put("data", list);
}else{
map.put("status","404");
map.put("message","Data not found");
}
return map;
}
And my ajax load function
data = "";
load = function(){
$.ajax({
url:'list',
type:'POST',
success: function(response){
alert("Hello");
data = response.data;
$('.tr').remove();
for(i=0; i<response.data.length; i++){
$("#table").append("<tr class='tr'> <td> "+response.data[i].userName+" </td> <td> "+response.data[i].userSurname+" </td> <td> <a href='#' onclick= edit("+i+");> Edit </a> </td> </td> <td> <a href='#' onclick='delete_("+response.data[i].userId+");'> Delete </a> </td> </tr>");
}
},
error: function () {
alert(response);
}
});
Here is my dependencies
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>UserManagementMongoDB</groupId>
<artifactId>UserManagementMongoDB</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>UserManagementMongoDB Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Servlet Library -->
<!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<!-- Spring dependencies -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>${spring.data.commons.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${spring.data.mongodb.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.tanesha.recaptcha4j/recaptcha4j -->
<dependency>
<groupId>net.tanesha.recaptcha4j</groupId>
<artifactId>recaptcha4j</artifactId>
<version>0.0.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish/javax.json -->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.10</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.framework.version}</version>
</dependency>
</dependencies>
<!-- Properties for the dependencies -->
<properties>
<java-version>1.7</java-version>
<!-- Spring properties -->
<spring.framework.version>5.0.9.RELEASE</spring.framework.version>
<spring.data.commons.version>1.12.1.RELEASE</spring.data.commons.version>
<spring.data.mongodb.version>1.10.6.RELEASE</spring.data.mongodb.version>
<!-- Other properties -->
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<junit.version>4.12</junit.version>
<jstl.version>1.2</jstl.version>
</properties>
<build>
<finalName>ExampleWebApplication</finalName>
</build>
</project>
I am getting 500 right now I just can't get the response everything other than that works. I can send my parameters with ajax just can't receive the map resources
My model code:
public class User {
#Id
private String userId;
private String userName;
private String userSurname;
private String phoneNo;
public User(String userId,String userName,String userSurname,String phoneNo) {
setUserId(userId);
setUserName(userName);
setUserSurname(userSurname);
setPhoneNo(phoneNo);
}
public User() {
// TODO Auto-generated constructor stub
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserSurname() {
return userSurname;
}
public void setUserSurname(String userSurname) {
this.userSurname = userSurname;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
My Stacktrace:
ava.lang.Exception
at com.kaan.springmvc.controller.MainPageController.getAll(MainPageController.java:117)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:891)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Blockquote
Do you separate the front end and back end?
If yes, it might be different server or port number and violate CORS. Please help to update more information.
The second point, your method require User object, but i don't any thing relative to it from ajax request?

BindingResult always false Spring MVC

I'm trying to implement spring validation framework in my mvc application. My login page has user name and password which are mandatory. I defined them as not null and not empty in the model class. If they are left blank I expect spring to bind the errors to BindingResult object. I'm not sure where I'm doing it wrong.. the hasError() method of BindingResult always return false in my controller class.
Below is my login controller
public class LoginController {
#Autowired
private UserRoleService userRoleService;
#Autowired
private AuthenticationService authenticationService;
#RequestMapping(value = "/login", method=RequestMethod.GET)
public ModelAndView showLoginPage() {
System.out.println("coming into LoginController!!");
ModelAndView mav = new ModelAndView("login");
mav.addObject("userModel", new UserInfo());
return mav;
}
#RequestMapping(value = "/welcome", method=RequestMethod.POST)
public ModelAndView login(#Valid #ModelAttribute("userModel") UserInfo user, BindingResult bindingResult) {
System.out.println("authenticate username and password -- invoke LDAP!!");
System.out.println(user.getUsername() + user.getPassword());
String userId = user.getUsername();
String password = user.getPassword();
if(bindingResult.hasErrors())
{
return new ModelAndView("login");
}
if(authenticationService.athenticate(userId,password)) {
List<String> roles = userRoleService.searchRolesByUserId(userId);
for(String role : roles)
System.out.println("role is: "+role);
ModelAndView mav = new ModelAndView("welcome");
return mav;
}
else {
ModelAndView mav = new ModelAndView("login");
mav.addObject("loginFailed", "User Name or Password is incorrect");
return mav;
}
}
}
Below is my model class..
public class UserInfo{
#NotNull
#NotEmpty(message="User name cannot be empty")
private String username;
#NotNull
#NotEmpty(message="Password cannot be empty")
private String password;
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;
}
}
My spring xml has these entries...
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/"/>
<mvc:annotation-driven />
Below is my login jsp page..
<form:form class="form-signin" commandName="userModel" method="POST" action="welcome.do" id="loginform">
<h2 class="form-signin-heading">Welcome to BPAY</h2>
<div style="color: red">${loginFailed}</div>
<label for="inputEmail" class="sr-only">Username</label>
<form:input type="text" path="username" id="usernameId" class="form-control"
placeholder="Username" required autofocus/>
<form:errors path="username" cssClass="error"/>
<label for="inputPassword" class="sr-only">Password</label>
<form:input type="password" id="passwordId" path="password" class="form-control"
placeholder="Password" required/>
<form:errors path="password" cssClass="error"/>
<button class="btn btn-lg btn-primary btn-block" type="submit" value="OK">Login</button>
</form:form>
The bindingResult.hasErrors() method in my controller class always return false. Can you please let me know, what am I missing?
pom has required entries as below..
<!-- Validation framework -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.5.Final</version>
</dependency>
You should use this dependency
`<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.10.Final</version>
</dependency>`
And remove the dependency javax.validation
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
Try in pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
Try using spring-boot-starter-validation:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Resources