JSP doesn't generate all HTML code - java

I have an older JSP web page which was working perfectly fine before on apace tomcat 7. Now I am trying to restore the page and I added it on server (with the same apache tomcat 7 server) and it does't work any more as it was suppose to.
Than I checked the source code on page and I saw that at some random point the html code is not written anymore.
If anyone can help me with this.
code where the html stops:
<!-- Portfolio Modals -->
<!-- Use the modals below to showcase details about your portfolio projects! -->
<!-- Portfolio Modal 1 -->
<%
for(int i=0; i<seznamID.size(); i++){
id=seznamID.get(i);
title=seznamTitle.get(i);
description=seznamDescription.get(i);
mainThumbnail=seznamMainThumbnail.get(i);
investor=seznamInvestor.get(i);
year=seznamYear.get(i);
%>
<div class="portfolio-modal modal fade" id="portfolioModal<%=id %>" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="close-modal" data-dismiss="modal">
<div class="lr">
<div class="rl">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="modal-body">
<!-- Project Details Go Here -->
<h2><%=title %></h2><br/>
<div class="container">
<div class="row">
<div class="col-md-4">
<%
String sql4="SELECT name FROM webPage.images WHERE eng_references_ideng_references='"+id+"';";
Class.forName("com.mysql.jdbc.Driver");
Connection con4 = DriverManager.getConnection("jdbc:mysql://path_to_db?useUnicode=true&characterEncoding=UTF-8",
"username", "password");
Statement st4 = con4.createStatement();
ResultSet rs4= st4.executeQuery(sql4);
ArrayList <String>seznamImages=new ArrayList();
String images=null;
while (rs4.next()){
images=rs4.getString("name");
seznamImages.add(images);
}
con4.close();
rs4.close();
st4.close();
%>
<div class="fotorama" data-nav="thumbs" data-width="90%" data-ratio="800/600 " data-loop="true">
<img src="img/references/<%=mainThumbnail%>">
<%for (int j=0; j<seznamImages.size();j++){
String slika=seznamImages.get(j);
%>
<img src="img/references/<%=slika%>">
<%} %>
</div>
</div>
<div class="col-md-6">
<p><%=description%></p>
<table class="table">
<tr>
<td>Investor</td>
<td><%=investor %></td>
</tr>
<tr>
<td>implementation</td>
<td><%=year %></td>
</tr>
<tr>
<td>Actions</td>
<td>
<%
String sql3="select a.title , c.title, c.ideng_references from action a inner join action_references b on a.idaction = b.action_idaction inner join eng_references c on b.eng_references_ideng_references = c.ideng_references where c.ideng_references='"+id+"';";
Connection con3 = DriverManager.getConnection("jdbc:path_to_db?useUnicode=true&characterEncoding=UTF-8",
"username", "password");
Statement st3 = con3.createStatement();
ResultSet rs3=st3.executeQuery(sql3);
ArrayList <String>seznamAction=new ArrayList();
String action=null;
while(rs3.next()){
action=rs3.getString("title");
seznamAction.add(action);
}
con3.close();
st3.close();
rs3.close();
for(int j=0; j<seznamAction.size(); j++){
action=seznamAction.get(j);
out.print(action+"<br/>");
}
%>
</td>
</tr>
</table>
</div>
</div><br/>
<button type="button" class="btn btn-primary center" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
source code from web page:

HTML stop generated because of exception in code.
Add:
Try {
Catch (Throwable e){e.printStackTrace();}
Surronding your code and find problem

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.

How to redirect the user to the intended page with the details he want to modify in jsp servlet?

The main functioning of my project to give privileges to the user to modify the event he want to.
so first page is modify-event.jsp where he will get the list of events present in the system with modify button at the end column
modify-event.jsp
<%#page import="java.util.ArrayList"%>
<jsp:include page="includes/header.jsp" />
<div>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
HttpSession session1 = request.getSession();
//String id = request.getParameter("userId");
String driverName = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String dbName = "technovision";
String userId = "root";
String password = "root";
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<h2 align="center"><font><strong>Retrieve data from database in jsp</strong></font></h2>
<table align="center" cellpadding="5" cellspacing="5" border="1">
<tr>
</tr>
<tr bgcolor="#A52A2A">
<td><b>Event name</b></td>
<td><b>Registration Amount</b></td>
<td><b>EventHead name</b></td>
<td><b>EventHead contact</b></td>
<td><b>Event Description</b></td>
<td><b>Action</b></td>
</tr>
<%
try{
connection = DriverManager.getConnection(connectionUrl+dbName, userId, password);
statement=connection.createStatement();
String sql ="SELECT * FROM events";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
session1.setAttribute("eventid",resultSet.getString(1));
session1.setAttribute("eventname",resultSet.getString(2));
session1.setAttribute("registrationamount",resultSet.getString(3));
session1.setAttribute("eventheadname",resultSet.getString(4));
session1.setAttribute("eventheadcontact",resultSet.getString(5));
session1.setAttribute("eventdescription",resultSet.getString(6));
//ArrayList a = new ArrayList();
//a.add(resultSet.getString(1));
//a.add(resultSet.getString(2));
//a.add(resultSet.getString(3));
//a.add(resultSet.getString(4));
//a.add(resultSet.getString(5));
//a.add(resultSet.getString(6));
%>
<tr bgcolor="#DEB887">
<td><%=resultSet.getString("event_name") %></td>
<td><%=resultSet.getString("registration_amount") %></td>
<td><%=resultSet.getString("eventhead_name") %></td>
<td><%=resultSet.getString("eventhead_contact") %></td>
<td><%=resultSet.getString("event_description") %></td>
<td>Modify</td>
</tr>
<%
}
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</div>
<%# include file="includes/footer.jsp" %>
<%#include file="includes/scripts.jsp" %>
</body>
</html>
Now when user clicks on any of the modify button he should redirect to the page which will fetch the clicked event details so that he can edit the same, but the case here is its opening the last data from that table above in modify-event.jsp because i made use of httpsession but i guess in the wrong way.
so when user clicks on modify button i redirected him to page name modify-page.jsp
modify-page.jsp
<%#page import="java.util.ArrayList"%>
<jsp:include page="includes/header.jsp" />
<%--<%# page import="com.event"%>--%>
<style>
input.eventdescription{
padding-top : 20px;
padding-bottom : 100px;
}
</style>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.*"%>
<%#page import="java.sql.Connection"%>
<%
// ArrayList[] eventname = new ArrayList[10];
// ArrayList[] registrationamount = new ArrayList[10];
// ArrayList[] eventheadname = new ArrayList[10];
// ArrayList[] eventheadcontact = new ArrayList[10];
// ArrayList[] eventdescription = new ArrayList[10];
// ArrayList[] eventid = new ArrayList[10];
//
//HttpSession session1 = request.getSession();
// eventname = (ArrayList[])session1.getAttribute("eventname");
// registrationamount = (ArrayList[])session1.getAttribute("registrationamount");
// eventheadname = (ArrayList[])session1.getAttribute("eventheadname");
// eventheadcontact = (ArrayList[])session1.getAttribute("eventheadcontact");
// eventdescription = (ArrayList[])session1.getAttribute("eventdescription");
// eventid = (ArrayList[])session1.getAttribute("eventid");
%>
<div class="addevent-content" style="background-color:black">
<div class="pattern height-resize">
<div class="container">
<form class="form-horizontal" action="UpdateEvent" method="post"
id="addevent_form" >
<!-- Form Name -->
<center>
<h2 id="registerheading">
<b style="color: gold">Modify Event</b>
</h2>
</center>
<br>
<!-- Text input-->
<div class="form-group">
<label class="col-md-5 control-label" style="color: #fff">Event
Name<abbr title="Required">*</abbr>
</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<input name="event_name" id="form_fname" placeholder="Event Name"
value='${eventname}' class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-5 control-label" style="color: #fff">Registration Amount<abbr title="Required">*</abbr>
</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<input name="registration_amount" id="form_lname" placeholder="Registration Amount"
value='${registrationamount}' class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-5 control-label" style="color: #fff">Event Image<abbr
title="Required">*</abbr></label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<input name="event_image" placeholder="Event Image" class="form-control"
value='' type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-5 control-label" style="color: #fff">EventHead Name<abbr
title="Required">*</abbr></label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<input name="eventhead_name" id="password1" placeholder="EventHead Name"
value='${eventheadname}' class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-5 control-label" style="color: #fff">EventHead Contact
<abbr title="Required">*</abbr>
</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<input name="eventhead_contact" id="password2" placeholder="(+91)"
value='${eventheadcontact}' class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-5 control-label" style="color: #fff">Event Description<abbr
title="Required">*</abbr></label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<input name="event_description" id="email" placeholder=""
value='${eventdescription}' class="form-control eventdescription" type="text" required>
</div>
</div>
</div>
<!-- Select Basic -->
<input name="event_id"class="form-control"
value='${eventid}' type="hidden" >
<!-- Button -->
<div class="form-group">
<label class="col-md-5 control-label"></label>
<div class="col-md-5">
<br>
<button type="submit" class="btn btn-warning">SUBMIT</button>
</div>
</div>
</form>
</div>
<!-- /.container -->
</div>
<!-- pattern height resize-->
</div>
<%# include file="includes/footer.jsp" %>
<%#include file="includes/scripts.jsp" %>
</body>
</html>
So is there any way that when user clicks on modify button and it should retrieve that particular event details in modify-page.jsp from the database for modification and then user can click on submit to update the database .
below is the structure of the database table "Events"
Database structure
send unique id with url ,
Modify
Then get id in modify-page request.getParameter("id")
connect db again with PreparedStatement
using SELECT * FROM Events WHERE eventid= ? sql statement.

Redirect to same tab on page upon Form submission - Spring MVC

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();
});
});

