handling session with spring mvc - spring

Actually i am setting the attributes which are getting from bean class in modelandveiw method and trying to get that attribute in other modelandveiw method method but getting null values in
rs.getAttribute("customerId")
. Please help me.
#RequestMapping(value ="/insert",method= RequestMethod.Post)
public ModelAndView inserData(#ModelAttribute SavingBean savingBean,HttpServletRequest rs) {
HttpSession session = rs.getSession();
if (savingBean != null)
SavingBean saving = persionalService.insertData(savingBean);
int a = saving.getCustomerId();
rs.setAttribute("customerId",a );
System.out.println(saving.getDisgnProf());
List<SavingBean> list = new ArrayList<SavingBean>();
list.add(saving);
return new ModelAndView("welcome","list", list);
}
#RequestMapping(value ="/insertdata",method= RequestMethod.Post)
public ModelAndView check (#ModelAttribute SavingBean savingBean,HttpServletRequest rs) {
System.out.println(savingBean.getFirstName());
HttpSession session = rs.getSession();
System.out.println("abhishek" + rs.getAttribute("customerId"));
return null ;
}

You're not putting or getting anything from the session in this code. You're putting and getting attributes from rs, and rs is the request, not the session.

Yes you are putting it in the request rs, put it in session instead and you vill se it

Related

SPRING MVC: Defined HttpSession in One Method is Not Available to Another Method

