request.getAttribute("user") returning null object - java

I am trying to send object of User class to success.jsp. But getting null when trying to retrieve the object in success.jsp.
Code for UserController:
#Controller
#RequestMapping("/user")
public class UserController {
#PostMapping("/login")
public String Register(#Valid #ModelAttribute("user") User user,Errors errors,Model model) {
System.out.println("....done....");
if(errors.hasErrors()) {
return "user";
}
else {
RegisterService.show(user);
model.addAttribute("user",user);
return "redirect:/success";
}
}
}
Code for success.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page import="com.company.models.User" %>
<body>
Registration Successful
<%
User user=(User)request.getAttribute("user");
System.out.println("user="+user);
%>
</body>

you can use RedirectAttributes to send data to the page even if you are redirecting.
example:
#PostMapping("/login")
public String Register(#Valid #ModelAttribute("user") User user,Errors errors, RedirectAttributes attributes) {
System.out.println("....done....");
if(errors.hasErrors()) {
return "user";
}
else {
RegisterService.show(user);
attributes.addFlashAttribute("user", user);
return "redirect:/success";
}
}
read the documentation at: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/support/RedirectAttributes.html

It was because I was sending a redirect to success.jsp. So cannot pass data

Related

How to handle Dot Char in Url Mapping

I have a spring boot project but, I have some links from past and users are linking url on their websites and I cannot request client to change their urls. I am trying to navigate jsp link to React app. I have just found a solution but I got stuck.
Here is the link example: abc/Dashboard.jsp#/company/88
I am handling abc/Dashbord but I cannot handle abc/Dasboard.jsp to navigate a jsp page.
There is my handling endpoint;
#Controller
#RequestMapping("")
public class DashboardController {
#GetMapping("/Dashboard")
public String viewBooks() {
return "view-dashboard";
}
}
#GetMapping("/Dashboard.jsp")
public String viewBooks2() {
return "view-dashboard";
}
My Jsp Page
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>e-ŞİRKET</title>
</head>
<body>
</body>
</html>
<script>
const url = window.location.href.split('/')
if(url && url.length > 0) {
const id = url[url.length -1]
if(id) {
window.location.replace(window.location.origin + '?page=company&company=' + id)
}
}
</script>
It is working for abc/Dashboard#company/88 but;
how I can handle abc/Dashboard.jsp#/company/123. I am getting 404.

#RequestAttribute in springMVC is not binding Object of Entitiy class [duplicate]

