Spring ModelAttribute nullPointerException - spring

these are my controllers:
#RequestMapping(value="/requestBooking", method = RequestMethod.GET)
#ModelAttribute("booking")
public ModelAndView requestBooking(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ModelAndView view = new ModelAndView("requestBooking");
OAuthAuthenticationToken token = (OAuthAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
if(token.getUserProfile().getAttributes().get("email").toString().matches(".*#nisum.com")==false){
SecurityContextHolder.clearContext();
return new ModelAndView("redirect:/j_spring_security_logout?redirectTo=/rejected");
}
VacationBooking booking=new VacationBooking();
String email=token.getUserProfile().getAttributes().get("email").toString();
User user=userImp.getUserByMail(email);
booking.setUser(user); //setting user
System.out.println(booking.getBookingId() + " - " + booking.getUser().getUserId());
view.addObject("booking", booking);
view.addObject("user", token.getUserProfile().getAttributes().get("email"));
return view;
}
#RequestMapping(value="/requestBooking/process", method=RequestMethod.POST)
public ModelAndView addBooking(#ModelAttribute("booking") VacationBooking booking , BindingResult result) {
/* val.validate(booking, result);*/
/* if(result.hasErrors()){
System.out.println("Error!!!!");
ModelAndView modelAndView = new ModelAndView("requestBooking");
return modelAndView;
}else{ */
SimpleMailMessage email2 = new SimpleMailMessage();
SimpleMailMessage emailPm = new SimpleMailMessage();
emailPm.setTo(booking.getUser().getMail()); //error here null value
email2.setTo(booking.getUser().getManager().getMail()); //error here, null value
email2.setSubject("Vacation Request");
emailPm.setSubject("Vacation Request");
emailPm.setText("<h3>Vacation Request<h3>\nThe employee has requested Vacation days between for leave. \n \n Please take action to approve or reject this request. \n \n To review, approve or reject the request, log into SaS, click Vacation Booking and click in Pending Approval link. \n \nNOTE: This is an Automated E-mail generated from the SaS mail process. Please do not reply to this E-mail. Vacation days Request Pending Approval");
email2.setText("<h3>Vacation Request<h3>\nYour vacation days request has been routed to your manager for approval. \n \nNote: If these dates should change, it is your responsibility to notify the appropriate people or withdraw your request in case you won't take those days.\n \nTo review, withdraw or modify your request, log into SaS, click Vacation Booking and check the current status or your Request. \n \nNOTE: This is an Automated E-mail generated from the SaS mail process. Please do not reply to this E-mail. Vacation days Request Routed for Approval");
mailSender.send(email2);
mailSender.send(emailPm);
System.out.println(booking.getFromDate());
bookingService.saveVacationBooking(booking);
ModelAndView modelAndView = new ModelAndView("myBookings");
String message = "the vacation booking was added!";
modelAndView.addObject("message", message);
return modelAndView;
}
and this is my view:
<!doctype html>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html class="no-js" lang="en">
<head>
<title>Vacation booking</title>
<link href="/vacation/resources/bootstrap-3.0.3/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<!--Booking Form-->
<body>
<jsp:include page="../../templates/PageHeader.jsp" />
<form:form method="POST" style="width:800px;" commandName="booking" action="${pageContext.request.contextPath}/requestBooking/process" class="form-horizontal">
<div class="container">
<div class="row">
<div clas="col-md-12"><h4>Vacation Booking Form</h4></div>
<hr>
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">From:</label>
<div class="col-sm-6">
<form:input type="date" path="fromDate" class="form-control"></form:input>
<form:hidden path="user.userId" class="form-control"/>
<form:hidden path="bookingId" class="form-control"/>
<!--<input type="date" class="form-control"/> -->
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">To:</label>
<div class="col-sm-6">
<form:input type="date" path="toDate" class="form-control"></form:input>
<!-- <input type="date" class="form-control"/> -->
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Comments:</label>
<div class="col-sm-6">
<form:textarea path="comments" rows="4" class="form-control" placeholder="Fill this field if you have any comments related to your request"/>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-sm-6">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>
</form:form>
<jsp:include page="../../templates/PageFooter.jsp" />
<script src="/vacation/resources/js/jquery-2.0.3.min.js" type="text/javascript"></script>
<script src="/vacation/resources/bootstrap-3.0.3/js/bootstrap.min.js" type="text/javascript"></script>
</body>
</html>
When I try to do booking.getUser().getMail() I get null. It is like my "booking" object is null in my post method. Any idea of how I can get my booking with the user object inside in my post controller, so I can call the getUser() method?

Related

Data not showing in my another Html table after submitting. I am using spring mvc with thymeleaf, what might be the reason

I added thymeleaf object and variable expressions in html and written #Getmapping and #postmapping methods and separate pojo class. after submitting the data using form.html file it going to another grades.html file but data is not showing what might be the issue.
controller program
#Controller
public class piperscontroller {
List<piedpiper> addGrades= new ArrayList<>();
#GetMapping("/")
public String submitForm(Model model){
model.addAttribute("grades",new piedpiper());
return "form";
}
#PostMapping("/handleSubmit")
public String grademeth(piedpiper grades){
addGrades.add(grades);
return "redirect:/grades";
}
#GetMapping("/grades")
public String finalButton(Model model){
model.addAttribute("grades",addGrades);
return "grades";
}
}
<!DOCTYPE HTML>
<html>
<head>
<title>Form</title>
<link th:href="#{/css/form.css} " rel="stylesheet">
</head>
<body>
<div class="topnav">
<a>Form</a>
<a>Grades</a>
</div>
<div class="container">
<h2> Grade Portal </h2>
<form method="post" th:object="${grades}" th:action="#{/handleSubmit}">
<input type="text" placeholder="Name" th:field="*{name}" >
<input type="text" placeholder="Score" th:field="*{score}">
<input type="text" placeholder="Subject" th:field="*{subject}">
<br><br>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>

View and controller data exchange

I'm using form tag to get information of title and content.
But I can't get any information from form tag.
It happens to me several time. I don't know what is the problem..
this is the controller code
#Slf4j
#Controller
#RequiredArgsConstructor
public class PostController {
private final PostRepository postRepository;
private final MemberService memberService;
#GetMapping("/board/upload")
public String moveToUploadPage(Model model) {
model.addAttribute("uploadPostForm", new UploadPostForm());
return "board/uploadForm";
}
#PostMapping("/board/upload")
public String updateBoard(#ModelAttribute UploadPostForm uploadPostForm, Authentication authentication, Model model) {
log.info("uploadPostForm.title = {}", uploadPostForm.getTitle());
Member member = findMember(authentication);
Post post = new Post(member, uploadPostForm.getTitle(), uploadPostForm.getContent());
postRepository.save(post);
return "/board/board";
}
}
this is html code
<!DOCTYPE html>
<html lang="kr" xmlns:th="http://www.thymeleaf.org">
<head th:insert="~{fragment/header :: header}">
<meta charset="utf-8">
</head>
<body>
<div th:replace="~{fragment/navbar :: nav}"></div>
<!-- Form Tag -->
<form th:action th:object="${uploadPostForm}" method="post" class="container-md">
<div class="m-3">
<label for="title" class="form-label">Title</label>
<input type="text" class="form-control" id="title" th:field="*{title}">
</div>
<div class="m-3">
<label for="content" class="form-label">Text Area</label>
<textarea class="form-control" id="content" rows="10" th:field="*{content}"></textarea>
</div>
<div class="container" style="text-align: right">
<span class="m-3" th:text="|writer: | + ${#authentication.getName()}"></span>
<button type="submit" class="btn btn-primary">upload</button>
</div>
</form>
</body>

Spring Security returns 403 on any request

I created two users with ADMIN and USER roles, but every time I try to login server return 403.
WebSecurityConfig:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin/**")
.access("hasAnyAuthority('ADMIN','USER')")
.and().formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username")
.passwordParameter("password")
.and().logout().logoutSuccessUrl("/login?logout")
.and().csrf().disable();
}
my UserService which maps my users from db:
#Transactional(readOnly = true)
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUserName(username);
org.springframework.security.core.userdetails.User.UserBuilder builder = null;
if (user != null) {
builder = org.springframework.security.core.userdetails.User.withUsername(username);
builder.disabled(!user.isEnabled());
builder.password(user.getPassword());
String[] authorities = user.getUserRole()
.stream().map(a -> a.getRole()).toArray(String[]::new);
builder.authorities(authorities);
} else {
throw new UsernameNotFoundException("User not found.");
}
return builder.build();
}
csrf is disabled. I also use hasAnyUthority* method so I don't need ROLE_ prefix.
I use spring security 5
My login.html
<head>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="resources/style.css"/>
</head>
<body>
<div class="container">
<header>
<h1>Login</h1>
</header>
<div class="alert alert-error" th:if="${error != null}">
<div>
<strong>Okay, Houston, we've had a problem here.</strong>
</div>
</div>
<div class="alert alert-error" th:if="${logout != null}">
<div>
<strong>Okay, Houston, you're logged out successfully .</strong>
</div>
</div>
<form class="form-horizontal" th:action="#{/login}" method="POST">
<fieldset>
<div class="control-group">
<label class="control-label">Login</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on">#</span>
<input id="loginField" name="username" class="span3" type="text"/>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">Password</label>
<div class="controls">
<input id="passwordField" name="password" class="span3" type="password"/>
</div>
</div>
<div class="form-actions">
<button id="loginButton" class="btn btn-primary" type="submit">Login</button>
</div>
</fieldset>
</form>
</div>
</body>
I did everything as in example projects but it still doesn't want to log me in.
I don't see that hasAnyAuthority(...) will work without "ROLE_", try .access("hasAnyRole('ADMIN','USER')") or .access("hasAnyRole('ROLE_ADMIN','ROLE_USER')").
Note that in String[] authorities = user.getUserRole().stream().map(a -> a.getRole()).toArray(String[]::new); you need in a.getRole() return with prefix ROLE_ or the same what you will have in hasAnyAuthority(...)
For example if your a.getRole() will return WHAT_EVER than hasAnyAuthority('WHAT_EVER) should work, but hasAnyRole('WHAT_EVER') will expect that a.getRole() returns ROLE_WHAT_EVER
Maybe it will help someone so i will unswer my question.
I couldn't login becouse when i launch my program, i add some new users with not encrypted password. But spring security decrypts it anyways so that is why i couldn't login and got 403 repsonse. All i needed is to encrypt password before adding it into database.

Spring MVC with Spring Boot: form tag error - equal symbol expected

I am trying to fill a form with values provided by the controller using tags in an app built with spring boot. But I get an error:
org.apache.jasper.JasperException: /WEB-INF/jsp/index.jsp (line: 52, column: 102) equal symbol expected
related part of index.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title><spring:message code="title.main" /></title>
</head>
<body>
<%#include file="include/navbar.jsp" %>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-sm-offset-0 col-md-8 col-md-offset-2 main">
<div class="panel panel-default">
<div class="panel-body">
<form:form method="get" id="indexForm" commandName="indexForm" action="<c:url value="index_search" />" role="form">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="city_out"><spring:message code="label.index.0" /></label>
<input:input type="text" class="form-control" id="city_out" path="city_out" />
</div>
<div class="form-group">
<label for="city_in"><spring:message code="label.index.1" /></label>
<form:input type="text" class="form-control" id="city_in" path="city_in" />
</div>
<div class="form-group">
<label for="company"><spring:message code="label.index.2" /></label>
<form:input type="text" class="form-control" id="company" path="company" />
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="date0"><spring:message code="label.index.3" /></label>
<form:input type="datetime" class="form-control" placeholder="dd.MM.yyyy [HH:mm]" id="date0" path="date0" />
</div>
<div class="form-group">
<label for="date1"><spring:message code="label.index.4" /></label>
<form:input type="text" class="form-control" placeholder="dd.MM.yyyy [HH:mm]" id="date1" path="date1" />
</div>
<div class="form-group" align="right">
<br />
<button type="submit" id="search_btn" data-loading-text="Loading..." class="btn btn-primary">Search</button>
</div>
</div>
</div>
</form:form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I have created a class to match form fields:
public class IndexForm {
private String city_out;
private String city_in;
private String company;
private String date0;
private String date1;
// getters, setters
}
And created a bean in main class (I hope so):
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application extends SpringBootServletInitializer {
#Bean
public static IndexForm indexForm() {
return new IndexForm();
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
Controller contains this method:
#RequestMapping("/index")
public String index(#RequestParam(value="e", required=false) List<Integer> errors, Map<String, Object> model) {
model.put("indexForm", new IndexForm());
if (errors != null)
model.put("errors", errors);
return "index";
}
I don't see any differences from examples I have seen, so I would be happy if someone pointed at my mistake.
some newbies do a mistake by making the field as required in order to validate the field is filled or not
e.g in normal html -
input type="text" name="name" required
in spring - form:input path="firstName" required .... here required will not work and so same type of error "equal symbol expected".
Oh. It seems, including jsp tags one in another doesn't work. So, I changed
action="<c:url value="index_search" />"
for
action="index_search"
and received my page without errors.

Issue with the Multiaction Controller in Spring

I am having a jsp page from which i have to pass the control to the next page.
And i am using Multiaction Controller for that but its giving me an error 404.
My JSP File is
<form id="form1" name="form1" method="post" action="registerSuccessControl.htm" commandName="register" >
<strong> <label> <label> <label>
<div align="center">Registeration</div>
</label></strong> <label></label>
<h1> </h1>
<p>
First Name <input type="text" name="textfield" accesskey="1"
tabindex="1" /> <label>
Last Name</label> <strong> <input type="text"
name="textfield3" />
</strong>
</p>
and this is my Controller
#RequestMapping("/registerSuccessControl.htm")
public ModelAndView registerSuccessControl(#ModelAttribute("register") Register register,BindingResult brResult,HttpServletRequest request,HttpServletResponse response) throws Exception {
System.out.println("RegisterSuccesssControl called");
//logger.debug("Registration Page Accessed at "+new Date());
System.out.println("I am In registerSuccess");
RegistrationValidator uValidator=new RegistrationValidator();
uValidator.validate(register,brResult);
HashMap<String, BindingResult> resultMap = new HashMap<String, BindingResult>();
if(brResult.hasErrors()){
resultMap.put("errors", errors);
return new ModelAndView("Register",resultMap);
}
else
return new ModelAndView("Firm");
}
I have other request handled in same controller and its working fine, but its not working for this link.

Resources