How to handle session to keep login information using Spring MVC - spring

I want to make login form with Spring MVC using Hibernate.
I found that I need to use 'session' to keep login information.
So, I use it in 'Controller.java', '.jsp'.
But It seems didn't work.
Below is my code. Controller.java:
#Controller
public class PassengerController {
#Autowired
private PassengerService passengerService;
public void setPassengerService(PassengerService passengerService) {
this.passengerService = passengerService;
}
#RequestMapping(value = "/login")
public String login(HttpSession session, HttpServletRequest request) {
String id = request.getParameter("idInput");
String pw = request.getParameter("pwInput");
// check DB
// if it is right, add session.
session.setAttribute("id", id);
session.setAttribute("pw", pw);
return "flightschedule";
}
#RequestMapping(value = "/logout")
public String logout(HttpSession session) {
session.invalidate();
return "flightschedule";
}
}
Below is part of flightschedule.jsp:
<c:if test="${sessionScope.loginId eq null}">
<!-- Not login: show login button -->
<div class="loginArea">
<form action="${loginAction}"> <!-- // URL '/login' -->
<input type="text" name="idInput" placeholder="ID" class="loginInput">
<input type="password" name="pwInput" placeholder="PASSWORD" class="loginInput">
<input id="loginButton" type="submit" value="login">
</form>
</div>
</c:if>
<c:if test="${sessionScope.loginId ne null}">
<!-- already login: show logout button -->
<div class="loginArea">
<form action="${logoutAction}"> <!-- // URL '/logout' -->
<input type="button" name="idInput" id="loginInfo" value="Welcome ${sessionScope.loginId}">
<input id="logoutButton" type="submit" value="LOGOUT">
</form>
</div>
</c:if>
I intended that when session.id exists, show log out button and when session.id doesn't exist, show login button.
I don't want to use interceptors or spring security etc..
I thought they're too complex to my little project.
And, I have login/logout form at all most of my pages. I don't use a separate page to login.
So I don't want to use interceptor. I just want to check whether session key exists in some jsp pages. Depending on its presence, I want to change page's view.
Above's code work partly. When login, it shows 'Welcome userId'.
But, when I click page's logo(then go to the first page), It still show 'login' button. It have to show 'log-out' button becuase session.loginId exists!
Do you have any solution?

In login method you put
// check DB
// if it is right, add session.
session.setAttribute("id", id);
session.setAttribute("pw", pw);
but on JSP check sessionScope.loginId , looks like you should check attribute with name id.

Related

I can't send a POST request using my browser?

I am working on an application using Spring Boot MVC and I have a login page and whenever I input data on the forms using chrome my browser doesn't redirect me to the page I've specified in my Controler class but instead It sends a GET request where it should be sending a POST request. This is my controller class
#Controller
#RequestMapping("/login")
public class loginController {
private final AuthService authService;
public loginController(AuthService authService) {
this.authService = authService;
}
#GetMapping
public String returnLogIn() {
return "login";
}
#PostMapping
public String login(#RequestParam String username, #RequestParam String password, Model model) {
User user = null;
try {
user = this.authService.login(username, password);
model.addAttribute("User", user);
return "redirect:/home";
} catch (InvalidArgumentsException exception) {
model.addAttribute("hasError", true);
model.addAttribute("error", exception.getMessage());
return "login";
}
}
}
As you see if the login is successful then I should be redirected to the home page but It doesn't happen I get redirected to the login page again and all that changes is the URL in it the parameters I've given are appended. But when I use POSTMAN everything works just fine a POST request is sent and I get redirected to the /home page just like I've specified it in my Controller class. But I don't know why this wont happen when I use chrome. Having to use POSTMAN everytime I do a small change is really time-consuming. Also this is the HTML form
<form id="form-id" th:action="#{/login}" th:method="post">
<div class="mb-3">
<input type="text" class="form-control" name="username" id="username" aria-describedby="emailHelp"
placeholder="User Name">
</div>
<div class="mb-3">
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
<!-- TODO use hasError set it in the model -->
<div th:if="${hasError}">
<span class="error text-danger" th:text="${error}"></span>
</div>
<div class="text-center"><button type="submit" class="btn btn-color px-5 mb-5 w-100 btn btn-dark" >Login</button></div>
</form>
I don't think there is something wrong with my code since everything works fine when I use POSTMAN but I really don't know why It wont work when I use my browser. Javascript is enabled in my browser I really don't know what seems to be the issue. I also tried mapping the POST request to a different URL but still I get the same issue.
I also believe that your code sample has no problem because if there is a problem it should not respond correctly from POSTMAN,Unless you have configured the application server and restricted requests from the browsers.
The suggestion I can give you is to monitor requests when sending a request using tools like Fiddler (Fiddler is a powerful web debugging proxy),etc.. ,to see if both requests send the same parameters to server .

