How to add popup window on Spring + Thymeleaf - java

I do have some problems on how will I implement a pop-up on a link. I'm currently using Spring-boot with Thymeleaf
I'm planning to implement the pop up window upon pressing the "Edit" button. Currently it shows on a new tab.
Here's the HTML:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head th:replace="template::header">
</head>
<body>
<div class="d-flex" id="wrapper">
<div th:insert="template::sidebar">
</div>
<div id="page-content-wrapper">
<nav th:insert="template::navbar">
</nav>
<div class="container-fluid">
<h1> Employee List </h1>
Add new Employee<br/><br/>
<table border="1" cellpadding="10">
<thead>
<tr>
<th> Employee Name </th>
<th> Designation </th>
<th> Credentials </th>
<th> Department </th>
<th> Image </th>
<th> Image filename </th>
<th> Actions </th>
</tr>
</thead>
<tbody>
<tr th:each="employee: ${employees}">
<td th:text="${employee.name}"></td>
<td th:text="${employee.designation}"></td>
<td th:text="${employee.credentials}"></td>
<td th:text="${employee.departmentName == null} ? 'Empty' : ${employee.departmentName}"></td>
<td><img th:src="#{'/uploads/' + ${employee.image_fn}}"/></td>
<td th:text="${employee.image_fn}"></td>
<td>
<a th:href="#{'/admin/employees/edit/' + ${employee.name}}" th:target="_blank"><button type="button" class="btn btn-primary">Edit</button></a> <!--Edit Button must launch a pop up window, but is currently launching only on new tab-->
<!-- -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#empDeleteConfirm">Delete</button>
<a th:href="#{'/admin/employees/imageUpload/' + ${employee.name}}">Upload Image</a>
</td>
<div class="modal fade" id="empDeleteConfirm" tabindex="-1" role="dialog" aria-labelledby="empDeleteConfirm" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="empDeleteConfirm">Are you sure?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Do you want to delete this employee?
</div>
<div class="modal-footer">
<a th:href="#{'/admin/employees/delete/' + ${employee.name}}"><button type="button" class="btn btn-primary">Delete</button></a>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</tr>
</tbody>
</table>
<!-- Modal -->
</div>
</div>
</div>
<script type="text/javascript" th:src="#{/js/jquery-3.4.1.min.js}"></script>
<script type="text/javascript" th:src="#{/js/bootstrap.js}"></script>
</body>
</html>
Here's the window to be shown on a pop up window:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head th:replace="template::header">
</head>
<body>
<div class="d-flex" id="wrapper">
<!-- <div th:insert="template::sidebar">
</div> -->
<div id="page-content-wrapper">
<!-- <nav th:insert="template::navbar">
</nav> -->
<div class="container-fluid" align="center">
<h1> Edit Employee </h1>
<form action="#" th:action="#{/admin/employees/update}" th:object="${employee}" method="post" th:fragment="empEdit">
<table border="0" cellpadding="10">
<td><input type="hidden" th:field="*{name}"/></td>
<td><input type="hidden" th:field="*{image_fn}"/></td>
<tr>
<td> Designation: </td>
<td><input type="text" th:field="*{designation}"/></td>
</tr>
<tr>
<td> Credentials: </td>
<td><input type="text" th:field="*{credentials}"/></td>
</tr>
<tr>
<select th:field="*{department}">
<option th:each="department: ${departments}" th:value="${department.name}" th:text="${department.description}"></option>
</select>
</tr>
<tr>
<td><button type="submit">Save</button></td>
</tr>
</table>
</form>
</div>
</div>
</div>
<script type="text/javascript" th:src="#{/js/jquery-3.4.1.min.js}"></script>
<script type="text/javascript" th:src="#{/js/bootstrap.js}"></script>
</body>
</html>
Using these controller:
import com.ppt.contentmanagementsystem.dao.DepartmentDAO;
import com.ppt.contentmanagementsystem.dao.EmployeeDAO;
import com.ppt.contentmanagementsystem.model.Department;
import com.ppt.contentmanagementsystem.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
#Controller
public class EmployeeVC {
#Autowired
EmployeeDAO employeeDAO;
#Autowired
DepartmentDAO departmentDAO;
#GetMapping("/admin/employees")
public String employeesHomePage(Model model){
List<Employee> employees = employeeDAO.getAllEmployees();
model.addAttribute("employees", employees);
model.addAttribute("title", "Employees");
return "employeeHome";
}
#GetMapping("/admin/employees/new")
public String newEmployeePage(Model model){
Employee employee = new Employee();
List<Department> departments = departmentDAO.getAllDepartments();
model.addAttribute("employee", employee);
model.addAttribute("departments", departments);
return "employeeNew";
}
#PostMapping("/admin/employees/new")
public String addEmployeePage(#ModelAttribute("employee") Employee employee){
employeeDAO.addEmployee(employee);
return "redirect:/admin/employees";
}
#GetMapping("/admin/employees/edit/{id}")
public String editEmployeePage(Model model, #PathVariable String id){
Optional<Employee> eopt = employeeDAO.getEmployee(id);
Employee employee = eopt.get();
List<Department> departments = departmentDAO.getAllDepartments();
model.addAttribute("employee", employee);
model.addAttribute("departments", departments);
model.addAttribute("title", "Employee Edit");
return "employeeEdit";
}
#GetMapping("/admin/employees/imageUpload/{id}")
public String uploadEmployeeImagePage(Model model, #PathVariable String id){
Optional<Employee> eopt = employeeDAO.getEmployee(id);
Employee employee = eopt.get();
model.addAttribute("employee", employee);
model.addAttribute("title", "Employee Image");
return "employeeImage";
}
#PostMapping("/admin/employees/imageUpload")
public String updateEmployeeImage(#ModelAttribute("employee") Employee employee, #RequestParam("imageFile") MultipartFile imageFile) throws IOException{
employeeDAO.saveEmployeeImage(employee, imageFile);
return "redirect:/admin/employees";
}
#PostMapping("/admin/employees/update")
public String updateEmployeePage(#ModelAttribute("employee") Employee employee){
employeeDAO.updateEmployee(employee);
return "redirect:/admin/employees";
}
#GetMapping("/admin/employees/delete/{id}")
public String deleteEmployeePage(#PathVariable String id){
employeeDAO.deleteEmployee(id);
return "redirect:/admin/employees";
}
}