This question already has an answer here:
Spring MVC Missing request attribute
(1 answer)
Closed 3 years ago.
I am new to spring,i am trying to develop basic java project with spring MVC using Annotations,i am trying to create an object of my Entity class(Information.java) in the controller using #RequestAttribute and send it to the view,my code as follows
My controller class
package org.practice.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView
#Controller()
public class HelloController
{
#RequestMapping("/hello")
public ModelAndView helloWorld(#RequestAttribute Information userInfo)
{
ModelAndView model = new ModelAndView("hello");
model.addObject("firstname", userInfo.getFirstName());
model.addObject("lastname", userInfo.getLastName());
return model;
}
#RequestMapping("/")
public ModelAndView homePage() {
ModelAndView model = new ModelAndView("index", "info", new Information());
return model;
}
}
My Entity class
package org.practice.spring;
public class Information {
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
private String lastName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>Hello,Please Enter Name</h3>
<form:form action="hello" modelAttribute="info">
First Name:<form:input path="firstName"/><br>
Last Name:<form:input path="lastName"/><br>
<input type="submit" value="Submit">
</form:form>
</body>
</html>
hello.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
Hello World
<h3>Hello ${firstName} ${lastName}</h3>
</body>
</html>
and Tomcat is giving me this
org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver logException
WARNING: Resolved [org.springframework.web.bind.ServletRequestBindingException: Missing request attribute 'userInfo' of type Information]
When i run the application browser is giving me this
HTTP Status 400 – Bad Request Type Status Report
Message Missing request attribute 'userInfo' of type Information
Description The server cannot or will not process the request due to
something that is perceived to be a client error (e.g., malformed
request syntax, invalid request message framing, or deceptive request
routing).
So far i dont have any syntax errors in my code,but my code is not working,i struck here for almost 2 days,did alot of googling but no luck,any help would be appreciated.
You can try this: #RequestAttribute(name="info").

Unable to make Spring MVC portlet with annotations make work

This is my controller
#Controller
#RequestMapping("VIEW")
public class SearchController {
private static final Log LOGGER = LogFactoryUtil.getLog(SearchController.class);
#RenderMapping
public String render() {
return "view";
}
#ActionMapping(params = "action = getResults")
public void getResults(#ModelAttribute("search") Search search, ActionRequest actionRequest, ActionResponse actionResponse) {
String keyword = search.getKeyword();
LOGGER.info("Keyword: " + keyword);
}
}
and my bean,
public class Search {
private String keyword;
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
}
and my view.jsp
<%#page import="org.springframework.web.bind.annotation.RequestMethod"%>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<portlet:defineObjects />
<portlet:actionURL var = "getResultsURL">
<portlet:param name="action" value="getResults"/>
</portlet:actionURL>
<form:form action="${getResultsURL}" commandName="search" method="POST">
<form:input path="keyword"/>
<input type="submit" value="Search">
</form:form>
and I am getting the following exception
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'search' available as request attribute
It is working fine if I place #ModelAttribute("search") as a parameter in render method, but I know it was absolutely wrong(correct me)
Any suggestions?
You get this exception when the JSP page is rendered, right?
Spring MVC tells you that it cannot find "search" attribute in the current request. And indeed, your controller doesn't put any instance of Search class to the Spring MVC model.
Two options:
Create getter for Search class instance with #ModelAttribute annotation:
#ModelAttribute
public Search getSearch() {
return new Search();
}
Put Search class instance to the Spring model in the render method:
#RenderMapping
public String render(Model model) {
model.addAttribute("search", new Search());
return "view";
}
This way the form tag will find the model under the given command name.

Show fields in jsp based on user roles(without using spring security)

I have a tabs.jsp which has links to other pages. When an admin logs in he must be given 2 extra links to add users and roles. while authenticating im able to validate if user is admin or not. on validation im returning control to a user display page if user exists if not redirecting back to login page. how do i achieve this extra 2 links if user is admin?
My controller
#RequestMapping(value = "auth", method = RequestMethod.POST)
public ModelAndView printStringLogin(
#ModelAttribute("USERS") Users userAuthentication,
HttpSession httpSession, ModelMap model) {
System.out.println(userAuthentication.getUsers_email());
System.out.println(userAuthentication.getUsers_password());
UserAuthentication userAuthentication2 = new UserAuthentication();
boolean exists = false,admin = false;
try {
exists = userAuthentication2.doesUserExist(
userAuthentication.getUsers_email(),
userAuthentication.getUsers_password());
} catch (Exception e) {
e.printStackTrace();
}
if (exists == true) {
System.out.println("user present");
httpSession.setAttribute("id", userAuthentication.getUsers_email());
System.out.println("Session Attribute: "
+ httpSession.getAttribute("id"));
return new ModelAndView("redirect:employee");
} else {
System.out.println("user not present");
return new ModelAndView("loginpage");
}
}
user authentication
public class UserAuthentication {
public boolean doesUserExist(String uname, String passwrd) throws Exception {
GetSession ses = new GetSession();
Session session = ses.retSession();
String query = "from Users as u where u.users_email = :sUname and u.users_password = :sPass";
List list = session.createQuery(query).setString("sUname", uname)
.setString("sPass", passwrd).list();
Iterator iterator = list.iterator();
boolean userExists = false;
if (iterator.hasNext()) {
Users obj = (Users) iterator.next();
System.out.print(obj.getUsers_email() + "\t"
+ obj.getUsers_password() + "\n");
System.out.println(obj.getMyRoles());
System.out.println("Is Admin??? :" +obj.getMyRoles().toString().contains("Admin")); //gives if user is admin or not
System.out.println(obj.getUser_id());
userExists = true;
}
System.out.println(userExists);
return userExists;
}
}
Tabs.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<body>
<div id="tabs" style="background-color: #C8C8C8; font-family: fantasy;">
Employee Details
Departments
Designation
Logout
Users
Roles
</div>
</body>
</html>
users and Roles links must be displayed only if user is admin and this tabs.jsp is included in every page of the application.
Put the User object in HttpSession in Controller and check whether the logged in User is admin or not in jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<body>
<div id="tabs" style="background-color: #C8C8C8; font-family: fantasy;">
Employee Details
Departments
Designation
Logout
<c:if test=${sessionScope.user.isAdmin}>
Users
Roles
</c:if>
</div>
</body>
</html>

Multiple select, Collections and Spring 3 web MVC

I'm using a multiple select HTML form input to allow a user to pick a collection of Extensions from a list of all possible Extensions.
The Extension class is quite simple -
public class Extension {
private String number;
private String firstName;
private String lastName;
... getters and setters ...
#Override
public String toString() {
return new StringBuilder(number).append(" - ")
.append(firstName).append(" ").append(lastName)
.toString();
}
}
Here's my form object -
public class BusinessUnitForm {
private String name;
private Collection<Extension> extensions;
public Collection<Extension> getExtensions() {
return extensions;
}
public void setExtensions(Collection<Extension> extensions) {
this.extensions = extensions;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And the controller -
#Controller
#RequestMapping("/businessunit")
public class BusinessUnitController {
... extension service & getters/setters ...
#RequestMapping(method = RequestMethod.GET)
public ModelAndView showForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
Integer customerId = (Integer) request.getSession().getAttribute("customerId");
ModelAndView mav = new ModelAndView("bu");
// this is quite expensive...
Collection<Extension> allExtensions = extensionService.getAllExtensions(customerId);
BusinessUnitForm businessUnitForm = new BusinessUnitForm();
mav.addObject("allExtensions", allExtensions);
mav.addObject("businessUnitForm", businessUnitForm);
return mav;
}
#RequestMapping(value="/create", method = RequestMethod.POST)
public ModelAndView create(HttpServletRequest request, HttpServletResponse response, BusinessUnitForm businessUnitForm, BindingResult result) throws Exception {
// *** BREAKPOINT HERE *** to examine businessUnitForm
Integer tenantId = (Integer) request.getSession().getAttribute("tenantId");
// code to process submission
ModelAndView mav = new ModelAndView("bu");
return mav;
}
}
And finally the view -
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<html>
...
<form:form action="businessunit/create" method="POST" commandName="businessUnitForm" >
<form:label path="name"></form:label><form:input path="name" />
<form:select path="extensions" cssClass="multiselect">
<form:options items="${allExtensions}" itemValue="number" />
</form:select>
<input type="submit" value="Create" />
</form:form>
...
</html>
At the breakpoint shown above in the create controller method, businessUnitForm.extensions is null. businessUnitForm.name is bound correctly.
I've tried, perhaps misguidedly, making businessUnitForm.extensions a LazyList but this doesn't help.
If I change BusinessUnitForm.extensions to be a Collection of unspecified type, it is populated successfully with a LinkedHashSet of Strings, containing the values selected.
Maybe I'm expecting too much of Spring, but I was hoping it would be able to use the values from the select, and also the reference data in allExtensions to automagically create a Collection<Extension> for me on the businessUnitForm. I understand the role of CustomCollectionEditors, but was under the impression that this might not be required in Spring 3.
Can Spring 3 populate my Collection<Extension> on the BusinessUnitForm without me writing a custom collection editor ? Some kind of trick with the view, perhaps ?
Thanks in advance ...
Dan
You need to implement a custom converter that is able to convert the String from the request into an Extension object.
And then you must use Collection (or List, or Set) with generic type information.
See this answer for an example of an converter: Submit Spring Form using Ajax where Entity has Foreign Entities

Categories