Submit button is not working in spring

File jsp
<form:form action="saveProduct" method="POST" modelAttribute="product">
<input type = "submit" name = "action1" value="Save"/>
</form:form>
File Controller
#RequestMapping(value = "/saveProduct", method = RequestMethod.POST, params = "action1")
public ModelAndView saveProduct(HttpServletRequest request,#ModelAttribute("product") Products product){
if(product.getIdPro() == 0){
proService.addPro(product);
} else {
proService.updatePro(product);
}
return new ModelAndView("redirect:/pro");
}
This is my jsp file and my controller. I use to extra <table/> tag, some another <input/> tag in <form/> tag. I tried to use <form:input> tag but not positive. I cannot execute submit button.
Everything looks ok, except of spaces after tag attributes (that is not valid).
Try to remove thoose:
<input type="submit" name="action1" value="Save"/>

Spring relationships between tables in view

Well, I started a new project using Spring MVC (I'm beginner in technology) and soon I had a basic question which I am unable to find on the internet, maybe the reason that I'm doing wrong or implementing the wrong question.
I have a form in which the data will be persisted are in two different tables.
What better way to do this?
I created two related tables, one called "Agency" and another called "Login". An "Agency" may contain one or more "Login" (# OneToMany), but the problem takes the view creation time, because data from both tables will compose a single form. With some research I noticed that I can not have two modelAttribute in my form.
I apologize for the mistakes in English.
Best regards!
if the mapping is correct and Agency contain one or many login, what you have to do is render the Agency in the model and view and in your form iterate the logins
<form:form id="foo"
method="post"
action="url"
modelAttribute="agency">
<form:input type="hidden" path="id"/>
<c:forEach var="login" items="${agency.logins}"
varStatus="login_index">
<form:input type="hidden" path="login.id" />
</c:foreach>
</form:form>
thanks for the reply.
But is not it :(
I have a form in which the data will be persisted are in two different tables.
<form class="form-signin" method="post" action="addAgency">
<div class="input-group">
<span class="input-group-addon entypo-user"></span>
//Table Agency
<spring:bind path="tenant.firstName"/>
<input class="form-control" placeholder="Nome"/>
//Table Login
<spring:bind path="login.email"/>
<input class="form-control" placeholder="Nome"/>
</div>
//Rest of my form...
</form>
In my view I have the annotation "bind" Spring, searching in the internet I found this way to make the connection between the controller and the view for persist two tables.
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(#ModelAttribute("tenant") Agency tenant, #ModelAttribute("login") Login login, ModelMap map) {
Agency agency = dashboardFacade.getAgency();
map.addAttribute("agency", agency);
if (tenantResolver.isMasterTenant()) {
//Here is the problem!!
// Add an attribute in my view of type login and agency, but i don't kwon if it is correct.
map.addAttribute("tenant", tenant);
map.addAttribute("login", login);
return "landing/index";
} else {
return "dashboard/home";
}
}
The method below to save an agency and login.
// Add a new agency
#RequestMapping(value = "/addAgency", method = RequestMethod.POST)
public String addAgency(#ModelAttribute("tenant") Agency agency, #ModelAttribute("login") Login login, Model model, final RedirectAttributes redirectAttributes) {
agency = dashboardFacade.addAgency(agency);
login = dashboardFacade.addLogin(login);
return "redirect:" + getAgencyFullUrl(agency);
}
What better way to do this?
Thank you

Spring - HTTP Status 404 - The requested resource is not available

I have the 404 error when requesting a page. I have a users page with a list of objects that the user can click on to then carry out a number of transactions, add, edit etc.
The controller for it
#RequestMapping(value="/main/user/setter/addpage/", method = RequestMethod.GET)
public String getAddPage(#RequestParam("userId") Integer userId, ModelMap model) {
Module module = new Module();
model.addAttribute("userId", userId);
model.addAttribute("module", module);
return "/main/user/setter/addpage";
}
The page I want to get
<c:url var="processUrl" value="/main/user/setter/addpage/?id=${userId}" />
<form:form modelAttribute="module" method="POST" action="${processUrl}" name="module"
enctype="multipart/form-data">
</form:form>
The page that I'm requesting it from:
<c:forEach items="${users}" var="setter" >
<c:url var="addUrl" value="/main/user/setter/addpage?userId=${setter.userId}" />
<td>
add
</td>
When I click on the add link above it goes to the 404 page. Obviously the url is going through. Any help would be great.
can you try :
#RequestMapping(value="/main/user/setter/addpage"
instead of
#RequestMapping(value="/main/user/setter/addpage/"

how to do binding in Spring annotated request parameter?

i have a controller that is using annotation for request mapping and requestParam.
the controller is working fine. However when submitting a command object with array, spring will crap out saying array index out of bound. i am guessing there is something wrong with binding but don't know how to fix it.
to be more specific, in eclipse i would set debugger at the beginning of the controller, and when submitting the form (by hitting a input submit button) eclipse debugger will not trigger and i will see array index out of bound error in console.
the controller is something like this:
#RequestMapping(value = {"/internal/pcsearch.dex", "/external/pcsearch.dex"},
method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView executeProductCatalogSearch(
HttpServletRequest request,
#RequestParam(value = "cat" ,required = false) String cat,
#RequestParam(value = "brand" ,required = false) String brand,
#ModelAttribute("command") ProductCatalogCommand cmd
){
[edit]
and the jsp is like:
<form name="pForm"
id="pForm"
action="<c:url value="psearch.dex"><c:param name="cat" value="${cat}"/></c:url>"
method="POST"
style="display:inline;">
...
...
<c:forEach var="model" items="${models}" varStatus="modelLinkStatus">
<script>
var modelImg<c:out value="${modelLinkStatus.index}"/>Src = '<c:out value="${model.altModelImage}"/>';
</script>
<spring:bind path="command.models[${modelLinkStatus.index}].modelSkusDisplayed">
<input type="hidden" name="<c:out value="${status.expression}"/>" id="<c:out value="${status.expression}"/>" value="<c:out value="${status.value}"/>"/>
</spring:bind>
<spring:bind path="command.updateCartButton">
<input type="submit" value="<spring:message code="orderEntryMessages.ecatalog.button.addToCart" text="Add to Cart" htmlEscape="yes" />" name="<c:out value="${status.expression}"/>" id="<c:out value="${status.expression}"/>" class="sub_buttons"/>
</spring:bind>
...
and the command object declare the model array as:
private List<ModelLink> models = new ArrayList<ModelLink>();
where modelLink is a custom ds.
the first foreach tag handle the the model command object and the 2nd part is the submit button i clicked on.
i think you should use AutoPopulatingList as models to bind list to view and controller. for example please refer link. This might resolve your problem of index.

Resources