JSF page ends in a redirect loop - java

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/>

Related

Spring annotation for a global scope of function variables?

I am working on a springboot+thymeleaf project. I have a page(form) which accepts user data (startdate and enddate),and a button(Check). On click of the button, backend does some validation. If there are errors, I print the errors on the textarea within the same page (below the check button). If there are no errors, then I activate another button below the textarea, to signify that the entries between the mentioned dates are ready to be stored in the database.
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<body>
<div th:fragment="contentinput">
<div class="container-md">
<a>Import Worklogs</a>
<div class="row justify-content-md-end">
<form modelAttribute = "userData">
<div class="row">
<div class="col-2">
<input type="text" class="form-control" id="txtFrom"
placeholder="start date(yyyy-mm-dd)" name="dateFrom">
</div>
<div class="col-2">
<input type="text" class="form-control" id="txtTo"
placeholder="end date(yyyy-mm-dd)" name="dateTo">
</div>
</div>
<div>
<br>
</div>
<div class="row">
<div class="row-2">
<input type="submit" class="btn btn-primary btn-sml"
value="check">
</div>
</div>
</form>
</div>
</div>
</div>
<div th:fragment="contentresult">
<div class="container-md">
<div class="row">
<div class="row">
<label style="color: black; font-weight: bold;">Issues: </label>
</div>
<br>
<div class="row">
<label for="Feedback"
th:text="'checking entries between '+ ${dateFrom}+' and '+ ${dateTo}"></label>
</div>
<div>
<textarea id="feedbackSection" name="story" cols="100" rows="10"
th:text="${styledErrors}">
</textarea>
</div>
</div>
<div>
<label th:if="${containsErrors}" style="color: green;"> There are
no issues. The entries can be imported</label>
<label
th:unless="${containsErrors}" style="color: red;"> There are
issues! Read the above for details</label>
</div>
<br>
<div class="row">
<div class="row-2">
<a th:if="${containsErrors}" type="button" th:attr="href='/importToDb'"
class="btn btn-primary btn-sml">Import</a>
<input th:unless="${containsErrors}" type="button" disabled="disabled"
value="Import">
</div>
</div>
</div>
</div>
<div th:fragment="contentmessage">
<div class="container-md">
<div class="row">
<label style="color: green; font-weight: bold;"
th:text="'Entries between '+ ${dateFrom}+' and '+ ${dateTo}+' are stored on the database'"></label>
</div>
</div>
</div>
</body>
</html>
I have run into a problem in my controller application for the import button. When I click on the import, I want to utilise the features that were used while clicking the button (check)
#GetMapping("/showform")
public String showForm(#RequestParam(value = "dateFrom", required = false) String dateFrom,
#RequestParam(value = "dateTo", required = false) String dateTo, Model model)
throws IOException, JSONException, InterruptedException, ExecutionException,
NumberFormatException, SQLException {
if (dateFrom != null && dateTo != null && !dateFrom.isBlank() && !dateTo.isBlank()) {
logger.info("inside the datefrom dateto");
CheckManager wm = prepareConfiguration(dateFrom, dateTo);
model.addAttribute("containsErrors", wm.getErrors().isEmpty());
model.addAttribute("styledErros", wm.getFormattedErrors(wm.getErrors()));
model.addAttribute("dateFrom", dateFrom);
model.addAttribute("dateTo", dateTo);
return "showform-errors"; //shows the fragment with contentinput and contentResult
} else {
logger.info("inside the validationform");
return "showform"; //only contentinput( having 2 textboxes for dates and a button)
}
}
private CheckManager prepareConfiguration(String dateFrom, String dateTo)
throws IOException, JSONException, InterruptedException, ExecutionException,
NumberFormatException, SQLException {
LocalDate from = LocalDate.parse(dateFrom, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDate to = LocalDate.parse(dateTo, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
Request req = new Request("username", "password");
List<Entry> entrylist = req.getEntryList(from,to);
// I want this info entrylist to be used globally
return new CheckManager(entryList,from,to);
}
#GetMapping("/placeinDB")
public String placeInDb(Model model) {
logger.info("Inside the db import");
//HERE I WOULD LIKE TO USE THE DATES AND THE LIST I HAD IN THE ABOVE RETURN STATEMENT
}
Problem: When I hit the endpoint(/placeinDB) I do not have the resources like entryList, datefrom, dateTo to perform some modifications.
I am hoping there is some spring annotation that could help me here. Please let me know.

submitting checkboxes with Thymeleaf + SpringBoot

I have a SpringBoot app. with this thymelaf template, that works fine when submitting:
<div class="form-group required-control">
<label for="gre">GRE</label>
<input id="gre" type="checkbox" name="gre" th:checked="*{gre}" th:onclick="submit()" />
</div>
but when I add another checkbox, It always take in account the first one, regardless which one I click
<div class="form-group required-control">
<label for="gre">GRE</label>
<input id="gre" type="checkbox" name="gre" th:checked="*{gre}" th:onclick="submit()" />
<label for="gre2">GRE2</label>
<input id="gre2" type="checkbox" name="gre2" th:checked="*{gre2}" th:onclick="submit()" />
</div>
There is no technical problem here. I think there is a problem with your submit() function, because I created a normal form and tried your same instance, and all selection combinations worked correctly.
I am adding the entity, controller and html files respectively for example.
public class Example {
private boolean gre;
private boolean gre2;
public Example() {
}
// getter/setter ...
}
#Controller
#RequestMapping("/example")
public class ExampleController {
#GetMapping("/create")
public String createExample(Model model) {
model.addAttribute("example", new Example());
return "example-form";
}
#PostMapping("/insert")
public String insertExample(Model model, Example example) {
model.addAttribute("example", example);
return "example-form";
}
}
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<div>
<form action="/example/insert" method="post" th:object="${example}">
<div class="form-group required-control">
<label for="gre">GRE</label>
<input id="gre" type="checkbox" name="gre" th:checked="*{gre}" />
<label for="gre2">GRE 2</label>
<input id="gre2" type="checkbox" name="gre2" th:checked="*{gre2}" />
</div>
<button type="submit">Submit Form</button>
</form>
</div>
</body>
</html>
If you don't want to add an attribute into the Model, you can receive checkbox condition via HttpServletRequest.
#GetMapping("/create")
public String createExample() {
return "example-form";
}
#PostMapping("/insert")
public String insertExample(User user, HttpServletRequest request) {
user.setGre(request.getParameter("gre") != null);
user.setGre2(request.getParameter("gre2") != null);
userServiceImp.updateUser(editedUser); //for example updating user in database
return "/";
}
HTML will be like this:
<form th:action="/insert" method="post">
<div class="form-group required-control">
<label>GRE</label>
<input type="checkbox" name="gre"/>
<label>GRE 2</label>
<input type="checkbox" name="gre2"/>
</div>
<button type="submit">Submit Form</button>
</form>

Java +springboot +mysql search doesnt work

import com.example.news.models.Posting;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface PostRepos extends CrudRepository<Posting, Long> {
List<Posting> findByTag(String tag);
}
_____________________________________________________________________________
#PostMapping("find")
public String find(#RequestParam String find, Map<String, Object> model){
Iterable<Posting> posts;
if(find != null && find.isEmpty()) {
posts = postRepos.findByTag(find);
} else {
posts = postRepos.findAll();
}
model.put("posts",posts);
return "redirect:/newspage";
}
______________________________________________________________________________
<div th:fragment="head" xmlns:th="http://www.w3.org/1999/xhtml">
<div class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom shadow-sm">
<h5 class="my-0 mr-md-auto font-weight-normal">ASAP NEWS</h5>
<nav class="my-2 my-md-0 mr-md-3">
<a class="p-2 text-dark" href="/homepage">Main page</a>
<a class="p-2 text-dark" href="/newspage">News</a>
<a class="p-2 text-dark" href="/newspage/addpage">Add news</a>
<a class="p-2 text-dark" href="/aboutpage">About</a>
</nav>
<a>
<form method="post" action="find">
<label>
<input type="text" placeholder="Search" name="find">
</label>
<button type="submit">Find</button>
</form>
</a>
</div>
</div>
it seems a missed ! mark before find.isEmpty()

Sending data(Objects) from Servlet to BootStrap Modal in the same page of JSP

In my application built on Java, JSP with BootStrap, and Servlet, there is the issue to send the data from Servlet to BootStrap Modal.
Based on my project, a user clicks the 'check button' in each table container and that table_id is caught in javascript and send it to Servlet with that value. Then Servlet operates on grabbing the data from the database based on its table_id. The result(orders in the code and results are displayed properly when printing out them) of the operation needed to send to the BootStrap modal section.
TableMonitor.jsp
<%# page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="/docs/4.0/assets/img/favicons/favicon.ico">
<title>Migarock Table Monitoring System</title>
<link rel="canonical"
href="https://getbootstrap.com/docs/4.0/examples/pricing/">
<!-- Bootstrap core CSS -->
<link href="../../dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="pricing.css" rel="stylesheet">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
<link href="./css/tableMonitor.css" rel="stylesheet">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
</head>
<body>
<!--
<div class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom box-shadow">
<h3 class="my-0 mr-md-auto font-weight-normal">Migarock Table Monitoring System</h3>
<a class="btn btn-outline-primary" href="#">Lock</a>
</div> -->
<div class="row">
<div class="col-2">
<div class="container">
<div class="card-deck mb-3 text-center ">
<div class="card mb-4 box-shadow ">
<div class="card-header status1">
<h3 class="my-0 font-weight-normal ">
<strong>Table_01</strong>
</h3>
</div>
<div class="card-body">
<a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
data-toggle="modal" href="#tableModal" data-table-id="1">Check</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-2">
<div class="container">
<div class="card-deck mb-3 text-center">
<div class="card mb-4 box-shadow">
<div class="card-header">
<h3 class="my-0 font-weight-normal">
<strong>Table_02</strong>
</h3>
</div>
<div class="card-body">
<a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
data-toggle="modal" href="#tableModal" data-table-id="2">Check</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-2">
<div class="container">
<div class="card-deck mb-3 text-center">
<div class="card mb-4 box-shadow">
<div class="card-header status2">
<h3 class="my-0 font-weight-normal">
<strong>Table_03</strong>
</h3>
</div>
<div class="card-body">
<a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
data-toggle="modal" href="#tableModal" data-table-id="3">Check</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-2">
<div class="container">
<div class="card-deck mb-3 text-center">
<div class="card mb-4 box-shadow">
<div class="card-header">
<h3 class="my-0 font-weight-normal">
<strong>Table_04</strong>
</h3>
</div>
<div class="card-body">
<a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
data-toggle="modal" href="#tableModal" data-table-id="4">Check</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-2">
<div class="container">
<div class="card-deck mb-3 text-center">
<div class="card mb-4 box-shadow">
<div class="card-header">
<h3 class="my-0 font-weight-normal">
<strong>Table_05</strong>
</h3>
</div>
<div class="card-body">
<a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
data-toggle="modal" href="#tableModal" data-table-id="5">Check</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-2">
<div class="container">
<div class="card-deck mb-3 text-center">
<div class="card mb-4 box-shadow ">
<div class="card-header status3">
<h3 class="my-0 font-weight-normal">
<strong>Table_06</strong>
</h3>
</div>
<div class="card-body">
<a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
data-toggle="modal" href="#tableModal" data-table-id="6">Check</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="tableModal" tabindex="1" role="dialog"
aria-labelledby="modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title" id="modal">Table Status</h2>
<button type="button" class="close" data-dismiss="modal"
aria-label="close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="controlBar">
<div class="row">
<div class="col-8" style="text-align: left;">
<button type="button" class="btn btn-outline-success btn-lg"
data-dismiss="modal">Add item</button>
<button type="button" class="btn btn-outline-secondary btn-lg"
data-dismiss="modal">Change Status</button>
</div>
<div class="col-4" style="text-align: right; padding-right: 10%;">
<button type="button" class="btn btn-outline-warning btn-lg"
data-dismiss="modal">Help</button>
<button type="button" class="btn btn-outline-info btn-lg"
data-dismiss="modal">Bill</button>
</div>
</div>
<div>
<div class="modal-body">
<h3>My name is ${test}</h3>
<!-- <form action="./evaluationRegisterAction.jsp" method="post"> -->
<div class="scrollbar scrollbar-primary">
<!-- <div> -->
<table class="table">
<thead>
<tr style="text-align: center;">
<th scope="col"><input type="checkbox"
class="select-all checkbox" name="select-all" /></th>
<th scope="col">OrderTime</th>
<th scope="col">Item</th>
<th scope="col">QTY</th>
<th scope="col">Price</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
<c:out value="${requestScope.orders}">
<c:forEach items="${orders}" var="order">
<tr style="text-align: center;">
<td style="text-align: center;">
<div class="form-check">
<input type="checkbox" class="select-item checkbox"
name="select-item">
</div>
</td>
<td><span id="orders"></span> ${order.getTimeStamp()}</td>
<td>{order.getOrderItem()}</td>
<td>{order.getOrderQty()}</td>
<td>{order.getOrderPrice()}</td>
<td>{order.getOrderStatus()}</td>
<td><a class="btn btn-light btn-sm mx-1 mt-2"
data-toggle="modal" href="#changeStatus">Ordered</a> <!-- <a class="btn btn-dark btn-sm mx-1 mt-2" data-toggle="modal"
href="#changeStatus">Delivered</a> -->
</td>
</tr>
</c:forEach>
</c:out>
</tbody>
</table>
</div>
</div>
<div>
<table class="table">
<tr style="text-align: center;">
<td colspan="3">
<h4>Total</h4>
</td>
<td colspan="3">
<h4>(total)</h4>
</td>
</tr>
</table>
</div>
<div class="controlBar">
<div class="row">
<div class="col-6" style="text-align: left;">
<button type="button" class="btn btn-danger btn-lg"
data-dismiss="modal">Close Session</button>
</div>
<div class="col-6"
style="text-align: right; padding-right: 10%;">
<button type="button" class="btn btn-outline-danger btn-lg"
data-dismiss="modal">Close Window</button>
</div>
</div>
</div>
</div>
<!-- </form> -->
</div>
</div>
</div>
</div>
<footer class="pt-4 my-md-5 pt-md-5 border-top"> </footer>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script>
window.jQuery
|| document
.write('<script src="../../assets/js/vendor/jquery-slim.min.js"><\/script>')
</script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script>
Holder.addTheme('thumb', {
bg : '#55595c',
fg : '#eceeef',
text : 'Thumbnail'
});
</script>
<script>
$(function() {
//button select all or cancel
$("#select-all").click(function() {
var all = $("input.select-all")[0];
all.checked = !all.checked
var checked = all.checked;
$("input.select-item").each(function(index, item) {
item.checked = checked;
});
});
//button select invert
$("#select-invert").click(function() {
$("input.select-item").each(function(index, item) {
item.checked = !item.checked;
});
checkSelected();
});
//button get selected info
$("#selected").click(
function() {
var items = [];
$("input.select-item:checked:checked").each(
function(index, item) {
items[index] = item.value;
});
if (items.length < 1) {
alert("no selected items!!!");
} else {
var values = items.join(',');
console.log(values);
var html = $("<div></div>");
html.html("selected:" + values);
html.appendTo("body");
}
});
//column checkbox select all or cancel
$("input.select-all").click(function() {
var checked = this.checked;
$("input.select-item").each(function(index, item) {
item.checked = checked;
});
});
//check selected items
$("input.select-item").click(function() {
var checked = this.checked;
console.log(checked);
checkSelected();
});
//check is all selected
function checkSelected() {
var all = $("input.select-all")[0];
var total = $("input.select-item").length;
var len = $("input.select-item:checked:checked").length;
console.log("total:" + total);
console.log("len:" + len);
all.checked = len === total;
}
});
$('#tableModal')
.on(
'show.bs.modal',
function(e) {
var tableID = $(e.relatedTarget).data('table-id');
console.log("test: ", tableID)
$(e.currentTarget).find('input[name="tableID"]')
.val(tableID);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("response").value = xhttp.responseText;
}
};
xhttp.open("POST", "TableMonitor", true);
xhttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xhttp.send("tableId=" + tableID);
var orders = $(this).data('orders');
$('#orders').html(orders);
});
</script>
</body>
</html>
TableMonitor.java(Servlet)
package servlets;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import brokers.TableBrokder;
import model.Order;
/**
* Servlet implementation class TableMonitor
*/
#WebServlet("/TableMonitor")
public class TableMonitor extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TableMonitor() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
getServletContext().getRequestDispatcher("/TableMonitor.jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String table_id = request.getParameter("tableId");
String action = request.getParameter("action");
System.out.println("servlet: " + table_id);
List<Order> orders = null;
TableBrokder tb = new TableBrokder();
try {
orders = tb.getOrderAll(Integer.parseInt(table_id));
} catch (NumberFormatException | SQLException e) {
e.printStackTrace();
}
for (int i = 0; i < orders.size(); i++) {
orders.get(i).toString();
}
// response.sendRedirect("TableMonitor");
RequestDispatcher dispatcher = request.getRequestDispatcher("/TableMonitor.jsp");
request.setAttribute("orders", orders);
request.setAttribute("test", "test");
dispatcher.forward(request, response);
}
}
Even though I google it but didn't get clear answers. Could you help me with this issue?
Looks like you are making an ajax call in your js but in your servlet you are not returning the response. I highly recommend checking out this answer on how to make ajax calls with servlets.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String table_id = request.getParameter("tableId");
String action = request.getParameter("action");
System.out.println("servlet: " + table_id);
List<Order> orders = null;
TableBrokder tb = new TableBrokder();
try {
orders = tb.getOrderAll(Integer.parseInt(table_id));
} catch (NumberFormatException | SQLException e) {
e.printStackTrace();
}
for (int i = 0; i < orders.size(); i++) {
orders.get(i).toString();
}
//convert your list of orders to json
String json = new Gson().toJson(orders);
//add json to response
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
When you make ajax calls you won't be able to do things like this:
request.setAttribute("orders", orders);
request.setAttribute("test", "test");
Because when you call this servlet url through ajax, you are not loading the jsp page again so the HttpServletRequest won't be passed to the jsp page. Hope this helps understand it some more.