I am facing a problem regarding to the Httpsession that I implementing in the Spring MVC project.
First of all, after the user successfully login, I will take the Httpsession object in loginAuthentication controller and set attribute with the name and value I want. (Shown in following figure).
A.java controller file,
#RequestMapping(value="login-authentication", method = RequestMethod.POST)
public String authentication(#Valid #ModelAttribute("systemAccount") SystemAccount systemAccount,
BindingResult bindingResult, Model model, HttpServletRequest request){
if (bindingResult.hasErrors()) {
model.addAttribute(GenericConstant.MessageAttributeName.ERROR_MSG_NAME.toValue(), SystemMessage.SystemException.LOGIN_INCORRECT_USERNAME_PASSWORD.toValue());
model.addAttribute("systemAccount", new SystemAccount());
return "index";
}else {
if (systemAccountService.authenticate(systemAccount.getUsername(), systemAccount.getPassword()) != null &&
!"".equals(systemAccountService.authenticate(systemAccount.getUsername(), systemAccount.getPassword()))) {
SystemAccount dbSystemAccount = systemAccountService.authenticate(systemAccount.getUsername(), systemAccount.getPassword());
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ID.toValue(),dbSystemAccount.getAccountID());
//check account role
if(dbSystemAccount.getCounterStaff()!= null && !"".equals(dbSystemAccount.getCounterStaff())){
CounterStaff counterStaff = dbSystemAccount.getCounterStaff();
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(), counterStaff.getStaffName());
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(), GenericConstant.SystemRole.COUNTER_STAFF.toValue());
}else if(dbSystemAccount.getCustomer()!= null && !"".equals(dbSystemAccount.getCustomer())){
Customer customer = dbSystemAccount.getCustomer();
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(), customer.getCustomerName());
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(), GenericConstant.SystemRole.CUSTOMER.toValue());
}else if(dbSystemAccount.getManager()!= null && !"".equals(dbSystemAccount.getManager())){
Manager manager = dbSystemAccount.getManager();
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(), manager.getManagerName());
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(), GenericConstant.SystemRole.MANAGER.toValue());
}else if(dbSystemAccount.getDoctor()!= null && !"".equals(dbSystemAccount.getCounterStaff())){
Doctor doctor = dbSystemAccount.getDoctor();
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(), doctor.getDoctorName());
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(), GenericConstant.SystemRole.DOCTOR.toValue());
}
request.setAttribute(SessionAttribute.AttributeName.LOGIN_DATE.toValue(), DateTimeUtil.getCurrentDate());
return "mainPage";
}else {
model.addAttribute(GenericConstant.MessageAttributeName.ERROR_MSG_NAME.toValue(), SystemMessage.SystemException.LOGIN_INCORRECT_USERNAME_PASSWORD);
model.addAttribute("systemAccount", new SystemAccount());
return "index";
}
}
}
After everything is ready, the controller will navigate user to the main page and the main page able to access all the defined variable without issue. (The following figure shown the controller that mapped with mainPage).
A.java controller file,
#RequestMapping(value = "/mainPage", method = RequestMethod.GET)
public String renderMainPageView(Model model, HttpServletRequest request) {
if(request.getAttribute(SessionAttribute.AttributeName.LOGIN_CHECK.toValue()) != null) {
model.addAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ID.toValue(),
request.getAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ID.toValue()));
model.addAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(),
request.getAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue()));
model.addAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(),
request.getAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue()));
model.addAttribute(SessionAttribute.AttributeName.LOGIN_DATE.toValue(),
request.getAttribute(SessionAttribute.AttributeName.LOGIN_DATE.toValue()));
return "mainPage";
}else {
model.addAttribute("systemAccount", new SystemAccount());
return "index";
}
}
In the navigation menu of main page, I click on the selection to direct me to add manager web page. (The following shown the link).
<a href="addManager" target="ifrm" >Add New Account</a>
The controller that mapped with the link (GET) able to detect. However, this controller (renderAddManagerView) does not recognised the HTTP session that I defined earlier when I try to access using the getAttribute method in the if condition. It keep showing null value (Shown in the following figure.
B.java controller file,
#RequestMapping(value = "/addManager", method = RequestMethod.GET)
public String renderAddManagerView(Model model, HttpSession httpSession) {
if(httpSession.getAttribute(SessionAttribute.AttributeName.LOGIN_CHECK.toValue()) != null) {
model.addAttribute("manager", new Manager());
model.addAttribute(FormSelectionValue.FormSelectionAttributeName.COUNTRY_SELECTION.toValue(), FormSelectionValue.COUNTRY_SELECTION_LIST);
model.addAttribute(FormSelectionValue.FormSelectionAttributeName.GENDER_SELECTION.toValue(), FormSelectionValue.GENDER_SELECTION_LIST);
return "addManager";
}else {
model.addAttribute("systemAccount", new SystemAccount());
return "index";
}
}
So I am not sure what is the issue for my code and there is no error message is displayed.
I have solved the issue by using the HttpServletRequest instead of HttpSession.
Now my session will not be loss even redirect or navigate to any pages in JSP.
Something like this:
#RequestMapping("/renderview", method = RequestMethod.GET)
#Controller
public class TestController {
#RequestMapping(method = RequestMethod.GET)
public String myMethod(HttpServletRequest request)
{
request.getSession().setAttribute("mySession", "XXX");
return "jspview";
}
}
Reference: Set session variable spring mvc 3

How to keep request parameters after redirect?

I'm trying to resolve a bug when I send a form with an empty input.
This is my methode:
#RequestMapping(value = "/modifier.html", method = RequestMethod.POST)
public String modifier(ModelMap map, #ModelAttribute("FormObject") FormObject formObject, BindingResult result, HttpServletRequest req) {
formObject.setModif(true);
String idParam = req.getParameter("idTypeOuverture");
if (result.hasErrors()) {
return "redirect:/gestion.html?section=Configuration&panel=4&ouvrir=modifier";
} else {
//Instructions
}
When there are errors (empty input) the controller redirects to this link to tell user to correct errors. The problem is when I check parameters here they look correct (id, name ...), but the id becomes null in the following method:
#Override
public ModelAndView dispatcher(HttpServletRequest request, HttpServletResponse response) throws RorException {
Map<String, Object> myModel = (Map<String, Object>) request.getAttribute(EnumParam.R_MY_MODEL.getKey());
Enumeration<?> keys = request.getParameterNames();
while (keys.hasMoreElements()) {
String paramName = (String) keys.nextElement();
String value = request.getParameter(paramName);
myModel.put(paramName, value);
}
GlobalSession globalSession = (GlobalSession) getApplicationContext().getBean(Utilities.GLOBALSESSION_BEAN_REF);
myModel.put("module", globalSession.getModule().getKeyMessage());
String section = request.getParameter("section");
// This instruction returns null
String idForm = request.getParameter("id");
id = Integer.parseInt(idForm);
// This instruction returns NumberFormatException
ObjectForm of = getForm(id);
// ...
}
Well, I don't know why parameter id changed after redericting? do you have any idea? I tried to redifine parameters in the first method but still got the same NFE.
Thank you in advance.
Thank you
Although the previous answer is accepted, I am adding this answer just for your information.
You can also use RedirectAttributes with and without FlashAttributes also Before issuing redirect, post method should take RedirectAttributes as argument These attributes will be passed as request parameters Look at my code example and see if its helpful.
Way 1 :
#RequestMapping(value={"/requestInfo.html"}, method=RequestMethod.POST)
public String requestInfoPost1(
#ModelAttribute("requestInfoData") RequestInfoData requestInfoData,
BindingResult result,
RedirectAttributes redirectAttributes,
SessionStatus status
) {
// some logic
redirectAttributes.addAttribute("name", requestInfoData.getName());
redirectAttributes.addAttribute("age", requestInfoData.getAge());
// some logic
return "redirect:requestInfoSuccessRedirect";
}
#RequestMapping("requestInfoSuccessRedirect")
public String requestInfoSuccessRedirect()
{
return "requestInfoSuccess";
}
Way 2:
Whatever data is added in flash attribute will be added in session It will be in session only till redirect is successful On redirect, data is retrieved from session and added to Model for new Request. Only after redirect is successful, data is removed
#RequestMapping(value={"/requestInfo.htm"}, method=RequestMethod.POST)
public String requestInfoPost(
#ModelAttribute("requestInfoData") RequestInfoData requestInfoData,
BindingResult result,
RedirectAttributes redirectAttributes,
SessionStatus status
) {
// some logic
redirectAttributes.addFlashAttribute("requestInfoData",
requestInfoData);
// some logic
return "redirect:requestInfoSuccessRedirect";
}
#RequestMapping("requestInfoSuccessRedirect")
public String requestInfoSuccessRedirect()
{
return "requestInfoSuccess";
}
The request parameter is only for one request.
You make a redirect, it means that you make another new "request".
You should add it to the redirect:
return "redirect:/gestion.html?section=Configuration&panel=4&ouvrir=modifier&idTypeOuverture="+idParam;

Adding #ModelAttribute results in 400 (Bad Request) in Delete Request

I can submit a delete request fine with the following:
#RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Result> deleteTest(#PathVariable String id) {
return new ResponseEntity<>(Result.Success("Hi " + id + "!!!", null), HttpStatus.OK);
}
However, when I add an #ModelAttribute variable, I get 400 (Bad Request) as the http response code:
#RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Result> deleteTest(#PathVariable String id, #ModelAttribute("authUser") User authUser) {
return new ResponseEntity<>(Result.Success("Hi " + id + "!!!", null), HttpStatus.OK);
}
This #ModelAttribute is working fine with a put request handler I have in my #RestController but not in this delete request.
Here's the #ModelAttribute code:
#ModelAttribute("authUser")
public User authUser(#AuthenticationPrincipal SpringAuthUser springAuthUser) throws Exception {
User user = ConstantsHome.userprofileMgr.getUserByUserId(springAuthUser.getUsername(), true, true);
user.updateRights(null);
request.getSession().setAttribute(ConstantsHome.USEROBJECT_KEY, user);
return user;
}
Why would adding #ModelAttribute cause a delete request to return a 400 (Bad Request) http response?
I'm using spring-web-4.1.4 & spring-security-4.0.3
I digged a little and found that specifying a #PathVariable of "id" somehow attaches it to the #ModelAttribute variable (as a Long(!) instead of a String as I specified). I then came across this post that lead me to different ways to resolve the issue :
Values of #PathVariable and #ModelAttribute overlapping.
Ended up with this as a method declaration (replaced "id" with "userId"):
#RequestMapping(value = "/{userId}", method = RequestMethod.DELETE)
public ResponseEntity<Result> deleteUser(#PathVariable String userId,
#ModelAttribute("authUser") User authUser) {
...
}
Hopefully this will help someone else quickly that might run into this issue instead of spending a day trying to figure it out...

