Error message not showing in view page in JSR303, using Bootstrap in jsp - spring

I am adding server side validation in my project. and somehow the error message from controller is not reaching view page.
I am using :
spring
jpa,
JSR303 for validation, and
bootstrap
Below is code for add.jsp
<!DOCTYPE html>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<style>
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
<title>Add User</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="col-md-4">
<h2>Add User</h2>
<form:form action="user" method="post" role="form"
commandName="user">
<form:errors path="*" cssClass="errorblock" />
<div class="form-group ">
<label for="user">User Name:</label>
<form:input type="text" class="form-control" path="name"
id="name" placeholder="Enter User Name" required="requried"/>
</div>
<div class="form-group">
<label for="email">Email Address:</label>
<form:input type="email" path="emailAddress" class="form-control"
id="email" placeholder="Enter Email Address" required="requried"/>
</div>
<div class="form-group">
<label for="role">Role:</label>
<form:select path="role" class="form-control" id="role" required="requried">
<option disabled selected></option>
<c:forEach var="role" items="${roles}">
<option value="${role.value}">${role.name}</option>
</c:forEach>
</form:select>
</div>
<button type="submit" value="Submit" name="add"
class="btn btn-info active">Submit</button>
Back
</form:form>
</div>
<div class="col-md-4">
<div class="col-md-4"></div>
</div>
</div>
</div>
</div>
</body>
</html>
Below is code for Controller.java
#RequestMapping(value = "/user", params = "add", method = RequestMethod.GET)
public String getAddUser(Model model) {
ArrayList<Role> roles = new ArrayList<Role>();
// From user Add only admin and head of department can be added
roles.add(Role.ADMIN);
roles.add(Role.HEAD_OF_DEPARTMENT);
model.addAttribute("roles", roles);
model.addAttribute("user", new User());
return "user/add";
}
#RequestMapping(value = "/user", params = "add", method = RequestMethod.POST)
public String postAddUser(#ModelAttribute #Valid User user,
BindingResult result) {
if (result.hasErrors()) {
return "redirect:user?add";
} else {
System.out.println("Inside postAddUser");
user = userRepository.save(user);
return "redirect:user?id=" + user.getId();
}
}
Below is code for User.java
package in.ac.jmi.entities;
import in.ac.jmi.constants.Role;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table(name="USER")
public class User extends UrlEntity{
#Column(name="NAME", nullable = false)
#NotEmpty(message="Name can not be empty")
private String name;
#Column(name="ROLE", nullable = false)
#NotNull(message="Role can not be left blank")
private Role role;
#Column(name = "EMAIL_ADDRESS", nullable = false)
#NotEmpty(message="email address can not be empty")
private String emailAddress;
public User(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
#Override
public String toString() {
return "\nUser [name=" + name + ", role=" + role + ", emailAddress="
+ emailAddress + "]";
}
}

The reason is you are using return "redirect:user?add";, which cleared the error messages in model, try change it to return "user?add";

Related

use Thymleaf and spring met org.springframework.web.method.annotation.MethodArgumentTypeMismatchException

I am running a springboot demo,integrated with Thymleaf.But it keep throwing the following exeption:
WARN 25302 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved
[org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:
Failed to convert value of type 'java.lang.String' to required type
'java.lang.Long'; nested exception is java.lang.NumberFormatException:
For input string: "form.html"]**
controller:
#RestController
#RequestMapping("/users")
public class UserController {
#Autowired
private UserRepository userRepository;
private List<User> getUserlist() {
return userRepository.listUser();
}
#GetMapping
public ModelAndView list(Model model) {
model.addAttribute("userList", getUserlist());
model.addAttribute("title", "user management");
return new ModelAndView("users/list", "userModel", model);
}
#GetMapping("/form")
public ModelAndView createForm(Model model) {
User user=new User();
user=userRepository.saveOrUpateUser(user);
model.addAttribute("user", user);
model.addAttribute("title", "create user");
return new ModelAndView("users/form", "userModel", model);
}
list.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title th:text="${userModel.title}">welcome</title>
</head>
<body>
<div th:replace="~{fragments/header :: header}">...</div>
<h3 th:text="${userModel.title}">Welcome to baidu.com</h3>
<div>
create user
</div>
<table border="1">
<thead>
<tr>
<td>ID</td>
<td>Age</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<tr th:if="${userModel.userList.size()} eq 0">
<td colspan="3">no user info!!</td>
</tr>
<tr th:each="user : ${userModel.userList}">
<td th:text="${user.id}">1</td>
<td th:text="${user.age}">11</td>
<td><a href="view.html" th:href="#{'/users/' + ${user.id}}"
th:text="${user.name}">waylau</a></td>
</tr>
</tbody>
</table>
<div th:replace="~{fragments/footer :: footer}">...</div>
</body>
</html>
form.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title th:text="${userModel.title}">users : View</title>
</head>s
<body>
<div th:replace="~{fragments/header :: header}">...</div>
<h3 th:text="${userModel.title}">Welcome to baidu.com</h3>
<div>
back to home
</div>
<form action="/users" method="POST" th:object="${userModel.user}">
<input type="hidden" name="id" th:value="*{id}">
名称:<br>
<input type="text" name="name" th:value="*{name}">
<br>
年龄:<br>
<input type="text" name="age" th:value="*{age}">
<input type="submit" value="提交">
</form>
<div th:replace="~{fragments/footer :: footer}">...</div>
</body>
</html>
User.java
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement // mediatype 转为xml
public class User {
private long id; // 用户的唯一标识
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
....getter and setter
}
on the home page,everything goes fine,except the create user anchor which should return a form to fill.
any idea?

Sending object from thymeleaf template to Rest Controller returns "Unsupported Media Type"

I'm trying to POST some object fields to a RestController using thymeleaf.
But the result of the post returns what looks like a parsing error :
There was an unexpected error (type=Unsupported Media Type, status=415). Content type
'application/x-www-form-urlencoded;charset=UTF-8' not supported
The index page sends two attributes to the controller which then calls the business service that builds the new object.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Simple Sidebar - Start Bootstrap Template</title>
<!-- Bootstrap core CSS -->
<link th:href="#{/index/vendor/bootstrap/css/bootstrap.min.css}"
rel="stylesheet">
<!-- Custom styles for this template -->
<link th:href="#{/index/css/simple-sidebar.css}" rel="stylesheet">
</head>
<body>
<!-- Page Content -->
<div id="page-content-wrapper">
<div class="container-fluid">
<form action="#" th:action="#{/accounts}" th:object="${account}" method="post" enctype="application/json">
<div class="form-row">
<div class="form-group col-md-4 ">
<label for="inputState">Departement</label>
<input type="text" th:field="*{owner}" class="form-control" placeholder="Type in the department ..." />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4 ">
<label for="inputState">Budget</label>
<input type="number" step="0.01" th:field="*{budget}" class="form-control" placeholder="Type in Budget ..." />
</div>
</div>
<button class="btn btn-primary" type="submit">Enregistrer</button>
</form>
</div>
</div>
<!-- /#page-content-wrapper -->
</body>
</html>
This is the Rest Controller :
#RestController
public class AccountController {
#Autowired
private AccountService accountService;
#RequestMapping(value="/accounts", method=RequestMethod.POST)
public void addAccount(#RequestBody Account account ) {
accountService.addAccount(account);
}
}
Account is a simple POJO :
public class Account {
private String id;
private String owner;
private double budget;
private double budgetInvest;
private double budgetFonction;
public Account() {
}
public Account(String id,String owner, double budget, double budgetInvest, double budgetFonction
) {
super();
this.id = id;
this.owner=owner;
this.budget = budget;
this.budgetInvest = budgetInvest;
this.budgetFonction = budgetFonction;
}
public Account (String owner, double budget) {
this.owner = owner;
this.budget=budget;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getBudget() {
return budget;
}
public void setBudget(double budget) {
this.budget = budget;
}
public double getBudgetInvest() {
return budgetInvest;
}
public void setBudgetInvest(double budgetInvest) {
this.budgetInvest = budgetInvest;
}
public double getBudgetFonction() {
return budgetFonction;
}
public void setBudgetFonction(double budgetFonction) {
this.budgetFonction = budgetFonction;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
And the add method simply adds the object to a list of objects.
What am i doing wrong here ?
I think problem in you controller. First it won't be #RestController. It will be #Controller. Second it won't be #RequestBody. It will be #ModelAttribute.So write your controller like
#Controller
public class AccountController {
#Autowired
private AccountService accountService;
#RequestMapping(value="/accounts", method=RequestMethod.POST)
public void addAccount(#ModelAttribute("account") Account account ) {
System.out.ptintln("Checking");
accountService.addAccount(account);
}
The most relevant to the discussion of REST, the #RestController annota- tion tells Spring that all handler methods in the controller should have their return value written directly to the body of the response, rather than being carried in the model to a view for rendering. This line from book spring in action. So here you should use #Controller annotation.
You can use restcontroller but u must using ajax post for run "/account"
Cmiiw

Spring Boot Spring Security Login Redirection Issues

I implemented the Spring Boot Spring Security for handling authentication.
But as soon as I implemented it I keep getting re-directed to the webjars js instead of the welcome page. Here is my code, please suggest what could be the problem.
header.jspf
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fm"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Life Hacking Tech</title>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="/css/holdings.css"/>
</head>
<body>
login.jsp
<%# include file="common/header.jspf" %>
<%# include file="common/navigation.jspf" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<div class="container">
<form method="POST" action="${contextPath}/login" class="form-signin">
<h2 class="form-heading">Log in</h2>
<div class="form-group ${error != null ? 'has-error' : ''}">
<input name="username" type="text" class="form-control" placeholder="Username" autofocus="autofocus"/>
<input name="password" type="password" class="form-control" placeholder="Password"/>
<span>${message}</span>
<span>${error}</span>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<button class="btn btn-lg btn-primary btn-block" type="submit">Log In</button>
<h4 class="text-center">Create an account</h4>
</div>
</form>
</div>
<%# include file="common/footer.jspf" %>
LoginController.java
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
if (error != null)
model.addAttribute("error", "Your username and password is invalid.");
if (logout != null)
model.addAttribute("message", "You have been logged out successfully.");
return "loginPost";
}
#RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
public String showPage(ModelMap model) {
model.addAttribute("uname", getLoggedInUserName());
return "welcome";
}
SecurityConfiguration.java
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Autowired
private UserDetailsService userDetailsService;
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/registration").permitAll().anyRequest().authenticated()
.antMatchers("/css/**", "/login").permitAll()
.antMatchers("/","/*todo*/**").authenticated()
.antMatchers("/*holding*/**").authenticated()
.and().formLogin()./*successHandler(authSuccessHandler()).*/loginPage("/login").permitAll()
.and().logout().permitAll()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.and().exceptionHandling()
.accessDeniedPage("/access-denied");
}
#Bean
public AuthenticationSuccessHandler authSuccessHandler(){
return new SimpleUrlAuthenticationSuccessHandler();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
}
After a successful login I get re-directed to the scripts in footer.jsp
footer.jspf
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="webjars/bootstrap-datepicker/1.0.1/js/bootstrap-datepicker.js"></script>
<script>
$('#targetDate').datepicker({
})
</script>
<script>
$('.nav li').click(function(e) {
$('.nav li.active').removeClass('active');
var $this = $(this);
if (!$this.hasClass('active')) {
$this.addClass('active');
}
});
</script>
</body>
</html>
I encountered the same issue. Adding
.antMatchers("webjars/**").permitAll()
to the SecurityConfiguration did the trick.

HTTP Status 400 - Bad Request issue

I create simple Spring app.I have two views(forma,confirmation),model(User) and Spring Bean-Controller(Main_Controller).When I'm on the adress http://localhost:8080/Path/forma.htm and fill all forma fields and submit forma glassfish say HTTP Status 400 - Bad Request.Why?To work well should I see a confirmation page with client entry.
Main_Controller
package kontroleri;
#RequestMapping(value = "/forma",method = RequestMethod.GET)
public String pozivanjeForme(Model model)
{
model.addAttribute("user",new User());
return "forma";
}
#RequestMapping(value="/forma",method= RequestMethod.POST)
public String confirm(#ModelAttribute("user")User user,ModelMap model)
{
model.addAttribute("first_name",user.getFirst_name());
model.addAttribute("last_name",user.getLast_name());
model.addAttribute("date_of_birth",user.getDate_of_birth());
model.addAttribute("pid",user.getPid());
model.addAttribute("email",user.getEmail());
model.addAttribute("country",user.getCountry());
model.addAttribute("city",user.getCity());
model.addAttribute("postal",user.getPostal());
return "confirmation";
}
}
User
package model;
private String first_name;
private String last_name;
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate date_of_birth;
private String pid;
private String email;
private String country;
private String city;
private String postal;
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getCity() {
return city;
}
public String getCountry() {
return country;
}
public LocalDate getDate_of_birth() {
return date_of_birth;
}
public String getEmail() {
return email;
}
public String getFirst_name() {
return first_name;
}
public String getLast_name() {
return last_name;
}
public String getPid() {
return pid;
}
public String getPostal() {
return postal;
}
public void setCountry(String country) {
this.country = country;
}
public void setCity(String city) {
this.city = city;
}
public void setDate_of_birth(LocalDate date_of_birth) {
this.date_of_birth = date_of_birth;
}
public void setEmail(String email) {
this.email = email;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public void setPostal(String postal) {
this.postal = postal;
}
}
forma.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Forma page</title>
<style>
.field{
clear:both;
padding: 5px;
}
.field label{
text-align: left;
width: 100px;
float: left;
}
.error{
color: red;
}
</style>
</head>
<body>
<form:form action="forma.htm" method="post" commandName="user">
<div class="field">
<form:label path="first_name">First name</form:label>
<form:input path="first_name"/>
</div>
<div class="field">
<form:label path="last_name">Last name</form:label>
<form:input path="last_name"/>
</div>
<div class="field">
<form:label path="date_of_birth">Date of birth</form:label>
<form:input path="date_of_birth" type="date"/>
</div>
<div class="field">
<form:label path="pid">Personal ID</form:label>
<form:input path="pid"/>
</div>
<div class="field">
<form:label path="email">Email</form:label>
<form:input path="email"></form:input>
</div>
<div class="field">
<form:label path="country">Country</form:label>
<form:input path="country"></form:input>
</div>
<div class="field">
<form:label path="city">City</form:label>
<form:input path="city"/>
</div>
<div class="field">
<form:label path="postal">Postal code</form:label>
<form:input path="postal"></form:input>
</div>
<input type="submit" value="Submit">
</form:form>
</body>
</html>
confirmation.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Confirmation Page</title>
</head>
<body>
<h1>You entered following data:</h1>
<p>First name:${first_name}</p>
<p>Last name:${last_name}</p>
<p>Date of birth:${date_of_birth}</p>
<p>Personal ID:${pid}</p>
<p>Email:${email}</p>
<p>Country:${country}</p>
<p>City:${city}</p>
<p>Postal code: ${postal}</p>
</body>
</html>
dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
<prop key="forma.htm">Kontroler</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
<bean class="kontroleri.Main_Controller" id="Kontroler"/>
Please, define extra namespace in dispatcher-servlet.xml
<beans
...
xmlns:mvc="http://www.springframework.org/schema/mvc"
...
xsi:schemaLocation="
...
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
Add <mvc:annotation-driven/> to enable annotation-driven and support for formatting Date etc. fields.

Spring REST not returing anything

Here is my rest controller:
#RestController
public class LoginController {
#Autowired
private AppInstances appInstances;
#RequestMapping(method = RequestMethod.POST, value = "/signup")
public ResponseEntity<?> signup(#RequestBody SignupForm form) throws Exception
{
ResponseEntity<?> validate = FormFieldValidator.validate(form);
if(validate.getStatusCode() != HttpStatus.OK)
return validate;
else
{
return SignupService.signup(form, appInstances);
}
}
Here is HTML form
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form method="post">
<input type="text" name="userType" value="USER"/><br>
<input type="text" name="pwd" value="123456"/><br>
<input type="text" name="rpwd" value="123456"/><br>
<input type="text" name="name" value="manish kumar"/><br>
<input type="text" name="sex" value="Male"/><br>
<input type="text" name="bizzCategory" value="Restaurant"/><br>
<button>OK</button>
</form>
<script src="jquery.js"></script>
<script>
var formData = $("form").serializeArray();
var jsonData={};
$(formData).each(function(i,o){
console.log(o.name+"==="+o.value);
jsonData[o.name] = o.value;
});
$.ajax({
url:"http://localhost:8084/mobapp/signup",
type:"POST",
contentType:"application/json",
data:JSON.stringify(jsonData)
}).done(function(d){
alert(JSON.stringify(d));
}).error(function(e){
alert(e);
});
</script>
</body>
</html>
Here is what it shows in firebug. It has no response by the way.
OPTIONS signup 200 OK localhost:8084
I a using spring security 4.0.1.

Resources