For modal window you should add the JavaScript code to your template as described here
Thymeleaf documentation 13.4 Textual parser-level comment blocks: removing code
Simple implementation of the modal window in js is:
<!DOCTYPE html>
<html> <head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style> body {font-family: Arial, Helvetica, sans-serif;}
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
padding-top: 100px;
/* Location of the box */
left: 0; top: 0; width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
background-color: rgb(0,0,0);
/* Fallback color */
background-color: rgba(0,0,0,0.4);
/* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover, .close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() { modal.style.display = "block"; }
// When the user clicks on <span> (x), close the modal
span.onclick = function() { modal.style.display = "none"; }
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
} }
</script>
</body> </html>

I've found a textual solution here: Spring MVC: Open link in new browser window in handler method
And a tutorial explaining Javascripts window.open function
https://www.youtube.com/watch?v=G83c-ZqZ7pk
Answering the question on how to open a new browser-window (popup) when clicked on an element or link.

Related

Why is my JPA update (edit) option not working?

I am trying to create a CRUD with JPA. Both the insert new record and delete record work. But once I go to update, which is the line ctrl.edit(cats) it returns error: org.apache.jasper.JasperException: java.lang.NullPointerException
Could someone please review my code and advise if there is something I am missing? I have created entities and controllers with JPA.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="entities.Categories"%>
<%#page import="controller.CategoriesJpaController"%>
<%#page import="java.util.List"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CATEGORIAS</title>
<script>
function cargar(id,nom,des)
{
document.modalito.txtcatid.value = id;
document.modalito.txtcatname.value = nom;
document.modalito.txtcatdes.value = des;
}
</script>
</head>
<body>
<%
HttpSession sesion = request.getSession();
//validar que solo si hay sesion activa pueda entrar
//la unica sesion es usuario y nivel
if(sesion.getAttribute("usuario")==null && sesion.getAttribute("nivel")==null)
{
response.sendRedirect("../login/index_login.jsp");
}
if(sesion.getAttribute("usuario")!=null && sesion.getAttribute("nivel")!=null)
{
String useruser = sesion.getAttribute("usuario").toString();
String nivel = sesion.getAttribute("nivel").toString();
%>
<nav class="navbar navbar-expand navbar-dark bg-dark static-top">
<hr>
<p style="color:white; font-size: 20px;"> Bienvenido <%=useruser%> (Nivel: <%=nivel%>) | <a style="color:white;" href="${pageContext.request.contextPath}/index.jsp"> | Home | </a></p>
<hr>
</nav>
<%
}
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setDateHeader ("Expires", 0);
%>
<br><br>
<h3 align="center">Formulario Categorias</h3>
<hr>
<button style="margin-left: 45%;" type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#miModal">
Ingresar Nuevo
</button>
<br><br>
<pre align="center">CONTENIDO DE LA TABLA PRODUCTOS</pre>
<br>
<%
List <Categories> ls;
CategoriesJpaController ctrl = new CategoriesJpaController();
Categories cats = new Categories();
ls = ctrl.findCategoriesEntities();
if(request.getParameter("btnGuardar")!=null || request.getParameter("btnMod")!=null || request.getParameter("btnEliminar")!=null)
{
//guardar en un objeto producto lo del form
cats.setCategoryID(Integer.parseInt(request.getParameter("txtcatid")));
cats.setCategoryName(request.getParameter("txtcatname"));
cats.setDescription(request.getParameter("txtcatdes"));
}
if(request.getParameter("btnGuardar")!=null)
{
ctrl.create(cats);
out.print("<script>alert('Exito al insertar');window.location.href = 'vCategoria.jsp';</script>");
ls=ctrl.findCategoriesEntities();
}
else if(request.getParameter("btnMod")!=null)
{
ctrl.edit(cats);
out.print("<script>alert('Exito al modificar');window.location.href = 'vCategoria.jsp';</script>");
ls=ctrl.findCategoriesEntities();
}
else if(request.getParameter("btnEliminar")!=null)
{
ctrl.destroy(cats.getCategoryID());
out.print("<script>alert('Exito al eliminar');window.location.href = 'vCategoria.jsp';</script>");
ls=ctrl.findCategoriesEntities();
}
%>
<div style="width: 700px; position: relative; margin-left: 27%;">
<table border="1" class="table">
<thead class="thead-dark">
<tr>
<th class="text-center">ID CATEGORIA</th>
<th class="text-center">NOMBRE CATEGORIA</th>
<th class="text-center">DESCRIPCIÓN</th>
</tr>
</thead>
<tbody>
<%
for(Categories c : ls)
{
%>
<tr>
<td class="text-center"><%= c.getCategoryID()%>
<a href="javascript:cargar('<%= c.getCategoryID() %>','<%= c.getCategoryName()%>','<%= c.getDescription() %>')">
<img src="../recursos/editar.jpg" width="25px" height="25px" data-toggle="modal" data-target="#miModal">
</a>
</td>
<td class="text-center"><%= c.getCategoryName() %></td>
<td class="text-center"><%= c.getDescription() %></td>
</tr>
<%
}
%>
</tbody>
</table>
</div>
</body>
<!--Este es el formulario modal-->
<div class="modal fade" id="miModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Formulario de Registro</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<form action="vCategoria.jsp" method="POST" name="modalito">
<input type="text" name="txtcatid" placeholder="ID Categoria" class="form-control" /><br>
<input type="text" name="txtcatname" placeholder="Nombre Categoria" class="form-control" /><br>
<input type="text" name="txtcatdes" placeholder="Descripción" class="form-control" /><br>
<input type="submit" name="btnGuardar" class="btn btn-primary" value="Guardar"/>
<input type="submit" name="btnMod" class="btn btn-info" value="Modificar"/>
<input type="submit" name="btnEliminar" class="btn btn-danger" value="Eliminar"/>
<input type="hidden" value="nuevo" name="opcion" /><br>
</form>
</div>
</div>
</div>
</div>
</div>
<!--Hasta aquí el modal-->
</body>
Sorry, in order to post as Resolved, I found the answer here: es.stackoverflow.com/a/104830 it is in Spanish but it did help.
I simply initiated my OneToMany List on my Entity in question and that resolved it.
#OneToMany(mappedBy = "categoryID") private List<Products> productsList = new
ArrayList<Products>

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.

403 error - CSRF token in modal window

I'm working on a Spring Boot + Bootstrap project.
I've created a modal window to confirm the removal of itens, but after I added Spring Security to the project, the modal stopped working.
How can I properly configure the CSRF token in a modal window?
I have tried some approaches, with no success.
I get the following error when deleting itens:
There was an unexpected error (type=Forbidden, status=403). Invalid
CSRF Token 'null' was found on the request parameter '_csrf' or header
'X-CSRF-TOKEN'.
Thanks for the help!
confirmRemove.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<div class="modal fade" id="confirmRemove" tabindex="-1"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog">
<form th:attr="data-url-base=#{/restaurants}" method="POST">
<input type="hidden" name="_method" value="DELETE" />
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Você tem certeza?</h4>
</div>
<div class="modal-body">
<span>Are you sure you want to delete this restaurant?</span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Delete</button>
</div>
</div>
</form>
</div>
</div>
</html>
restaurantpoll.js
$('#confirmRemove').on(
'show.bs.modal',
function(event) {
var button = $(event.relatedTarget);
var codeRestaurant = button.data('id');
var nameRestaurant = button.data('name');
var modal = $(this);
var form = modal.find('form');
var action = form.data('url-base');
if (!action.endsWith('/')) {
action += '/';
}
form.attr('action', action + codeRestaurant);
modal.find('.modal-body span').html(
'Are you sure you want to delete <strong>'
+ nameRestaurant + '</strong>?')
});
RestaurantController (only the relevant part)
package com.matmr.restaurantpoll.controller;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.matmr.restaurantpoll.exception.RestaurantNotFoundException;
import com.matmr.restaurantpoll.model.Category;
import com.matmr.restaurantpoll.model.Restaurant;
import com.matmr.restaurantpoll.model.filter.RestaurantFilter;
import com.matmr.restaurantpoll.service.RestaurantService;
#Controller
#RequestMapping("/restaurants")
public class RestaurantController {
#Autowired
private RestaurantService restaurantService;
#Autowired
public RestaurantController(RestaurantService restaurantService) {
this.restaurantService = restaurantService;
}
#RequestMapping(value = "{id}", method = RequestMethod.DELETE)
public String delete(#PathVariable Long id, RedirectAttributes attributes) throws RestaurantNotFoundException {
restaurantService.deleteById(id);
attributes.addFlashAttribute("message", "The restaurant was successfully deleted.");
return "redirect:/restaurants";
}
}
restaurantList.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://ultraq.net.nz/thymeleaf/layout"
layout:decorator="Layout">
<head>
<title>Pesquisa de Restaurantes</title>
</head>
<section layout:fragment="conteudo">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="clearfix">
<h1 class="panel-title liberty-title-panel">Pesquisa de
Restaurantes</h1>
<a class="btn btn-link liberty-link-panel"
th:href="#{/restaurants/new}">Cadastrar Novo Restaurante</a>
</div>
</div>
<div class="panel-body">
<form method="GET" class="form-horizontal"
th:action="#{/restaurants}" th:object="${filter}">
<div layout:include="MensagemGeral"></div>
<div layout:include="MensagemErro"></div>
<div class="form-group">
<div class="col-sm-4">
<div class="input-group">
<input class="form-control"
placeholder="Qual restaurante você está procurando?"
autofocus="autofocus" th:field="*{name}"></input> <span
class="input-group-btn">
<button type="submit" class="btn btn-default">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</div>
</div>
</form>
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th class="text-left col-md-1">#</th>
<th class="text-left col-md-2">Nome</th>
<th class="text-left col-md-3">Descrição</th>
<th class="text-left col-md-2">Categoria</th>
<th class="col-md-1"></th>
</tr>
</thead>
<tbody>
<tr th:each="restaurant : ${restaurants}">
<td class="text-left" th:text="${restaurant.id}"></td>
<td class="text-left" th:text="${restaurant.name}"></td>
<td class="text-left" th:text="${restaurant.description}"></td>
<td class="text-left"
th:text="${restaurant.category.description}"></td>
<td class="text-center"><a class="btn btn-link btn-xs"
th:href="#{/restaurants/{id}(id=${restaurant.id})}"
title="Editar" rel="tooltip" data-placement="top"> <span
class="glyphicon glyphicon-pencil"></span>
</a> <a class="btn btn-link btn-xs" data-toggle="modal"
data-target="#confirmRemove"
th:attr="data-id=${restaurant.id}, data-name=${restaurant.name}"
title="Excluir" rel="tooltip" data-placement="top"> <span
class="glyphicon glyphicon-remove"></span>
</a></td>
</tr>
<tr>
<td colspan="5" th:if="${#lists.isEmpty(restaurants)}">Nenhum
restaurante foi encontrado!</td>
</tr>
</tbody>
</table>
</div>
</div>
<div layout:include="confirmRemove"></div>
</div>
</section>
</html>
Adding th:action="#{/restaurants}" to the modal's form tag did the trick:
<form th:action="#{/restaurants}" th:attr="data-url-base=#{/restaurants}" method="POST">

Spring MVC -- Handle multiple forms in a single jsp

I have been searching around for reason why I have error Neither BindingResult nor plain target object for bean name 'addItemForm' available as request attribute but can't understand.
The page is loading fine but if I click on Add new item button, a lightbox containing a form appears, I click on Add item and I got same error as above but bean name is searchForm.
The controller looks fine, I think there is a binding problem between the view and the form. Can someone explain please?
Also, it is able to add new items to database, so the POST method is working, but the view returns errors ..
JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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=ISO-8859-1">
<title>Admin View</title>
<style type="text/css">
body{margin:0, padding:0}
#body{
text-align: center;
top: 3%;
}
.table2{
border-spacing: 5%;
}
.table1 {
border-collapse: collapse;
width: 80%;
}
.table1 tr:nth-child(odd) td{
background-color: #ffffff;
}
.table1 tr:nth-child(even) td{
background-color: #4da6ff;
}
.table1 td, th {
text-align: left;
border: 1px solid green;
}
.black_overlay{
display: none;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.white_content {
display: none;
position: absolute;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
padding: 16px;
border: 16px solid orange;
background-color: white;
z-index:1002;
overflow: auto;
}
</style>
</head>
<body>
<div id="body">
<h3>This is the Administrator View</h3>
<p>From here, you can search for items in the database, view, add new items and delete items from database</p>
<table align="center">
<tr>
<td>
<form:form action="AdminView" method="POST" commandName="searchForm">
<form:input path="KeyWordSearch" size="40"/>
<input type="submit" name="search" value="Search Store"/>
</form:form>
</td>
<td><button onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">Add new item</button></td>
</tr>
</table>
<br>
<c:if test="${not empty itemList}">
<table class="table1" align="center">
<tr>
<th>Item Name</th>
<th>Date added</th>
<th>Item Description</th>
<th>View Details</th>
</tr>
<c:forEach var="item" items="${itemList}">
<tr>
<td>${item.itemName}</td>
<td>${item.itemAdded}</td>
<td>${item.itemDescription}</td>
<td>View</td>
</tr>
</c:forEach>
</table>
</c:if>
</div>
<div id="light" class="white_content">
<h2 align="center">Add new item to Store</h2>
<form:form action="AdminView" method="POST" commandName="addItemForm">
<table align="left">
<tr>
<th style="border:0">Item name</th>
<td><form:input path="ItemName"/></td>
</tr>
<tr>
<th style="border:0">Item location</th>
<td><form:input path="ItemLocation"/></td>
</tr>
<tr>
<th style="border:0">Item Description</th>
<td><form:textarea path="ItemDescription"/></td>
</tr>
<tr>
<td><input type="submit" name="add" value="Add Item"/></td>
</tr>
</table>
</form:form>
Close
</div>
<div id="fade" class="black_overlay"></div>
</body>
</html
This is the Controller:
package com.test.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.test.forms.AddNewItemForm;
import com.test.forms.SearchForm;
import com.test.models.items.ItemIF;
import com.test.transaction.TransactionFactory;
/**
* Handles requests for Admin View page
* #author Trung
*
*/
#Controller
#RequestMapping (value = "/AdminView")
public class AdminViewController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView adminForm(Model model){
SearchForm searchForm = new SearchForm();
model.addAttribute("searchForm", searchForm);
AddNewItemForm addItemForm = new AddNewItemForm();
model.addAttribute("addItemForm", addItemForm);
return new ModelAndView("AdminView");
}
#RequestMapping (params = "search", method = RequestMethod.POST)
public String processingSearchStore(#ModelAttribute("searchForm") SearchForm searchForm, Model model){
List<ItemIF> relatedItems = null;
TransactionFactory transaction = new TransactionFactory();
relatedItems = transaction.retrieveItemByName(searchForm.getKeyWordSearch());
if (relatedItems.isEmpty()){
System.out.println("okay, there isn't any item that is matched your criteria");
} else {
model.addAttribute("itemList", relatedItems);
}
return "AdminView";
}
#RequestMapping(params = "add", method = RequestMethod.POST)
public ModelAndView addNewItemForm(#ModelAttribute("addItemForm") AddNewItemForm addItemForm){
TransactionFactory transaction = new TransactionFactory();
String itemName = addItemForm.getItemName();
String itemLocation = addItemForm.getItemLocation();
String itemDescription = addItemForm.getItemDescription();
transaction.insertItem(itemName, itemLocation, itemDescription);
return new ModelAndView("AdminView");
}
}
You need a BindingResult as parameter in both post methods after the #ModelAttribute parameter, like this:
public String processingSearchStore(#ModelAttribute("searchForm") SearchForm searchForm, BindingResult result, Model model){

How to post form login using jsoup?

i want to login in here
source code
<HTML><HEAD><TITLE>:: Dhaka Electric Supply Company Limited (DESCO)::</TITLE>
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<META http-equiv=Pragma content=no-cache>
<META http-equiv=imagetoolbar content=no>
<META content="Home Page of Dhaka Electric Supply Company Limited" name=description>
<META content="MSHTML 6.00.2900.2180" name=GENERATOR>
<style type="text/css">
img{
border:0px;
}
</style>
<script type="text/javascript" src="js/ajax-dynamic-content.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript" src="js/ajax-tooltip.js"></script>
<link rel="stylesheet" href="css/ajax-tooltip.css" media="screen" type="text/css">
<link rel="stylesheet" href="css/ajax-tooltip-demo.css" media="screen" type="text/css">
<LINK media=all href="css/global.css" type=text/css rel=stylesheet>
</HEAD>
<BODY>
<DIV id=over style="DISPLAY: none"></DIV>
<DIV class=baselayout>
<DIV class=pagetopshadow></DIV>
<DIV class=basebg>
<DIV class=pageleft></DIV>
<DIV class=pagecenter>
<DIV id=Header>
</DIV>
<DIV id=Menu>
</DIV>
<DIV id=HomeContent>
<DIV class=right>
<DIV class=homeintro>
<div style="padding-top: 0px;">
<script>
function checkLogin()
{ if( document.login.username.value == '')
{
alert( 'Please enter your account number' );
return false;
}return true;
}
alert('Payments through VISA and Master Card are stopped by DBBL. only DBBL Nexus card is allowed.');
</script>
<form NAME='login' METHOD='POST' ACTION='authentication.php'>
<table width="350" height="181"cellpadding='0' cellspacing='0' border='0' style="border:#e5e5e5 0px solid; BACKGROUND: url(css/images/top9.png) no-repeat left top;" align="center">
<tr> <td rowspan="6" style="padding-left:15px;"><img src="css/images/groupperms.gif" width="50" height="50"><td></tr>
<tr>
<td colspan="2" height="50"></td>
</tr>
<tr>
<td nowrap><span class="textcolor1">Account No. </span></td>
<td><input type='text' name='username' style="border:#cacaca 2px solid; color:#000099;" value=''></td></tr>
<tr>
<td> <a class="uiTooltip" href="#" onMouseOver="ajax_showTooltip(window.event,'tooltip/help.html',this);return false" onMouseOut="ajax_hideTooltip()">Help</a></td>
<td><input name="login" type='submit' value='Login' style="width:80px; font-family:Arial, Helvetica, sans-serif; font-weight:bold; color:#FFFFFF; border:#000000 2px solid; cursor:pointer; background-color: #1b4585;" border="0" align="right" title="Login" onClick="return checkLogin();"/></td>
</tr>
</table>
</form>
<table width="630" border="0" cellspacing="2" cellpadding="2" align="center" bgcolor="#FFFFFF" bordercolor="#FFFFFF">
<tr>
<td width="80"></td>
<td><img src="images/right_3.gif"/></td>
<td><span class="textcolor"><strong>Before, use this facility/services please read instructions...</strong></span></td>
</tr>
</table>
<p align="center" class="textcolor"><strong>Back Home</strong></p>
<table align="center" width="135" border="0" cellpadding="2" cellspacing="0" title="Click to Verify - This site chose VeriSign SSL for secure e-commerce and confidential communications.">
<tr>
<td width="135" align="center" valign="top"><script type="text/javascript" src="https://seal.verisign.com/getseal?host_name=www.desco.org.bd&size=S&use_flash=YES&use_transparent=YES&lang=en"></script><br />
ABOUT SSL CERTIFICATES</td>
</tr>
</table>
</div>
<div align="center" style="padding-top:10px;">
<CENTER><B>
Total Visits: 1</B></CENTER>
</div>
</DIV>
</DIV>
</DIV>
</DIV>
<DIV class=pageright></DIV></DIV>
<DIV class=pagebotshadow>
<DIV id=Footer>Copyright © 2010 Dhaka Electric Supply Company Ltd. All rights reserved.</DIV>
</DIV>
</DIV>
</BODY>
</HTML>
basically below code is the form
<form NAME='login' METHOD='POST' ACTION='authentication.php'>
<table width="350" height="181"cellpadding='0' cellspacing='0' border='0' style="border:#e5e5e5 0px solid; BACKGROUND: url(css/images/top9.png) no-repeat left top;" align="center">
<tr> <td rowspan="6" style="padding-left:15px;"><img src="css/images/groupperms.gif" width="50" height="50"><td></tr>
<tr>
<td colspan="2" height="50"></td>
</tr>
<tr>
<td nowrap><span class="textcolor1">Account No. </span></td>
<td><input type='text' name='username' style="border:#cacaca 2px solid; color:#000099;" value=''></td></tr>
<tr>
<td> <a class="uiTooltip" href="#" onMouseOver="ajax_showTooltip(window.event,'tooltip/help.html',this);return false" onMouseOut="ajax_hideTooltip()">Help</a></td>
<td><input name="login" type='submit' value='Login' style="width:80px; font-family:Arial, Helvetica, sans-serif; font-weight:bold; color:#FFFFFF; border:#000000 2px solid; cursor:pointer; background-color: #1b4585;" border="0" align="right" title="Login" onClick="return checkLogin();"/></td>
</tr>
</table>
</form>
i am trying this
package jsouptest;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class JsouptTest {
public static void main(String[] args) throws Exception {
Connection.Response loginForm = Jsoup.connect("https://www.desco.org.bd/ebill/login.php")
.method(Connection.Method.GET)
.execute();
Document document = Jsoup.connect("https://www.desco.org.bd/ebill/login.php")
.data("cookieexists", "false")
.data("username", "32007702")
.data("login", "Login")
.cookies(loginForm.cookies())
.post();
System.out.println(document);
}
}
but im getting below error
Exception in thread "main" java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:152)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:442)
at sun.security.ssl.InputRecord.read(InputRecord.java:480)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:439)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:424)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:178)
at jsouptest.JsouptTest.main(JsouptTest.java:12)
am is missing something? how to fix it?
The URL that are you using in order to do the POST request is wrong, simply because when you have to do a specific request to a form you should use the web page that is present in the form tag, in this case "authentication.php".
So the code will be:
package jsouptest;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class JsouptTest {
public static void main(String[] args) throws Exception {
Connection.Response loginForm = Jsoup.connect("https://www.desco.org.bd/ebill/login.php")
.method(Connection.Method.GET)
.execute();
Document document = Jsoup.connect("https://www.desco.org.bd/ebill/authentication.php")
.data("cookieexists", "false")
.data("username", "32007702")
.data("login", "Login")
.cookies(loginForm.cookies())
.post();
System.out.println(document);
}
}
This one correctly retrieves the web page that you want.
For me the problem was that I didn't send the viewstate, eventvalidation, viewstategenerator values.
To get these values you have to first send a GET request to the login form page.
In my instance this was a default.aspx page.
Then you have to extract those values and put them into variables. Also of course you need the form login and password field ids, the submit button's id, among other things. For a list of all those variable that are sent, login manually and use chrome dev tools (inspect elements) to look at the network tab for a POST request. Inside it should show the username and password you submitted. There you will see other variables that are sent.
network tab in dev tools example
Next, send a POST request including all those variables, save the cookies from the response into a variable, and you can then use that to go to another page.
Code:
import java.io.IOException;
import java.util.Map;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.FormElement;
public class get_example {
public static void main(String[] args) throws IOException {
//===================================
Connection.Response response2 = Jsoup.connect("yourloginpage")
.method(Connection.Method.GET)
.execute();
Document responseDocument = response2.parse();
Element eventValidation = responseDocument.select("input[name=__EVENTVALIDATION]").first();
Element viewState = responseDocument.select("input[name=__VIEWSTATE]").first();
Element viewStateGen = responseDocument.select("input[name=__VIEWSTATEGENERATOR]").first();
Connection.Response response = Jsoup.connect("yourloginpage")
.method(Connection.Method.POST)
.data("ctl00$plnMain$txtLogin", "username")
.data("ctl00$plnMain$txtPassword", "password")
.data("ctl00$plnMain$Submit1", "Log In")
.data("ctl00$ucCopyright$hdnPrivacyStatement", "Privacy Statement")
.data("ctl00$ucCopyright$hdnTermsOfUse", "Terms of Use")
.data("__VIEWSTATE", viewState.attr("value"))
.data("__VIEWSTATEGENERATOR", viewStateGen.attr("value"))
.data("__EVENTVALIDATION", eventValidation.attr("value"))
.execute();
Map<String, String> cookies = response.cookies();
Document homePage = Jsoup.connect("anotherpage")
.cookies(cookies)
.get();
System.out.println(homePage.body().html());
}
}
In my case, it consists in three steps:
Get cookies from login form page;
Post credentials to login form action= URL, renew cookies;
The user will be redirected to index page. Don't parse here, just send Response to the final target URL.
Parse when you reach the final page.
The cookies should be renewed in every step, sometimes add entries, and sometimes you must clear it and reset. Be sure to check the network transmission with Internet Explorer/Chrome/Firefox Dev tool (F12), in the Network panel, cookies part.

Categories