How to avoid redirect loop in spring web mvc

public class ValidateSession extends HandlerInterceptorAdapter {
//before the actual handler will be executed
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
if(session.getAttribute("user")==null){
/*ModelAndView mav = new ModelAndView("/login/index");
throw new ModelAndViewDefiningException(mav);*/
ModelAndView mav = new ModelAndView();
mav.setViewName("redirect:/login/index.mars");
throw new ModelAndViewDefiningException(mav);
}
return true;
}
}
In my case if session is expired then user can't access my application, but i am stuck with redirection loop. although i have tried many possible ways but not luck :(
Don't associate the ValidateSession handler with the login/index.mars request. Use mvc interceptor. Exclusions possible since 3.2, I think.
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/yourpath/*"/>
<exclude-mapping path="/login/index.mars"/>
<bean class="org...ValidateSession " />
</mvc:interceptor>
</mvc:interceptors>
I know this is an old post but thought it may be of help since none of the above worked for me.
In the class implementing HandlerInterceptor:
response.sendRedirect("login?logout=true");
then in controller:
#RequestMapping(value = "login", method = RequestMethod.GET)
public String login(ModelMap modelmap, HttpServletRequest request, HttpSession httpSession, #RequestParam(required = false) String logout, #RequestParam(required = false) String reason, #RequestParam(required = false) String message) {
if (reason != null && MvcStatics.ERROR_MAP.get(reason) != null) {
ArrayList<String> errors = new ArrayList<>();
errors.add(MvcStatics.ERROR_MAP.get(reason));
modelmap.addAttribute("errors", errors);
}
if (logout != null && logout.equalsIgnoreCase("true")) {
httpSession.removeAttribute("loggedIn");
httpSession.removeAttribute("user");
httpSession.removeAttribute("token");
modelmap.addAttribute("message", "You have successfully been logged out.");
}}
i experienced the same issue. just remove the "redirect:" appended before "/login/index.mars"
ModelAndView mav = new ModelAndView();
mav.setViewName("redirect:/login/index.mars");
//to this and you redirect ll works fine
mav.setViewName("/login/index.mars");
throw new ModelAndViewDefiningException(mav);

Controller Testing For SPRING-MVC

I am getting error in my controller Saying Null Pointer Exception while When I don't perform the testing. Everything works fine.
Controller :
#RequestMapping(value = "/studentinsection/{sectionId}", method = RequestMethod.GET)
public ModelAndView studentInSectionForm(#ModelAttribute("studentInSectionFormData") StudentInSectionForm studentInSectionFormData,
#PathVariable Integer sectionId,
ModelMap model) {
ArrayList<StudentInSections> studentInSectionList = (ArrayList<StudentInSections>)
studentInSectionsService.retrieveAllStudentInSections(sectionId, 1);
StudentSection studentSection = studentSectionService.retrieveStudentSection(sectionId);
logger.info("section Name is:" + studentSection.getSectionName());
ArrayList<User> userList = new ArrayList<User>();
for (StudentInSections studentInSections : studentInSectionList) {
String studentName =
(userService.retrieveUserName(studentInSections.getStudentId(), 1));
User users = userService.retrieveUser(studentName);
userList.add(users);
}
logger.info("sectionId is " + sectionId);
ArrayList<User> allStudents = (ArrayList<User>)
userService.retrieveAllStudents();
studentInSectionFormData.setStudentInSectionList(studentInSectionList);
model.addAttribute("studentList", allStudents);
model.addAttribute("userList", userList);
model.addAttribute("studentSectionName", studentSection.getSectionName());
model.addAttribute("studentSectionId", studentSection.getSectionId());
return new ModelAndView("studentinsection", "studentInSectionFormData", studentInSectionFormData);
}
Testing is as follow:
#Test
public void testStudentInSectionForm() throws Exception {
mockMvc.perform(get("/studentinsection/1"))
.andExpect(status().isFound())
.andExpect(redirectedUrl("studentinsection"));
}
this is passing everything into the controller fine even sectionId is getting printed 1 in logger than also studentin sectionList returns nullMointerException. help me to resolve my problem.. Thanx
It slooks like the context is not being loaded correctly. What is the exception stacktrace.
You can also view the request if you do :
mockMvc.perform(get("/studentinsection/1"))
.andExpect(status().isFound())
.andDo(print())

Resources