Spring integration Javascript

On every page of my web application, I've a common header.
header.jsp :
<link rel="stylesheet" type="text/css" href="stylesheets/320x480/portrait/header.css" />
<div data-theme="b" data-role="header">
<div class="ui-grid-b">
<div class="ui-block-a">
<a id="backButton" data-role="button" data-icon="arrow-l" data-ajax="false">
<spring:message code="backButton"/>
</a>
</div>
<div class="ui-block-b">
<h3>GeoAccessibility</h3>
</div>
<div class="ui-block-c">
<div data-role="navbar">
<ul>
<li id="french">
<a id="fr" href="?language=fr" data-role="button" data-transition="fade" class="ui-btn-active">fr</a>
</li>
<li id="english">
<a id="en" href="?language=en" data-role="button" data-transition="fade">eng</a>
</li>
</ul>
</div>
</div>
</div>
</div>
Address.jsp :
<script>
$('#fr').click(function(){
alert("hello");
//treatment to follow
});
$(document).ready(function(){
alert("here");
$('#backButton').attr("href","/fdfds");
});
</script>
<body>
<div data-role="page" data-ajax="false" id="page1">
<jsp:include page="header.jsp"></jsp:include>
<div data-role="content">
<forms:form method="post" modelAttribute="address" action="/address">
<spring:message code="streetName" var="streetName" />
<forms:input path="streetName" id="streetName" placeholder="${streetName}" />
<spring:message code="streetNumber" var="streetNumber" />
<forms:input path="streetNumber" id="streetNumber" placeholder="${streetNumber}" />
<!-- Rest of the form -->
<button id="submitButton" type="submit" data-mini="true" data-inline="true" data-theme="b" data-ajax="false"><spring:message code="adressValidateBtn" /></button>
</forms:form>
</div>
</div>
The Address controller for getting of Address.jsp or post the form :
#Controller
public class AddressController {
#RequestMapping(value="/address",method=RequestMethod.GET)
public ModelAndView init(
#RequestParam(value="language",required=false,defaultValue="fr") String language){
Locale locale = new Locale(language);
String[] isoCountries = locale.getISOCountries();
Map<String,String> treeMap = new TreeMap<String,String>();
for(String isoCountry : isoCountries){
Locale countryLoc = new Locale(language, isoCountry);
String name = countryLoc.getDisplayCountry(locale);
if(!"".equals(name)){
treeMap.put(name,name);
}
}
Map<String,String> tree = new TreeMap<String,String>(treeMap);
ModelAndView modelAndView = new ModelAndView("address");
modelAndView.addObject("address",new Address());
modelAndView.addObject("countriesList", tree);
modelAndView.addObject("previousPage","/index");
return modelAndView;
}
#RequestMapping(value="/address",method=RequestMethod.POST)
public ModelAndView validate( #RequestParam(value="language",required=false,defaultValue="fr") String language,#ModelAttribute("address") Address address, BindingResult result){
boolean ok = true;
//check-up data
return new ModelAndView("address");
}
}
As you see in the 'init' method of 'AddressController' class, I've added an object 'previousPage' having the 'url' value of the previous page. I would like to retrieve the 'previousPage' attribute in my address.jsp to change the 'href' attribute of my 'back' button(sitting in the header.jsp). How to do ?
Thank you
like every other attribute:
${previousPage}
I don't see any reason to use JavaScript to initialize the href of your link. You can initialize it directly using
<a href="${previousPage}" ...>

Categories