get value from a session Object - java

I have a User bean class with constructor and getter and setter
public class User {
private String username;
private String password;
}
i have a controller which logs in a user
#PostMapping("/login")
public String login(#ModelAttribute User user,Model model){
model.addAttribute("session", user);
return "index1";
}
Also one demo mapping for the same index1 page to check session
#GetMapping("/find")
public String find(Model model){
return "index1";
}
in the jsp page i am not able to check the user that is populated in the session object
<%# page errorPage="index.jsp" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login</h1>
<c:if test='${sessionScope.session.user} == "user"'>
<% session.invalidate(); %>
</c:if>
<p>Hello ${sessionScope.session.password}</p>
</body>
</html>
i am using #sessionattribute of Spring to use the session values and my session object name is session .
How to invalidate the session when user is user it always comes as null please help .
How to get the values inside the object that is stored in a session
this is a demo to test session handling

Following will not work for you,
#PostMapping("/login")
public String login(#ModelAttribute User user,Model model){
model.addAttribute("session", user);
return "index1";
}
Because first of all you are not setting anything in the ModelAndView but into a model object which will be nullified once you move to index1 view.
You need to set the if as follows,
#PostMapping("/login")
public ModelAndView login(#ModelAttribute User user, Model model, HttpServletRequest request){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("session", user);
modelAndView.setViewName("index1");
return modelAndView;
}

Related

SPRING MVC: returned ModelAndView/parameters precedence

I'm new in Spring, and I'm trying to better undestand the MVC framework.
Considering the following jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World!</title>
</head>
<body>
Welcome <%=request.getAttribute("username")%>
</body>
</html>
I see that, in a #Controller class:
#GetMapping("/EntryPoint1")
public String helloView1(Model model) {
model.addAttribute("username", "pippo");
return "HelloWorld";
}
it uses as username value the one inserted in model.
However, if I declare both the Model model parameter and I return a ModelAndView object, that is:
#GetMapping("/EntryPoint2")
public ModelAndView helloView2(Model model) {
model.addAttribute("username", "pluto");
ModelAndView mav = new ModelAndView("HelloWorld");
mav.addObject("username", "paperino");
return mav;
}
I obtain that the value used by the view is the one contained in mav ignoring the value in model. Is there an explanation for this (for example, any kind of precedence between the objects considered by the view)?
see, here in model.addAttribute("username", "pluto");
and in mav.addObject("username", "paperino");
username is same so priorities goes to ModelAndView, However u change the name then u can render them both and access.

Invoke Spring controller method on redirect FROM jsp

So let assume I have 2 jsp files:
login.jsp and menu.jsp
Also I have two methods in the controller class:
#RequestMapping("/login")
public void login() {
return "login";
}
#RequestMapping("/menu")
public void menu() {
List<User> allUsers = userJpaRepository.findAll();
return new ModelAndView("allUsers", "users", allUsers);
}
In login.jsp
<%#page import="com.markovski.database.DataBase"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<form method="get" action="menu.jsp">
<%
String accname = request.getParameter("uname");
String password = request.getParameter("pass");
if(DataBase.checkForUserCreditinals(accname, password)){
session.setAttribute("userId", 2);
response.sendRedirect("menu.jsp");
} else {
//out.println("Error");
}
%>
</form>
So what do I want ? When I log in I would like to be redirected to menu page, but it does not invoke menu(), which will pass all users to my menu.jsp. So it is just opening an empty /menu page. How can I redirect to menu.jsp AND INVOKE the controller method, which will give me the data that I want to display ?
As you are coding in Spring, I think we can stick to it than mixing jsp and Spring style. Why don't you write a mapping for menu url and return menu.jsp from it. Also you can keep your database code as well there ( though not a good practice). You may also need to handle the login submissions as well.

Spring MVC form submission, populate on the same page

