Error when making CURL requests to ElasticSearch server - java

I'm trying to index some strings onto an ElasticSearch server that I have running on a DigitalOcean droplet. The following code compiles just fine. However when I run it, I get different o/p's for the different Curl requests I make. For some curl requests, I get 'Authorization required', and for some, I get the Apache2 Ubuntu Default Page's contents on the terminal. Is this a network issue? Please Help. Thanks.
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;
class SampleJSON
{
String row_id;
String date;
String body;
String title;
String score;
public SampleJSON(String row_id, String title, String body, String date, String score)
{
this.row_id = row_id;
this.date = date;
this.body = body;
this.title = title;
this.score = score;
}}
public class ParseXML {
public static void main(String argv[]) {
try {
File Android_API = new File("/home/bhargav/Downloads/Independent Study/Android API/Posts.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(Android_API);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("row");
System.out.println("----------------------------");
// nList.getLength()
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
//System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String keyword = "device";
String text = eElement.getAttribute("Title");
String eliminateLineBreaks = eElement.getAttribute("Body");
eliminateLineBreaks.replace("\n", "");
//System.out.println(text);
ParseXML obj = new ParseXML();
if(obj.search(keyword, text))
{
SampleJSON json = new SampleJSON(eElement.getAttribute("Id"), eElement.getAttribute("Title"), eElement.getAttribute("Body"), eElement.getAttribute("CreationDate"), eElement.getAttribute("Score"));
Gson gson = new Gson();
String serverName = "localhost";
String indexName = "android_api";
String typeName = "posts.xml";
//String keyword = "1";
String requestURL = String.format("curl -XPOST --anyauth \"http://%s:9200/%s/%s/%s/\" -d\'{\"Row_id\":\"%s\",\"Title\":\"%s\"}\'",serverName,indexName,typeName,keyword, eElement.getAttribute("Id"), eElement.getAttribute("Title"));
System.out.println(requestURL);
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(requestURL);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(output);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean search(String keyword, String text)
{
int length = keyword.length();
for(int i=0; i<=text.length()-length; i++)
{
if(i!=text.length()-length)
{
String temp = String.valueOf(text.substring(i, i+length));
if(temp.equalsIgnoreCase(keyword))
return true;
else
return false;
}
else if(i==text.length()-length)
{
String temp = String.valueOf(text.substring(i));
if(temp.equalsIgnoreCase(keyword))
return true;
else
return false;
}
else
{System.out.println("Alert"); return false;}
}
return false;
}
}
Output on the terminal:
curl -XPOST --anyauth "http://localhost:9200/android_api/posts.xml/device/" -d'{"Row_id":"7902","Title":"Device recognition on Android SDK"}'
<html>
<head><title>401 Authorization Required</title></head>
<body bgcolor="white">
<center><h1>401 Authorization Required</h1></center>
<hr><center>nginx/1.10.0 (Ubuntu)</center>
</body>
</html>
curl -XPOST --anyauth "http://localhost:9200/android_api/posts.xml/device/" -d'{"Row_id":"10325","Title":"Device recognized as ????? in ubuntu"}'
curl -XPOST --anyauth "http://localhost:9200/android_api/posts.xml/device/" -d'{"Row_id":"13793","Title":"Device stuck on "obtaining IP address", then sets network to "disabled""}'
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!--
Modified from the Debian original for Ubuntu
Last updated: 2014-03-19
See: https://launchpad.net/bugs/1288690
-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Apache2 Ubuntu Default Page: It works</title>
<style type="text/css" media="screen">
* {
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
}
body, html {
padding: 3px 3px 3px 3px;
background-color: #D8DBE2;
font-family: Verdana, sans-serif;
font-size: 11pt;
text-align: center;
}
div.main_page {
position: relative;
display: table;
width: 800px;
margin-bottom: 3px;
margin-left: auto;
margin-right: auto;
padding: 0px 0px 0px 0px;
border-width: 2px;
border-color: #212738;
border-style: solid;
background-color: #FFFFFF;
text-align: center;
}
div.page_header {
height: 99px;
width: 100%;
background-color: #F5F6F7;
}
div.page_header span {
margin: 15px 0px 0px 50px;
font-size: 180%;
font-weight: bold;
}
div.page_header img {
margin: 3px 0px 0px 40px;
border: 0px 0px 0px;
}
div.table_of_contents {
clear: left;
min-width: 200px;
margin: 3px 3px 3px 3px;
background-color: #FFFFFF;
text-align: left;
}
div.table_of_contents_item {
clear: left;
width: 100%;
margin: 4px 0px 0px 0px;
background-color: #FFFFFF;
color: #000000;
text-align: left;
}
div.table_of_contents_item a {
margin: 6px 0px 0px 6px;
}
div.content_section {
margin: 3px 3px 3px 3px;
background-color: #FFFFFF;
text-align: left;
}
div.content_section_text {
padding: 4px 8px 4px 8px;
color: #000000;
font-size: 100%;
}
div.content_section_text pre {
margin: 8px 0px 8px 0px;
padding: 8px 8px 8px 8px;
border-width: 1px;
border-style: dotted;
border-color: #000000;
background-color: #F5F6F7;
font-style: italic;
}
div.content_section_text p {
margin-bottom: 6px;
}
div.content_section_text ul, div.content_section_text li {
padding: 4px 8px 4px 16px;
}
div.section_header {
padding: 3px 6px 3px 6px;
background-color: #8E9CB2;
color: #FFFFFF;
font-weight: bold;
font-size: 112%;
text-align: center;
}
div.section_header_red {
background-color: #CD214F;
}
div.section_header_grey {
background-color: #9F9386;
}
.floating_element {
position: relative;
float: left;
}
div.table_of_contents_item a,
div.content_section_text a {
text-decoration: none;
font-weight: bold;
}
div.table_of_contents_item a:link,
div.table_of_contents_item a:visited,
div.table_of_contents_item a:active {
color: #000000;
}
div.table_of_contents_item a:hover {
background-color: #000000;
color: #FFFFFF;
}
div.content_section_text a:link,
div.content_section_text a:visited,
div.content_section_text a:active {
background-color: #DCDFE6;
color: #000000;
}
div.content_section_text a:hover {
background-color: #000000;
color: #DCDFE6;
}
div.validator {
}
</style>
</head>
<body>
<div class="main_page">
<div class="page_header floating_element">
<img src="/icons/ubuntu-logo.png" alt="Ubuntu Logo" class="floating_element"/>
<span class="floating_element">
Apache2 Ubuntu Default Page
</span>
</div>
<!-- <div class="table_of_contents floating_element">
<div class="section_header section_header_grey">
TABLE OF CONTENTS
</div>
<div class="table_of_contents_item floating_element">
About
</div>
<div class="table_of_contents_item floating_element">
Changes
</div>
<div class="table_of_contents_item floating_element">
Scope
</div>
<div class="table_of_contents_item floating_element">
Config files
</div>
</div>
-->
<div class="content_section floating_element">
<div class="section_header section_header_red">
<div id="about"></div>
It works!
</div>
<div class="content_section_text">
<p>
This is the default welcome page used to test the correct
operation of the Apache2 server after installation on Ubuntu systems.
It is based on the equivalent page on Debian, from which the Ubuntu Apache
packaging is derived.
If you can read this page, it means that the Apache HTTP server installed at
this site is working properly. You should <b>replace this file</b> (located at
<tt>/var/www/html/index.html</tt>) before continuing to operate your HTTP server.
</p>
<p>
If you are a normal user of this web site and don't know what this page is
about, this probably means that the site is currently unavailable due to
maintenance.
If the problem persists, please contact the site's administrator.
</p>
</div>
<div class="section_header">
<div id="changes"></div>
Configuration Overview
</div>
<div class="content_section_text">
<p>
Ubuntu's Apache2 default configuration is different from the
upstream default configuration, and split into several files optimized for
interaction with Ubuntu tools. The configuration system is
<b>fully documented in
/usr/share/doc/apache2/README.Debian.gz</b>. Refer to this for the full
documentation. Documentation for the web server itself can be
found by accessing the manual if the <tt>apache2-doc</tt>
package was installed on this server.
</p>
<p>
The configuration layout for an Apache2 web server installation on Ubuntu systems is as follows:
</p>
<pre>
/etc/apache2/
|-- apache2.conf
| `-- ports.conf
|-- mods-enabled
| |-- *.load
| `-- *.conf
|-- conf-enabled
| `-- *.conf
|-- sites-enabled
| `-- *.conf
</pre>
<ul>
<li>
<tt>apache2.conf</tt> is the main configuration
file. It puts the pieces together by including all remaining configuration
files when starting up the web server.
</li>
<li>
<tt>ports.conf</tt> is always included from the
main configuration file. It is used to determine the listening ports for
incoming connections, and this file can be customized anytime.
</li>
<li>
Configuration files in the <tt>mods-enabled/</tt>,
<tt>conf-enabled/</tt> and <tt>sites-enabled/</tt> directories contain
particular configuration snippets which manage modules, global configuration
fragments, or virtual host configurations, respectively.
</li>
<li>
They are activated by symlinking available
configuration files from their respective
*-available/ counterparts. These should be managed
by using our helpers
<tt>
a2enmod,
a2dismod,
</tt>
<tt>
a2ensite,
a2dissite,
</tt>
and
<tt>
a2enconf,
a2disconf
</tt>. See their respective man pages for detailed information.
</li>
<li>
The binary is called apache2. Due to the use of
environment variables, in the default configuration, apache2 needs to be
started/stopped with <tt>/etc/init.d/apache2</tt> or <tt>apache2ctl</tt>.
<b>Calling <tt>/usr/bin/apache2</tt> directly will not work</b> with the
default configuration.
</li>
</ul>
</div>
<div class="section_header">
<div id="docroot"></div>
Document Roots
</div>
<div class="content_section_text">
<p>
By default, Ubuntu does not allow access through the web browser to
<em>any</em> file apart of those located in <tt>/var/www</tt>,
public_html
directories (when enabled) and <tt>/usr/share</tt> (for web
applications). If your site is using a web document root
located elsewhere (such as in <tt>/srv</tt>) you may need to whitelist your
document root directory in <tt>/etc/apache2/apache2.conf</tt>.
</p>
<p>
The default Ubuntu document root is <tt>/var/www/html</tt>. You
can make your own virtual hosts under /var/www. This is different
to previous releases which provides better security out of the box.
</p>
</div>
<div class="section_header">
<div id="bugs"></div>
Reporting Problems
</div>
<div class="content_section_text">
<p>
Please use the <tt>ubuntu-bug</tt> tool to report bugs in the
Apache2 package with Ubuntu. However, check <a
href="https://bugs.launchpad.net/ubuntu/+source/apache2">existing
bug reports</a> before reporting a new bug.
</p>
<p>
Please report bugs specific to modules (such as PHP and others)
to respective packages, not to the web server itself.
</p>
</div>
</div>
</div>
<div class="validator">
<p>
<img src="http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0 Transitional" height="31" width="88" />
</p>
</div>
</body>
</html>

Shouldn't your CURL request look like this, I guess you're missing out a space after -d. Try this:
curl -XPOST --anyauth "http://localhost:9200/android_api/posts.xml/device/" -d '{"Row_id":"7902","Title":"Device recognition on Android SDK"}'
In your code:
String requestURL = String.format("curl -XPOST --anyauth \"http://%s:9200/%s/%s/%s/\" -d \'{\"Row_id\":\"%s\",\"Title\":\"%s\"}\'",serverName,indexName,typeName,keyword, eElement.getAttribute("Id"), eElement.getAttribute("Title"));
..........................................................................................................................................................^
This SO could be helpful!

Related

Css not rendering in velocity template (JAVA)

I have written some HTML-CSS in a file, It works perfectly in the browser but when I change the extendion to vm ( for apache velocity) . some of the css doesn't work . why is velocity not able to understand the css.
CODE:
<html>
<head>
<title>Letter</title>
<style>
.row {
width: 100%;
display:flex;
height:80px;
}
.column1 {
width:33%;
float: left;
}
.column2 {
width:33%;
float: center;
}
.column3 {
width:33%;
float: right;
}
body {
padding: 20px;
font-size: 12px;
font-family: Arial,Arial Unicode MS,Quivira,sans-serif,Wingdings;
}
#rcorners2 {
border-radius: 25px;
align-items:center;
border: 1px solid grey;
padding: 20px;
width: 1000px;
height: 50px;
display:flex;
}
.vl {
border-left: 1px solid grey;
height: 50px;
}
.gap{width:200px;background:none;height:200px;display:inline-block;}
</style>
</head>
<body>
<div class="row">
<div class="column1">
<img src="https://www.iconfinder.com/data/icons/pictype-free-vector-icons/16/home-512.png" height="50px" width="250" />
</div>
<div class="column2">
<h1 style="text-align: center;"> Letter Head</h1>
</div>
<div class="column3">
<h2 style="color:#AE275F;text-align: right;">SAMPLE</h2>
</div>
</div>
<div>
<div id="rcorners2" > </div>
<div>
<p>Date </p>
<p>MAY 28,2020</p>
</div>
<div class="gap">
</div>
<div class="vl"></div>
</div>
</body>
</html>
The problem was not with my velocity template. I was using Itext5 to convert HTML to PDF and as Itext5 does not support HTML5 , some of the features weren't working.
I am using openHtmlToPdf library for converting HTML to PDF and the css works perfectly now.

iText7 - Html to PDF - Footer with page counter - How change color

Using iText7 for Java, I try to convert a HTML into PDF.
I try to change the style of my footer, without success.
My HTML :
<html>
<head>
<style>
#header {
position: running(header);
text-align: left;
margin-top: 50pt;
margin-left: 320pt;
font-family: Garamond;
}
#page {
margin-top: 200pt;
margin-right: 30pt;
margin-bottom: 50pt;
margin-left: 30pt;
#top-right {
content: element(header);
}
#bottom-center {
content: "Page " counter(page) " of " counter(pages);
}
}
</style>
</head>
<body>
<div id="header">
Monsieur Jay LAPOISSE<br>
13 avenue de la Chance<br>
35911 Rennes
</div>
<div style="page-break-after: always;">First page</div>
<div style="page-break-after: always;">Second page</div>
<div>Last page</div>
</body>
</html>
My Java
try {
HtmlConverter.convertToPdf(new FileInputStream(new File(SRC)), new FileOutputStream(new File(DEST)));
} catch(Exception e) {
e.printStackTrace(System.err);
}
My goal:
If I try to do as for the header, I don't arrive to have the page counter.
And if I do as my code above, I don't arrive to affect a style.
CSS has 16 page margin areas in total where you can put your content. Your use case can be achieved by using those areas easily with the following CSS code:
#bottom-right {
color: red;
content: "Page " counter(page) " of " counter(pages);
}
#bottom-left {
color: red;
content: "[document title]";
}
Full HTML:
<html>
<head>
<style>
#header {
position: running(header);
text-align: left;
margin-top: 50pt;
margin-left: 320pt;
font-family: Garamond;
}
#page {
margin-top: 200pt;
margin-right: 30pt;
margin-bottom: 50pt;
margin-left: 30pt;
#top-right {
content: element(header);
}
#bottom-right {
color: red;
content: "Page " counter(page) " of " counter(pages);
}
#bottom-left {
color: red;
content: "[document title]";
}
}
</style>
</head>
<body>
<div id="header">
Monsieur Jay LAPOISSE<br>
13 avenue de la Chance<br>
35911 Rennes
</div>
<div style="page-break-after: always;">First page</div>
<div style="page-break-after: always;">Second page</div>
<div>Last page</div>
</body>
</html>
Visual result after converting to PDF with pdfHTML 3.0.1:

Missing image in generated PDF

I am trying to convert a HTML page to a PDF with the help of iText library. I do not have a lot experience and I am failing to get my image added in the PDF.
First I read a HTML template (that I use for the basis). The image is placed with the <img> tag as follows <img src="http://clipartmag.com/image/iron-man-face-drawing-6.png" class="avatar-image">. I retrieve a Document class from that template. I add the wanted content to the Document instance. Once that is done, I retrieve the html and use it to generate the PDF.
String resumeFilePath = String.format(RESUME_FILE_PATH, userProfileBean.getFirstname(), userProfileBean.getLastname());
Document resumeAsHtml = createHtmlDocument(userProfileBean);
HtmlConverter.convertToPdf(resumeAsHtml.html(), new FileOutputStream(resumeFilePath));
File newResume = new File(resumeFilePath);
In the testing phase, I even created the HTML page separately to see everything is in place - resumeAsHtml.html(). The web page had the image in the page. But when I call
HtmlConverter.convertToPdf(
resumeAsHtml.html(), new FileOutputStream(resumeFilePath));
the created PDF is missing the image. I also get 3 errors in the logs:
2019-09-29 10:06:22,678 ERROR c.i.s.c.p.s.CssParserStateController:495 - The rule #keyframes is unsupported. All selectors in this rule will be ignored.
2019-09-29 10:06:22,944 ERROR c.i.s.r.r.ResourceResolver:146 - Unable to retrieve image with given base URI (file:/Users/jklancic/dev/custom/resume/) and image source path (http://clipartmag.com/image/iron-man-face-drawing-6.png)
2019-09-29 10:06:22,947 ERROR c.i.h.a.i.DefaultHtmlProcessor:356 - Worker of type com.itextpdf.html2pdf.attach.impl.tags.DivTagWorker unable to process com.itextpdf.html2pdf.attach.impl.tags.ImgTagWorker
Any idea what could be wrong? Here is the template that contains the image already:
<!DOCTYPE html>
<html>
<head>
<style>
#resume-header {
margin-bottom: 25px;
}
#resume-body {
}
#clear {
clear: both;
}
.header-left {
width: 29%;
height: 160px;
float: left;
}
.header-right {
padding-top: 10px;
width: 70%;
height: 160px;
float: right;
}
.header-right h1,h2,h3 {
text-align: left;
font-family: verdana;
}
.header-right h1 {
color: #4065a3;
font-size: 34px;
margin: 5px 0px 15px 0px;
}
.header-right h2 {
font-size: 22px;
margin: 5px 0px 5px 0px;
}
.header-right h3 {
font-size: 10px
}
.avatar-image {
display: block;
margin-left: auto;
margin-right: auto;
height: 160px;
}
.info {
margin: 0px 20px 0px 0px;
font-family: verdana;
font-size: 10px
}
span.section-header {
color: #507fcc;
font-family: verdana;
font-size: 16px;
margin: 0px 0px 0px 10px;
}
p.section-title {
color: #000000;
font-family: verdana;
font-size: 12px;
}
p.section-subtitle {
color: #9aa3b3;
font-family: verdana;
font-size: 12px;
margin-left: 10px;
}
p.text {
color: #000000;
font-family: verdana;
font-size: 10px;
}
ul.list {
color: #000000;
font-family: verdana;
font-size: 10px;
padding-left: 25px
}
div.web-profile {
margin-top: 10px;
}
div.section-content {
margin-bottom: 20px;
}
div.bottom-border {
border-bottom: 1px solid #507fcc;
}
.primary {
color: #507fcc;
}
.small-top-margin {
margin: 2px 0px 0px 0px;
}
.small-bottom-margin {
margin: 15px 0px 2px 0px;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css">
</head>
<body>
<div id="resume-header">
<div class="header-left">
<img src="http://clipartmag.com/image/iron-man-face-drawing-6.png" class="avatar-image">
</div>
<div class="header-right" id="basic-info">
</div>
<div id="clear"></div>
</div>
<div id="resume-body">
<div class="bottom-border" id="education-section">
<i class="fas fa-graduation-cap primary"></i><span class="section-header">Education</span>
</div>
<div class="bottom-border" id="job-section">
<i class="fas fa-briefcase primary"></i><span class="section-header">Work</span>
</div>
<div class="bottom-border" id="skill-section">
<i class="fas fa-pencil-ruler primary"></i><span class="section-header">Skills</span>
</div>
</div>
</body>
</html>
iText has a very high number of bugs. Don't comment on the version you are using, but the resource loader has several problems that must be corrected by overloading it (it doesn't know how to load images from base64, it doesn't know how to load resources with 302 redirection, ...).
In your specific case, the error indicated is:
Unable to retrieve image with given base URI (file:/Users/jklancic/dev/custom/resume/) and image source path (http://clipartmag.com/image/iron-man-face-drawing-6.png)
This suggests that iText is trying to access the address "file:/Users/jklancic/dev/custom/resume/http://clipartmag.com/image/iron-man-face-drawing-6.png". Debug at c.i.s.r.r.ResourceResolver:146 to confirm.
If you are able to upgrade to a new version, try to do so, otherwise you should overload the resource loader to fix it.
Remember, you should determine first the exact problem (currently like a bad base+path combination problem), anyway, I fixed a lot of related problems implementing our custom ITextUserAgent as follows:
final ITextRenderer renderer = new ITextRenderer();
{
final TextUserAgent userAgent = new TextUserAgent(renderer.getOutputDevice());
renderer.getSharedContext().setUserAgentCallback(userAgent);
userAgent.setSharedContext(renderer.getSharedContext());
}
You must to implement your custom TextUserAgent to fix your specific problem (iText is not free now):
public class TextUserAgent extends ITextUserAgent {
public TextUserAgent(ITextOutputDevice outputDevice) {
super(outputDevice);
}
#Override
public ImageResource getImageResource(final String uri) {
final ImageResource legacy = super.getImageResource(uri);
if (legacy != null && legacy.getImage() != null) {
return legacy;
}
return alternativeImageResource(uri);
}
...

Inserting mysql database data into a html form

I have records of products in my mysql database (I'm talking about a spring MVC java project using hibernate).
I have a html (and css) form of a search screen, here is its code:
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
* {box-sizing: border-box;}
body {
margin: 0;
font-family: Arial, Helvetica, sans-serif;
}
.topnav {
overflow: hidden;
background-color: #e9e9e9;
}
.topnav a {
float: left;
display: block;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #2196F3;
color: white;
}
.topnav .search-container {
float: right;
}
.topnav input[type=text] {
padding: 6px;
margin-top: 8px;
font-size: 17px;
border: none;
}
.topnav .search-container button {
float: right;
padding: 6px 10px;
margin-top: 8px;
margin-right: 16px;
background: #ddd;
font-size: 17px;
border: none;
cursor: pointer;
}
.topnav .search-container button:hover {
background: #ccc;
}
#media screen and (max-width: 600px) {
.topnav .search-container {
float: none;
}
.topnav a, .topnav input[type=text], .topnav .search-container button {
float: none;
display: block;
text-align: left;
width: 100%;
margin: 0;
padding: 14px;
}
.topnav input[type=text] {
border: 1px solid #ccc;
}
}
</style>
</head>
<div class="topnav">
<a class="active" href="#home">Home</a>
About
Contact
<div class="search-container">
<form action="/search1">
<input type="text" placeholder="Search.." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
</form>
</div>
</div>
<div style="padding-left:16px">
</div>
<style>
table {
border-collapse: collapse;
border-spacing: 0;
width: 100%;
border: 1px solid #ddd;
}
th, td {
text-align: left;
padding: 16px;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
</style>
</head>
<body>
<h2>Search Results</h2>
<table>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Product Price</th>
</table>
</body>
</html>
I also have a java function that connect to my database and fetches the correct search results (currently it just prints the results to the console) , here is that function:
#RequestMapping("/results")
public String results(UserSearch search){
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
ArrayList<ProductsEntity> li = (ArrayList<ProductsEntity>)session.createQuery("from ProductsEntity").list();
for (ProductsEntity c: li) {
if (c.getProductName().toLowerCase().contains(search.getSearch().toLowerCase())){
System.out.println(c.getProductName());
}
}
session.close();
factory.close();
return "results";
}
What I want to do is to insert those results from the java function into the html form (so that the html will contain a table with the search results), does anyone knows are?
Thanks!
I would say, your form in the HTML page must be a tag <form:form>
and assigned a modelattribute. I believe it will be a ProductsEntity.
The binding of the form tag is explained here.
You will have include the taglib library for tag to work.
Include <%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%> between the <!DOCTYPE html> and the <html> tag.

Populate JSP textarea with method in Java Servlet

I have looked for a clear answer or lead all over stack and other forums, but all of them are associated with filling textareas with input, forms, and/or submissions. In my case I do not require any of those. I simply need the area to populate with information fetched by a query that I wrote in my Servlet's service() method. I do not want to rely on scriptlets. I want to be able to maintain security with my private instances and maintain 2 different files where I can code in one language for each. Its easier and more organized for me that way.
For the record, the algorithm for fetching the information has been tested and is working properly if run through a servlet with a printwriter executing all of the html code. I now want to separate the html/jsp from the java to maintain better coding practice.
How would I invoke my service() method and fill the textarea in my jsp with the desired values from my query?
Thank you.
Servlet:
/**
* Servlet implementation class Homepage
*/
#WebServlet(urlPatterns = { "/Homepage" })
public class Homepage extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection connection;
private Statement stmt;
private ResultSet rs;
/**
* #see HttpServlet#HttpServlet()
*/
public Homepage() {
super();
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("driver found");
connection = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1;" +
"instance=SQLEXPRESS;databaseName=Timecard_DB;user=Dan;password=12345;");
try {
stmt = connection.createStatement();
String feedSelect = "SELECT ROLE_NAME from ROLES";
rs = stmt.executeQuery(feedSelect);
ResultSetMetaData metadata = rs.getMetaData();
while(rs.next()) {
for(int i = 1; i <= metadata.getColumnCount(); i++) {
String colValue = rs.getString(i);
out.println(colValue);
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
response.setContentType("text/html");
}
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>Home</title>
<style>
body {
background-image: url(Images/whitebg.jpg);
background-repeat: no-repeat;
background-size: 100%;
}
#container {
width: 900px;
margin: 0 auto;
font-family: "Trebuchet MS", Helvetica, sans-serif;
}
#header img {
position: absolute;
top: 80px;
left: 72px;
width: 200px;
height: 50px;
}
#container a:visited {
color: blue;
}
#container a:hover {
color: red;
}
#welcome {
position: absolute;
top: 20px;
right: 100px;
}
#logout {
position: absolute;
top: 20px;
right: 20px;
width: 50px;
height:25px;
}
#links {
position: absolute;
top: 200px;
left: 72px;
}
#links ul {
list-style-type: none;
padding: 5px 10px 5px 10px;
border: 2px solid red;
border-radius: 10px;
}
#links li {
padding: 10px 0 25px 0;
}
#feed {
position: absolute;
top: 100px;
left: 400px;
width: 800px;
height: 400px;
}
#feedtext {
width:800px;
height:400px;
overflow: scroll;
}
</style>
</head>
<body>
<div id='container'>
<div id='header'>
<img src='Images/mPowerlogo.jpg'/>
</div>
<div id='welcome'>
Welcome, User1
</div>
<div id='logout'>
<a href=''>Logout</a>
</div>
<div id='links'>
<ul>
<li><a href=''>Timecard Management</a></li>
<li><a href=''>User Management</a></li>
<li><a href=''>Customer Management</a></li>
<li><a href=''>Admin</a></li>
<li><a href=''>Reports</a></li>
</ul>
</div>
<div id='feed'>
<p>Recent Activity:</p>
<textarea id='feedtext' readonly>
***WANT DB INFO HERE***
</textarea>
</div>
</div>
</body>
</html>
First your class needs to override the doPost or doGet method from HttpServlet.
Then, when you go to your Homepage, the servlet would receive the request, process the data and add it to the request. In your loop you would do something like:
StringBuilder data = new StringBuilder();
while (rs.next()) {
for (...) {
data.append(rs.getString(i));
data.append("|"); // Some separator
}
data.append("\n");
}
request.setAttribute("data", data);
After that you need to redirect to the JSP:
RequestDispatcher dispatcher = request.getRequestDispatcher("/pathToJsp");
dispatcher.forward(request, response);
And last you get the data in your JSP:
<textarea>
${data} <%-- This will grab data from the request attribute --%>
</textarea>
You need to be concerned about HTML injection in case some one save HTML in your database. This would be rendered on the browser.
In JSP you can use Expression Language to access data from the request.

Categories