I have a question, I didn't understand why this part of the code(where is registration) Spring doesn't find even if I wrote an url. But the same code in another part, for example, add a new book or add the new author of the book is working correctly it added everything into the database and send me into another page. But if I register the person and click submit it always shows me 400 - bad request error. Please help me. What I wrote wrong?
This is my controller(doesn't work registration part with register book (not redirect to registerbook and doesn't add data into DB)):
#Controller
public class HelloController {
private static final Logger logger = Logger.getLogger(HelloController.class.getName());
#Autowired
#Qualifier("author")
private AuthorzDAO authorzDAO;
#Autowired
#Qualifier("book")
private BooksDAO booksDAO;
#Autowired
#Qualifier("borrow")
private BorrowsDAO borrowsDAO;
#Autowired
#Qualifier("person")
private PersonDAO personDAO;
#RequestMapping(value = "/",method = RequestMethod.GET)
public ModelAndView printHello() {
return new ModelAndView("hello", "command", new LoginPerson());
}
#RequestMapping(value = "/",method = RequestMethod.POST)
public String login(#ModelAttribute("SpringWeb")LoginPerson person, ModelMap model, HttpServletRequest request) {
model.addAttribute("info", personDAO.getInfromStudent(person.getEmail(), person.getPassword()));
model.addAttribute("takenbook", person.getEmail());
if (person.getEmail().equals("admin#admin.com") && person.getPassword().equals("admin")) {
logger.warning("AAAAA");
logger.warning(person.getEmail());
return "admin";
} else if(personDAO.checkPerson(person.getEmail(), person.getPassword()) == true){
logger.warning(personDAO.checkPerson(person.getEmail(), person.getPassword()).toString());
logger.warning("BBBBB");
logger.warning(person.getPassword());
return "personinfo";
} else {
return new ResponseStatusException().error();
}
}
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public ModelAndView registration() {
return new ModelAndView("registration", "person", new Person());
}
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String register(#ModelAttribute("person") Person person) {
logger.warning("Hello");
logger.warning(person.toString());
personDAO.connectPerson(person);
return "redirect:/registerbook";
}
#RequestMapping(value = "/registerbook", method = RequestMethod.GET)
public ModelAndView registerbook() {
//model.addAttribute("newborrow", new Borrows());
return new ModelAndView("registerbook", "newborrow", new Borrows());
}
#RequestMapping(value = "/registerbook", method = RequestMethod.POST)
public String regbook(#ModelAttribute("newborrow") Borrows borrows, ModelMap model) {
logger.warning(String.valueOf(borrows.getId()));
model.addAttribute("borrowid", borrows.getId());
model.addAttribute("personid", borrows.getStudentid());
model.addAttribute("bookid", borrows.getBookid());
Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, -30);
Date today30 = cal.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Timestamp todays30 = Timestamp.valueOf(dateFormat.format(today30));
Timestamp todayy = Timestamp.valueOf(dateFormat.format(today));
borrows.setTakendate(todayy);
borrows.setBroughtdate(todays30);
borrowsDAO.insertBorrow(borrows);
return "hello";
}
#RequestMapping(value = "/addauth", method = RequestMethod.GET)
public ModelAndView addauth() {
return new ModelAndView("addauthbooks", "adding", new Authorz());
}
#RequestMapping(value = "/example", method = RequestMethod.POST)
public String addingauthor(#ModelAttribute Authorz authorz, ModelMap model) {
model.addAttribute("id_author", authorz.getAuthorid());
model.addAttribute("fname_author", authorz.getName());
model.addAttribute("lname_author", authorz.getSurname());
logger.warning(String.valueOf(authorz.getAuthorid()));
logger.warning(authorz.getName());
logger.warning(authorz.getSurname());
authorzDAO.insertAuthorz(authorz);
return "example";
}
#RequestMapping(value = "/addbooks", method = RequestMethod.GET)
public ModelAndView addbook() {
return new ModelAndView("addbook", "addingbook", new Books());
}
#RequestMapping(value = "/admin", method = RequestMethod.POST)
public String addingbook(#ModelAttribute Books books, ModelMap model) {
model.addAttribute("id", books.getId());
model.addAttribute("name", books.getName());
model.addAttribute("pagecount", books.getPagecount());
model.addAttribute("point", books.getPoint());
model.addAttribute("authorid", books.getAuthorid());
model.addAttribute("typeid", books.getTypeid());
model.addAttribute("fragment", books.getFragment());
logger.warning(String.valueOf(books.getId()));
logger.warning(books.getName());
logger.warning(String.valueOf(books.getPagecount()));
booksDAO.insertBook(books);
return "admin";
}
#RequestMapping(value = "/deleteauth", method = RequestMethod.GET)
public ModelAndView deleteauthbooks() {
return new ModelAndView("deleteauthbooks", "deletingauthor", new Authorz());
}
#RequestMapping(value = "/admins", method = RequestMethod.POST)
public String deleteresult(#ModelAttribute Authorz authorz, ModelMap model) {
model.addAttribute("id", authorz.getAuthorid());
model.addAttribute("name", authorz.getName());
model.addAttribute("surname", authorz.getSurname());
authorzDAO.delete_book(authorz.getSurname());
return "admin";
}
#RequestMapping(value = "/deletebooks", method = RequestMethod.GET)
public ModelAndView deletebook() {
return new ModelAndView("deletebooks", "deletingbook", new Books());
}
#RequestMapping(value = "/nadmin", method = RequestMethod.POST)
public String deletebookresult(#ModelAttribute Books books, ModelMap model) {
model.addAttribute("id", books.getId());
model.addAttribute("name", books.getName());
model.addAttribute("pagecount", books.getPagecount());
model.addAttribute("point", books.getPoint());
model.addAttribute("authid", books.getAuthorid());
model.addAttribute("typeid", books.getTypeid());
booksDAO.delete_book(books.getName());
return "admin";
}
#RequestMapping(value = "/borrow", method = RequestMethod.GET)
public ModelAndView borrows() {
return new ModelAndView("borrow", "borrowing", new LoginPerson());
}
#RequestMapping(value = "/res", method = RequestMethod.POST)
public String borrow(#ModelAttribute LoginPerson borrows, ModelMap model) {
logger.warning(borrows.getEmail());
List list_borrows = personDAO.searchStudent(borrows.getEmail());
logger.warning(list_borrows.toString());
model.addAttribute("borrow", list_borrows);
return "result";
}
#RequestMapping(value = "/changebook", method = RequestMethod.GET)
public ModelAndView change() {
return new ModelAndView("changebook", "changing", new Person());
}
#RequestMapping(value = "/changebook", method = RequestMethod.POST)
public String changebook(#ModelAttribute("changebook") Person point, ModelMap model, HttpServletRequest request) {
model.addAttribute("point", point.getPoint());
model.addAttribute("email", point.getEmail());
logger.warning("Upper");
logger.warning(String.valueOf(point.getPoint()));
logger.warning(point.getEmail());
logger.warning(request.getParameter("email"));
if(point.getPoint() != null && request.getParameter("email") != null) {
logger.warning("It works!!!");
personDAO.changeBook(point.getPoint(), request.getParameter("email"));
}
logger.warning("Down");
return "changebook";
}
}
This is my jsp of registration:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: lado
Date: 2019-05-19
Time: 17:48
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Registration</title>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center><h2>Person Information</h2></center>
<%--<form:form method = "post" action = "/springlab_war_exploded/admin" modelAttribute="person">--%>
<form:form method ="post" modelAttribute="person">
<fieldset>
<center>
<div id="legend">
<legend class="">Registration</legend>
</div>
</center>
<center>
<div class="control-group">
<!-- id -->
<label class="control-label" for="id">Id:</label>
<div class="controls">
<input type="number" id="id" name="id" placeholder="" class="input-xlarge">
<p class="help-block">Id can contain only numbers</p>
</div>
</div>
<div class="control-group">
<!-- name -->
<label class="control-label" for="name">First name:</label>
<div class="controls">
<input type="text" id="name" name="name" placeholder="" class="input-xlarge">
<p class="help-block">First name can contain any letters or numbers, without spaces</p>
</div>
</div>
<div class="control-group">
<!-- surname -->
<label class="control-label" for="surname">Last name:</label>
<div class="controls">
<input type="text" id="surname" name="surname" placeholder="" class="input-xlarge">
<p class="help-block">Last name can contain any letters or numbers, without spaces</p>
</div>
</div>
<div class="control-group">
<!-- E-mail -->
<label class="control-label" for="email">Email:</label>
<div class="controls">
<input type="email" id="email" name="email" placeholder="" class="input-xlarge">
<p class="help-block">Please provide your Email</p>
</div>
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="pass">Password:</label>
<div class="controls">
<input type="password" id="pass" name="pass" placeholder="" class="input-xlarge">
<p class="help-block">Password should be at least 4 characters</p>
</div>
</div>
<div class="control-group">
<!-- Date -->
<label class="control-label" for="birthdate">Date:</label>
<div class="controls">
<input type="datetime" id="birthdate" name="birthdate" placeholder="" class="input-xlarge">
<p class="help-block">Please enter your birthdate</p>
</div>
</div>
<div class="control-group">
<!-- Sex -->
<label class="control-label" for="gender">Sex:</label>
<div class="controls">
<input type="text" id="gender" name="gender" placeholder="" class="input-xlarge">
<p class="help-block">Please enter your gender only M or F</p>
</div>
</div>
<div class="control-group">
<!-- Class -->
<label class="control-label" for="job">Job:</label>
<div class="controls">
<input type="text" id="job" name="job" placeholder="" class="input-xlarge">
<p class="help-block">Job can contain any letters or numbers, without spaces</p>
</div>
</div>
<div class="control-group">
<!-- Point -->
<label class="control-label" for="point">Point:</label>
<div class="controls">
<input type="number" id="point" name="point" placeholder="" class="input-xlarge">
<p class="help-block">Point can contain only numbers</p>
</div>
</div>
<div class="control-group">
<!-- Phone number -->
<label class="control-label" for="phonenumber">Phone number:</label>
<div class="controls">
<input type="tel" id="phonenumber" name="phonenumber" placeholder="" class="input-xlarge">
<p class="help-block">Please enter your phone number</p>
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success" name="submit" value="submit">Next</button>
</div>
</div>
</center>
</fieldset>
</form:form>
</body>
</html>
And my jsp register book
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%--
Created by IntelliJ IDEA.
User: lado
Date: 2019-06-02
Time: 12:51
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Register Book</title>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<%--<form:form class="form-horizontal" action='/springlab_war_exploded/login' method="post">--%>
<form:form class="form-horizontal" action="/springlab_war_exploded/login" method="post" modelAttribute="newborrow">
<fieldset>
<div id="legend">
<legend class="">Register Book</legend>
</div>
<div class="control-group">
<!-- id -->
<%--<label class="control-label" for="borrowid">Borrow Id:</label>--%>
<div class="controls">
<form:label path="id">Borrow Id:</form:label>
<form:input path="id"/>
<%--<input type="number" id="borrowid" name="borrowid" placeholder="" class="input-xlarge">--%>
<p class="help-block">Enter borrow id(it is your id)</p>
</div>
</div>
<div class="control-group">
<!-- name -->
<%--<label class="control-label" for="personid">Person Id:</label>--%>
<div class="controls">
<form:label path="studentid">Person Id:</form:label>
<form:input path="studentid"/>
<%--<input type="number" id="personid" name="personid" placeholder="" class="input-xlarge">--%>
<p class="help-block">Eneter person id(it is your id)</p>
</div>
</div>
<div class="control-group">
<!-- surname -->
<%--<label class="control-label" for="bookid">Book Id:</label>--%>
<div class="controls">
<form:label path="bookid">Book Id:</form:label>
<form:input path="bookid"/>
<%--<input type="number" id="bookid" name="bookid" placeholder="" class="input-xlarge">--%>
<p class="help-block">Enter book id</p>
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success" name="submit" value="submit">Submit</button>
</div>
</div>
</fieldset>
</form:form>
</body>
</html>
Don't need "/" while redirecting or forwarding a request.
Can you try "redirect:registerbook";
Hi guys hope you can help me, because i cant get further at the moment
I have my Controller.
#RequestMapping(value="/kundenseite", method= RequestMethod.GET)
public String kundenLogin(ModelMap model) {
if(kundeComponent.getKunde() != null) {
List<Restaurant> restaurants = restaurantService.alleRestaurants();
model.addAttribute("restaurants", restaurants);
return "kundenseite";
}else {
return "redirect:/kunde/login";
}
}
#RequestMapping(value="/kundenseite", method= RequestMethod.POST)
public String kundenLoginAnswer(ModelMap model, #ModelAttribute Restaurant restaurant) {
System.out.println(restaurant.toString());
return "kundenseite";
And my jsp file
<%# include file="common/header.jspf" %>
<div class="jumbotron text-center">
<h1>MiMiMi Lieferservice</h1>
<p>Der schnellste Lieferservice von Passpick</p>
</div>
<div style="margin-right:auto; margin-left:auto; width: 33%">
<h2 style="text-align: center">Restaurant wählen</h2>
<div class="well">
<c:forEach items="${restaurants}" var="restaurant">
<form:form modelAttribute="${restaurant}" method="post">
<div style="margin-top: 8px" class=col-sm-4 >${restaurant.name}</div>
<div style="margin-top: 8px" class=col-sm-4 >${restaurant.restaurantTyp}</div>
<button type="submit">Bestellen</button>
</form:form>
<br style="clear:both;" />
</c:forEach>
</div>
</div>
</body>
</html>
If the user presses a button i want to return a restaurant.
But i don't know how to make that happen, my thought was to use a form but i cant get it to send a complete restaurant object back
If there is no solution for this i have to write the id with the button.
You need input hidden inside the form tab as below input hidden:
<input type="hidden" name="name" value="${restaurant.name}">
<input type="hidden" name="restaurantTyp" value="${restaurant.restaurantTyp}">
I am using Spring MVC. I have a jsp page with multiple tabs. Each tab has a form. All these tabs are in a single jsp page called admin.jsp
I want to redirect the tab to itself upon POST to show errors or success message of transaction(Validation of input). What view should I return from the controller for each tab.
Controller:
#RequestMapping(value="/register", method = RequestMethod.POST)
public String registerDevice(#ModelAttribute("deviceMaster") #Validated DeviceMaster deviceMaster, BindingResult result, Model model, Locale locale) {
try {
if(result.hasErrors()){
return "admin";
}
/*CODE*/
}
#RequestMapping(value="/lock", method = RequestMethod.POST)
public #ResponseBody Status lockDevice(#ModelAttribute("adminTransaction") #Validated AdminTransaction adminTransaction, BindingResult result, Model model, Locale locale,Map<String, Object> map, HttpServletRequest request, #RequestParam #DateTimeFormat(pattern="yyyy-MM-dd") Date dueDate) {
try {
if(result.hasErrors()){
return "admin";
}
/*CODE*/
}
#RequestMapping(value="/unlock", method = RequestMethod.POST)
public #ResponseBody Status unlockDevice(#ModelAttribute("adminTransaction") #Validated AdminTransaction adminTransaction, BindingResult result, Model model, Locale locale,Map<String, Object> map, HttpServletRequest request) {
try {
if(result.hasErrors()){
return "admin";
}
/*CODE*/
}
admin.jsp
<div class="tabs" align="center">
<div class="list-center">
<ul class="tab-links">
<li class="active">Register</li>
<li>Lock</li>
<li>Unlock</li>
</ul>
</div>
<div class="tab-content">
<div id="tab1" class="tab active">
<div class="devices">
<form:form method="post" id="registerForm" modelAttribute="deviceMaster" action="/DeviceManager/admin/register">
<form:errors path="*" cssClass="plErroMessage" element="div" />
<br>
<c:if test="${not empty serverError}">
<div id="serverError" class="plErroMessage">${serverError}</div>
</c:if>
<div>
<div class="plLabelSearch">Device Id:</div>
<div class="plinput"><form:input path="deviceId" type="text" size="29"/></div>
</div>
<div>
<div class="plLabelSearch">Home Whse:</div>
<div class="plselect">
<form:select path="warehouseHome">
<form:option value="NONE" label="------- Select One -------"/>
<form:option value="TR" label="TRAINING"/>
<form:options items="${homeWhseList}" itemValue="warehouseCode" itemLabel="warehouseCode"/>
</form:select>
</div>
</div>
<br>
<br>
<div>
<div class="plLabelSearch"> </div>
<div class="plinput"><a id="btnRegister" class="abutton">Register</a></div>
<div class="plinput"><a id="btnCancel1" class="abutton">Cancel</a></div>
</div>
</form:form>
</div>
</div>
<div id="tab2" class="tab">
<div class="devices" >
<form:form method="post" id="lockForm" modelAttribute="adminTransaction" action="/DeviceManager/admin/lock">
<form:errors path="*" cssClass="plErroMessage" element="div" />
<br>
<c:if test="${not empty serverError}">
<div id="serverError" class="plErroMessage">${serverError}</div>
</c:if>
<div>
<div class="plLabelSearch">Device Id:</div>
<div class="plinput"><form:input path="deviceId" size="29"/></div>
</div>
<div>
<div class="plLabelSearch">Reason Code:</div>
<div class="plselect">
<form:select path="reasonCodeForeignKey">
<form:option value="NONE" label="------- Select One -------" />
<form:options items="${reasonList}" itemValue="reasonCode" itemLabel="reasonDesc"/>
</form:select>
</div>
</div>
<div class="hidden" >
<div>
<div class="plLabelSearch">Away Whse:</div>
<div class="plselect">
<form:select path="awayWarehouse">
<form:option value="NONE" label="------- Select One -------" />
<form:options items="${homeWhseList}" itemValue="warehouseCode" itemLabel="warehouseCode"/>
</form:select>
</div>
</div>
<div>
<div class="plLabelSearch">Due Date:</div>
<div class="plinput"><form:input id="datepicker" path="dueDate" placeholder="yyyy-mm-dd"/></div>
</div>
<div>
<div class="plLabelSearch">IT Ticket:</div>
<div class="plinput"><form:input path="itTicket" value="" size="29"/></div>
</div>
</div>
<br>
<br>
<div>
<div class="plLabelSearch"> </div>
<div class="plinput"><a id="btnLock" class="abutton">Lock</a></div>
<div class="plinput"><a id="btnCancel2" class="abutton">Cancel</a></div>
</div>
</form:form>
</div>
</div>
<div id="tab3" class="tab">
<div class="devices" >
<form:form method="post" id="unlockForm" modelAttribute="adminTransaction" action="/DeviceManager/admin/unlock">
<form:errors path="*" cssClass="plErroMessage" element="div" />
<br>
<c:if test="${not empty serverError}">
<div id="serverError" class="plErroMessage">${serverError}</div>
</c:if>
<div>
<div class="plLabelSearch">Device Id:</div>
<div class="plinput"><form:input path="deviceId" size="29"/></div>
</div>
<br>
<br>
<div>
<div class="plLabelSearch"> </div>
<div class="plinput"><a id="btnUnlock" class="abutton">Unlock</a></div>
<div class="plinput"><a id="btnCancel3" class="abutton">Cancel</a></div>
</div>
</form:form>
</div>
</div>
Handled it using jQuery and kept selected tab active on refresh with Bootstrap 3
$(document).ready(function() {
var activeTab = localStorage.getItem('activeTab');
if(activeTab){
$('.tab-links a[href="' + activeTab + '"]').tab('show');
}
$('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
localStorage.setItem('activeTab', currentAttrValue);
jQuery('.tabs ' + currentAttrValue).siblings().slideUp(400);
jQuery('.tabs ' + currentAttrValue).delay(400).slideDown(400);
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
});
I am working with Ajax/jquery to reload a division of the page after clicking on a tab, but when I am running the code new jsp is displaying...
JSP page
<ul class="nav nav-tabs tabs-up" id="friends">
<li> Contacts </li>
<li> Friends list</li>
<li>Awaiting request</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="area">
<%# include file="areas.jsp" %>
</div>
<div class="tab-pane" id="friends_list">
</div>
<div class="tab-pane urlbox span8" id="awaiting_request">
</div>
</div>
ajax call
$('[data-toggle="tabajax"]').click(function(e) {
var $this = $(this),
loadurl = $this.attr('href'),
targ = $this.attr('data-target');
$.get(loadurl, function(data) {
$(targ).html(data);
});
$this.tab('show');
return false;
});
Controller
#RequestMapping("/area")
public ModelAndView noticesAjaxRequest(ModelMap model) {
String str="a";
return new ModelAndView("areas", "str", str);
}
But when i am running this code I am only getting areas.jsp as output.
The problem is that you still have href attributes in your <a> elements.
Change <a href="/area" ...
to <a href="" ...
You have to store the link in another attribute (e.g. data-href), then.
My browser is always returning a redirect loop and I have no idea why, it looks like when I access login.html it is calling some of my methods.
Here is the login.html file:
<ui:composition
template="/templates/master.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<ui:define name="body">
<div class="container-fluid">
<div class="row-fluid">
<div class="span12">
<h:form class="form-horizontal">
<fieldset>
<legend>Bem vindo a Sergio's</legend>
<br/>
<p>Preencha os campos abaixo para entrar no sistema.</p>
<div class="control-group">
<label class="control-label" for="user">Usuário</label>
<div class="controls">
<h:inputText required="true" id="user" value="#{loginController.username}" class="input-medium" />
<h:message for="user" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Senha</label>
<div class="controls">
<h:inputSecret required="true" id="password" value="#{loginController.password}" class="input-medium"/>
<h:message for="password" />
</div>
</div>
<div class="form-actions">
<h:commandButton action="#{loginController.login()}" class="btn btn-primary" value="Entrar"/>
</div>
</fieldset>
</h:form>
<h:messages/>
</div>
</div>
</div>
</ui:define>
</ui:composition>
And here is the LoginController:
package com.erp3.gui.controllers;
import java.io.IOException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
#ManagedBean
public class LoginController {
public Boolean isLoggedIn = false;
private String username;
private String password;
private FacesMessage facesMessage;
public ExternalContext externalContent;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Boolean getIsLoggedIn() {
return isLoggedIn;
}
public void setIsLoggedIn(Boolean isLoggedIn) {
this.isLoggedIn = isLoggedIn;
}
public void login() throws IOException {
if (this.getUsername().equals("daniel") && this.getPassword().equals("123")) {
this.isLoggedIn = true;
externalContent = FacesContext.getCurrentInstance().getExternalContext();
externalContent.getSessionMap().put("loginController", this);
externalContent.redirect(externalContent.getRequestContextPath() + "/views/home.html");
} else {
this.isLoggedIn = false;
facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Usuário ou senha inválida.", username);
FacesContext.getCurrentInstance().addMessage(null, facesMessage);
externalContent.redirect(externalContent.getRequestContextPath() + "/views/login.htm");
}
}
public void logOut() throws IOException {
externalContent = FacesContext.getCurrentInstance().getExternalContext();
externalContent.getSessionMap().remove("loginController");
externalContent.redirect(externalContent.getRequestContextPath() + "/views/login.html");
}
}
I have a master.html that is my template and it is calling a top.html with this content:
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Project name</a>
<div class="btn-group pull-right">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
<i class="icon-user"></i>
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>Conta</li>
<li class="divider"></li>
<li>Sair</li>
</ul>
</div>
<div class="nav-collapse">
<ul class="nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</div>
</div>
</div>
</ui:composition>
EL expressions in template text are immediately evaluated during render response and treated as value expressions. I.e. their return value is been printed as part of HTML output. "Plain vanilla" HTML is also template text. So the following
<li>Sair</li>
will basically invoke the method, print its returned value as href URL during render response. The resulting HTML is then:
<li>Sair</li>
(yes, the href is empty because you actually returned void instead of a valid String)
But inside that method you're telling JSF to redirect to the login page and hence it ends up in an infinite loop.
This is not what you actually want. You intend to invoke it as a backing bean action method. You should be using fullworthy JSF UICommand component for this, such as <h:commandLink>.
<li><h:form><h:commandLink value="Sair" action="#{loginController.logOut()}" /></h:form></li>
This way you can also change your logOut() method to return a fullworthy navigation outcome:
public String logOut() {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
return "/views/login.html?faces-redirect=true";
}
The ExternalContext#redirect() is supposed to be used only when you want to redirect to a non-JSF URL, or when you're actually not inside an action method.
found the problem, on my top.html, I'm calling loginController.logOut() on a link and I don't know why it is auto executing, is not waiting for my click so I changed the <a> for <h:commandLink/>