I am trying to create a simple function using a post method. What I want is whatever is entered in the form and submitted- it should appear on the same page below the form. However the text just disappears once I click "submit". Here is my code
Contoller
#Controller
public class SearchController {
#RequestMapping(value = "/search", method = RequestMethod.GET)
public String goToSearch(Model model) {
model.addAttribute("item", new Item());
return "itemsearch";
}
#RequestMapping(value = "/search", method = RequestMethod.POST)
public String search(Item item, Model model, #RequestParam String itemId) throws IOException{
model.addAttribute("item", new Item());
return "itemsearch";
}
}
Jsp file
<%# 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="s" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Search for an item</h2>
<sf:form action="search" method="POST" modelAttribute="item">
<label>Please enter the item Id number:<sf:input type="text" name="itemId" id="itemId" path="itemId" /></label><br/>
<input type="submit" value="Submit" path="submit" />
<br> You are trying to search for Id Number: <b><h3>${item.itemId}<h3></h3></b>
</sf:form>
Item class
public class Item {
private String itemId;
private List<String> itemDetails;
public List<String> getItemDetails() {
return itemDetails;
}
public void setItemDetails(List<String> itemDetails) {
this.itemDetails = itemDetails;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
}
Many thanks
I think you need a basic understanding how Spring MVC works.
Have a look at this picture:
You see an incoming request (your POST request) from the client which is redirected to the desired controller. The controller (your SearchController) makes some business magic and returns the model to the front controller. The model is by default empty. You can add objects that should be rendered via model.addAttribute("someId", someObject);
The passed model is now handled by the view template (itemsearch) which connects the template and the model to a (static) response that is passed to the client.
And there is the problem. You are passing in your controller new Item() to the model. It is an empty object which has no values (and no id which you want to render after the form submition). Therefore on your JSP page could be nothing displayed. Just pass the found item or the item from your request to the model.

Not able to read Model passed by controller on jsp

I am sending Object with help of ModdelAndView in Spring controller, but i am not able to read it on jsp?
JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Tried with EL:
${user}
Try with JSTL:
<c:out value="${user}"></c:out>
</body>
</html>
controller:
#Controller
public class StudentHome {
#RequestMapping(value = "/auth/Home")
public ModelAndView RedirectLogin() {
ModelAndView modelAndView = new ModelAndView("/auth/Home");
modelAndView.addObject("user", "Alex");
return modelAndView;
}
}
I have tried both Spring EL and jstl its not working. Do i need to include anything else?
We need to include org.springframework.web.servlet.ModelAndView instead of org.springframework.web.portlet.ModelAndView;
The model presents a placeholder to hold the information you want to display on the view. It could be a string, which is in your above example, or it could be an object containing bunch of properties.
update your code as follows
#Controller
public class StudentHome {
#RequestMapping(value = "/auth/Home")
public ModelAndView RedirectLogin() {
return new ModelAndView("yourJspName","user", "Alex");
}
}
then in your jsp, to display the message, you will do
Hello ${user}!
hope this will help you..!

How to manage error message in Spring MVC

I am new to spring MVC .My abc page is have one submit button. On click of submit button, abcHandler called which is inside xyzController.
Just wondering how to achieve this scenario.
-- If some error occurs then it should return some message.
-- It should stay in the same page , for me its abc page.
I have tried this.The problem I am facing is that , i am getting the alert message as "You must have something...",
but it is navigating to error page means a blank page. This is not suppose to happen.I want to show the message and stay in the same page.
How can i achieve easily with spring MVC.
Please suggest some idea.
public class xyzController extends MultiActionController implements InitializingBean {
public ModelAndView abcHandler(HttpServletRequest request,HttpServletResponse response)throws Exception {
// session
HttpSession session = request.getSession(true);
String abc = "";
if(abc != ""){
}else{
String error = "You must have xyzzzzzz";
return new ModelAndView("2.0/error", "downloaderror", error);
}
return new ModelAndView();
}
}
My error.jsp is like this
<!DOCTYPE html>
<html>
<head>
<script src="abc/js/jquery-1.9.0.min.js"></script>
</head>
<body>
<c:if test="${not empty downloaderror}">
<script>
alert("You must have something...");
</script>
</c:if>
</body>
</html>
You can implement HandlerExceptionResolver on your own.Refer to this tutorial: http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
Add an error flag in controller method like this
public ModelAndView abcHandler(HttpServletRequest request, HttpServletResponse response)throws Exception {
ModelAndView model=new ModelAndView();
model.addObject("error", true);
return model;
}
In JSP
<!DOCTYPE html>
<html>
<head>
<script src="abc/js/jquery-1.9.0.min.js"></script>
</head>
<body>
<c:if test="${error}">
<script>
alert("You must have something...");
</script>
</c:if>
</body>
</html>
You can achieve the scenario by going in following way:
import org.springframework.web.servlet.ModelAndView;
public ModelAndView abcHandler(HttpServletRequest request, HttpServletResponse response)throws Exception {
ModelAndView model=new ModelAndView();
model.addObject("ERROR_CODE", "Error Occurred");
model.setViewName("page1");
return model;
}
and your jsp page will be like following:
page1.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<body>
<c:if test="${!empty ERROR_CODE }">
<c:out value="${ERROR_CODE }"></c:out>
</c:if>
</body>
</html>
On validation failure do not return to error page, instead return to same page so your code in else block should be
}else{ String error = "You must have xyzzzzzz";
return new ModelAndView("2.0/error", "downloaderror", abc); }
And also store the errormessage in your modelmap against some key like "errormsg" and on your abc page check for this key and then print the message.

Categories

Resources