ERROR http 400 with java and servlets, JSP - java

How about community, this error happened to me today and I would like to know if some of you ever happened to you and how to solve it. I am creating an application with servlets in java that the functionality is to have a button, where by clicking it sends me a json with 50 records through the URL so that I can generate an excel. Now, all good when it comes to 10 records, no problem happens, when you have more than 20 records in that json or so, that's where the error happens to me. Investigating I found that the error happens because the header I am sending is too long. Here is an example of what the header I'm sending is:
Url: localhost:8080/pruebas/vistas/excel/Reporte_Insertados.jsp?registros=[{"CODPER":"123456","NRO":"1","DNI":"45874587","APELLIDOS_NOMBRES":"ROJAS%20LOPEZ%20GUSTAVO","FECHA":"14/01/2020","MONTO":"150.50","OBSERVACION":"DADSADSA","RAZON_SOCIAL":"","ESTADO":"DATOS%20CORRECTOS","":""}...] so until you have 50 records.
So my question is: If any of you solve it or how could I do it from my servlet to allow the header to be long, since it is the problem for which it does not leave me and the error happens to me.
I leave code of my application. Thank you in advance community.
My Javascript code:
function exportarReporteInsertados(registrosInsertados){
let tabla_reporte_insertados = $("#tablaCargaMasiva").tableToJSON({});//Here grab all 50 records.
window.location = "excel/Reporte_Insertados.jsp?registros="+JSON.stringify(tabla_reporte_insertados)
}
My jsp code to receive the data
<%#page import="org.json.JSONObject"%>
<%#page import="java.text.SimpleDateFormat"%>
<%#page import="java.text.DateFormat"%>
<%#page import="java.util.Date"%>
<%#page import="org.json.JSONArray"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
String datos = request.getParameter("registros");
JSONArray jsonArray_datos = new JSONArray(datos);
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=REPORTE_CARGA_MASIVA.xls");
%>
ERROR
enter image description here

#Felipo If you need to send a json, kindly refrain from adding it to the url. The url string has a character limit.Please look at : What is apache's maximum url length? . Also, according to convention in order to send a json via the request you need to add it to the request body instead of the url. Use an ajax request to send the data to the endpoint instead of passing it via the url.

Related

How to better display data from database in JSP

I am trying to display data in JSP and i am wondering if there is a better way then what i have done. I am not really experienced in Java or JSP so the code i made is probably not the cleanest.
I will only be returning count from my database as shown below so i will not be returning huge amounts of data i just need the number of rows from the database to display in my divs.
Would appreciate any help if anyone has any ideas but functionally what i have at the moment works good and without any problems i am just worried about security and how messy the code is. I am using Hibernate framework for this project.
My method that returns data from database:
public Long findCount() {
Session session = openCurrentSession();
Query result = session.createQuery("SELECT COUNT(*) FROM Polica", Polica.class);
Long count = (Long)result.uniqueResult();
return count;
}
data.jsp this is where i display count from database currently there is only 1 but there will be multiple here so i am wondering also if there is a way to call specific one using ajax.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="digiwallboard.Service.PolicaService" %>
<%#page import="digiwallboard.Config.*" %>
<%#page import="digiwallboard.DAO.PolicaDAO2" %>
<%#page import="digiwallboard.DAO.PolicaDaoInterface" %>
<%#page import="digiwallboard.Entity.Polica" %>
<%#page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p><%=PolicaService.findCount() %></p>
</body>
</html>
And finally my ajax call:
function refresh() {
$.ajax({
url: "data.jsp",
type: 'GET',
success: function(res) {
$('.result').html(res);
}
});
}

How to modify html to jsp display page for servlet response

I am trying to build a site that displays report results based on a date range inputted by the user. First I built the front-end "aesthetics" part of it in HTML/CSS/JS using dummy json data to retrieve the results. Now I am trying to eliminate the json and actually integrate it with the backend, which I have no experience with so am struggling a bit.
Right now I have a Java servlet written, and it works alright. I'm writing the ResultSet from the database query by doing response.getWriter().write(""); Now from what I've seen the next step is to display the results by appending to the URL, but the code that formats and displays it properly is just a div currently. What is the proper way to do this/modify the code?
Sorry if this is a badly written question, I'm not totally sure of all the terminology or best practices, although I'm trying to learn.
EDIT: Currently on the html page I have
$('#gen-report').click(function(){
$("#auction-report").fadeIn({ duration: 400 });
}
In the auction-report div is all of my formatting & elements (charts, displays, etc.) Is there a way to make use of this code instead of having to start my jsp page from scratch?
Put parameters in servlet to request, then invoke forward from request.getRequestDispatcher.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("now", LocalDate.now());
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/view/test.jsp");
dispatcher.forward(request, response);
}
Now you have access to params which you put in request. Here jsp:
<%# page language="java" contentType="text/html; charset=windows-1255"
pageEncoding="windows-1255"%>
<!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=windows-1255">
<title>Test</title>
</head>
<body>
<h2>Date</h2>
<%= request.getParameter("now") %>
</body>
</html>

null request response in simple jsp file

I am trying to just set up a very basic jsp file that takes in a query from a url and displays it. I have the following test.jsp file that I run on the server:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Test jsp</title>
</head>
<body>
<% String firstName = (String) request.getAttribute("firstName");
out.println("Hello :" + firstName);%>
</body>
</html>
However, when I type in the following URL, I still get a "null" result (even after refreshing): see Picture.
Note: my ultimate goal is to do have an event at some point that sends a POST request from a java file and display its result in the jsp page. If I understood well from my research, I would have to do it via a Servlet with a DispacherRequest forwarding method. But I first want to understand why the simple aforementioned code isnt working).
Thank you for your help !
You mention that you're trying to display a query parameter from the URL. A query or request parameter is not the same as a request attribute.
To get a query parameter, you would have to use the getParameter() method:
String firstName = request.getParameter("firstName")

Chinese character gets scrambled when going from JSP to server in Java

I have already set
<%#page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
This in my JSP. But, after doing as
xmlHttp.setRequestHeader("SEARCH_TEXT", srctxt);
or
passing as a parameter in the AJAX url,
I am still getting Chinese words as scrambled letters or '????' marks.
Required some insight regarding this. Please help.
#Mena, After your comment, I checked the 'encodeURIComponent' and as I encoded the Chinese string and decoded it my server side code, it got resolved. Thanx. Pasting code for reference,
Client Side code,
xmlHttp.setRequestHeader("SEARCH_TEXT", encodeURIComponent(srctxt));
Server Side Code,
CommonUtils.decodedStringValue(request.getHeader("SEARCH_TEXT"));
Hope this helps.

JSP data to be downloaded to Excel sheet using ActiveQuery results in character problems

downloading data using Active query from JSP page with some parameters is leading to character problems. Special characters in the german language as for example, ö, ä, ß are printed as ö, ä and ß.
Debugging the JSP page in Java shows that the result that is returned by the JSP page is correct. So the problem seems to be due to conversion within excel after download, most probably due to a unsopported charset.
I tried to convert the result string in JSP to different charsets, but the problem still persists.
Does anyone know a solution?
Thank You very much in advance!
Did you try setting the encoding of the page?
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
...
If you can't find a solution on the Microsoft side, I'd recommend this alternative here:
http://poi.apache.org/

Categories