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>
Related
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.
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")
Trying to find the best way to make a quasi java-javascript web application. I want to write a java servlet (for the controller and backend) with a jQuery front end. What's the best approach to having these two communicate with each other? I'm used to coding in both but never worked on them together.
Can anybody help me out? I suppose a start would be having a Java Servlet call from jQuery code and getting a response back from the servlet.
Thanks!
Create REST backend using one of JAX-RS implementations (Jersey, RESTeasy etc.). Writing web service with plain old Servlet API is tedious.
You can start learning JAX-RS from here.
Take a look at jQuery's ajax function. Here is a simple example:
// Servlet
#SuppressWarnings("serial")
public class AjaxHandler extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
resp.setContentType("text/plain");
resp.getWriter().print("Hello jQuery!");
}
}
// View.jsp
<%# 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">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<script>
$(document).ready(function() {
$.ajax({
url : '/AjaxHandler', // servlet mapping ("web.xml")
success : function(responseText) {
$('#ajaxHandlerResponse').text(responseText);
}
});
});
</script>
Servlet's message: <span id="ajaxHandlerResponse"></span>
</body>
</html>
I'm learning java and try to pass some variable from servlet to jsp page. Here is code from servlet page
#WebServlet("/Welcome")
public class WelcomeServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
session.setAttribute("MyAttribute", "test value");
// response.sendRedirect("index.jsp");
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);
}
}
And simple jsp
<%# 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>My Index page</title>
</head>
<body>
Index page
<br />
<%
Object sss = request.getAttribute("MyAttribute");
String a = "22";
%>
<%= request.getAttribute("MyAttribute"); %>
</body>
</html>
Whatever I do attribete at jsp is null.
What is wrong at this simple code?
you are getting if from request not session.
It should be
session.getAttribute("MyAttribute")
I suggest you to use JavaServer Pages Standard Tag Library or Expression Language instead of Scriplet that is more easy to use and less error prone.
${sessionScope.MyAttribute}
or
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:out value="${sessionScope.MyAttribute}" />
you can try ${MyAttribute}, ${sessionScope['MyAttribute']} as well.
Read more
Oracle Tutorial - Using JSTL
Oracle Tutorial - Expression Language
You set an attribute in a session. You have to retrieve it from a session:
Object sss = session.getAttribute("MyAttribute");
And since you are dispatching the request, you actually don't need a session. You can set the attribute in a request object in your servlet:
request.setAttribute("MyAttribute", "test value");
Then read it as you are already doing in you JSP.
You should avoid scriptlets because they are java code in HTML, they break MVC pattern, they are ugly, odd and deprecated.
Simply replace :
<%
Object sss = request.getAttribute("MyAttribute");
String a = "22";
%>
with simply using EL ${MyAttribute}
But if you want to stick with scriptlets, you should get the attribute from the proper scope which is session in your case.
Background:
I have a servlet in which I am dynamically generating javascript and putting into a variable script. Then I set the response content type as text/javascript and send the script over to the client:
resp.setContentType("text/javascript");
resp.getWriter().println(script);
Problem:
The browser does download the javascript file but it doesn't recognize the functions inside the file. If I create a static javascript file and use it instead, it works fine.
Question:
What should be done so that browser treats response from the servlet as a regular javascript file?
Thank you for help.
It should work fine. I suspect that you're just including it the wrong way or calling the function too early or that the response content is malformed.
I just did a quick test:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 6156155</title>
<script src="javaScriptServlet"></script>
<script>test()</script>
</head>
<body>
</body>
</html>
with
#WebServlet(urlPatterns={"/javaScriptServlet"})
public class JavaScriptServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/javascript");
response.getWriter().write("function test() { alert('peek-a-boo'); }");
}
}
and I get
How do you refer to this servlet from your browser ?
If you want to include this with a HTML page (existing one), you should refer to it from the tag of your page.
Ex.
<html>
<head>
<script type='text/javascript' src='URL_TO_YOUR_SERVLET'></script>
</head>
</html>
Or if you want it to be executed as part of a Ajax call, just pass the response to eval function.
Or else, if you just want to send the output and get it executed in browser, you need to send the HTML segment as well. Then include your JS with in the body tags, as a script tag.
ex. Your servlet sends the following, using content type 'text/html' :
<html>
<body>
<script type='text/javascript'>
<!-- write your generated JS here -->
</script>
</body>
</html>
You could always write the script 'in-line' to the web page.
I think this way is better.
<%# page language="java" contentType="text/javascript; charset=UTF-8" pageEncoding="UTF-8"%>
alert('Pure JavaScript right here!');
Set content type in JSP:
contentType="text/javascript; charset=UTF-8"