getParamter() returns NULL

Why is request.getParameter("termin"); returning NULL
.The Connection and the Statement for my Databse are correct.It works fine in an more simple Version.
This is JSp/JAva Code:
int result = 0;
if(request.getParameter("submit") != null) {
String name = new String();
if(request.getParameter("termin") != null) {
name = request.getParameter("termin");
}else {
out.println("termin is null");
}
Termin t1 = new Termin();
result = t1.setTermin(name);
Here is the HTML Code :
<form action="index.jsp" method="POST" name="test">
<div class="modal fade" id="bModal" tabindex="-1" role="dialog" aria-labelledby="beispielModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Schließen</span></button>
<h4 class="modal-title" id="beispielModalLabel">Neuer Termin</h4>
</div>
<div class="modal-body">
<!-- <form role="form" action="index.jsp" method="POST"> -->
<div class="form-group">
<label for="empfaenger-name" class="control-label">Name</label>
<input type="text" class="form-control" id="empfaenger-name" name="termin" value="">
</div>
<div class="form-group">
<label for="nachricht-text" class="control-label">Zusätzlich:</label>
<textarea class="form-control" id="nachricht-text"></textarea>
</div>
<!-- </form> -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" id="del" data-dismiss="modal" >Löschen</button>
<input type="submit" name="submit" class="btn btn-primary" id="eintrag" data-dismiss="modal" value="Speichern" >
</div>
</div>
</div>
</div>
</form>
I'm not a Bootstrap expert yet I can see a few potential causes to this issue:
data-dismiss="modal"- looking at:
http://getbootstrap.com/javascript/#modals-related-target it seems that data-dismiss="modal" is used only with "close" buttons - never with "submit"!
the class class="btn btn-primary" is supposed to be used with elements of type button and you're using it with input
using the id attribute might create a conflict with bootstrap autogenerated html-elements, but I'm just guessing here based on your comment above.

Categories