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.
Related
I am trying to create a shopping cart using cookies in spring boot but the cookie is not being added/displayed. Below are the controller mappings and page htmls, can you let me know what I'm doing wrong?
Screenshots of pages :
Controller Mappings:
#GetMapping("/products/addToCart/{id}")
private String addToCart(#PathVariable("id") long productId, HttpServletResponse response) {
try {
Cookie browserSessionCookie = new Cookie(Long.toString(productId), Long.toString(1L));
response.addCookie(browserSessionCookie);
return "redirect:/products/cart";
} catch (Exception e) {
logger.error(e.getMessage());
return "fail";
}
}
#GetMapping("/products/cart")
public String showCookies(HttpServletRequest request, Model model) {
Cookie[] cookies = request.getCookies();
model.addAttribute("cookies",cookies);
return "/cart";
}
Thymeleaf Page For Products List:
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>All Products</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
table, th, td {
border: 1px solid black;
}
td {
padding: 20px;
}
.topnav {
background-color: #A32638;
overflow: hidden;
}
.topnav a {
float: left;
color: #f2f2f2;
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: #FCB514;
color: white;
}
</style>
</head>
<body>
<div class="topnav">
<a th:href="#{/}">Home</a>
<a class="active" th:href="#{/productsList}">Products</a>
<a th:href="#{/products/cart}">Cart</a>
</div>
<br>
Products
<br>
<br>
<div th:if="${ not#lists.isEmpty(products)}">
<table>
<tr>
<th>Name</th>
<th>Price</th>
<th>Category</th>
<th>Action</th>
</tr>
<tr th:each="product : ${products}">
<td th:text="${product.name}"></td>
<td th:text="${product.price}"></td>
<td th:text="${product.category.name}"></td>
<td>
<a th:href="#{/products/details/{id}(id=${product.id})}">Details</a>
<a th:href="#{/products/addToCart/{id}(id=${product.id})}">Add To Cart</a>
</td>
</tr>
</table>
<br>
</div>
</body>
</html>
Thmeleaf Page For Showing Cookies :
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<br>
<h1>Show cookies</h1>
<dl th:each="cookie : ${cookies}">
<dt th:text="${cookie.getName()}"></dt>
<dd th:text="${cookie.getValue()}"></dd>
</dl>
<h1>Session Data</h1>
<dl th:each="elem : ${sessionElems}">
<dt th:text="${elem.getName()}"></dt>
<dd th:text="${elem.getValue()}"></dd>
</dl>
</body>
</html>
Thank you.
The solution was to set the path of the created cookie to the path of the cart page as below :
browserSessionCookie.setPath("/products/cart");
Thanks for the responses!
I am having trouble authenticating with HTMLUnit on a webpage. I enter a username and password, and then click sign in, then check the title of the page, and it is still the sign in page. SO I am not signed in properly.
What is going wrong here? I'm trying to use Fiddler and Charles for debugging but I don't see my requests show up there. Does this Java code make sense for authentication with the given website? Any debugging tips?
Please help me! Thank you.
My code:
package com.company;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.jupiter.api.*;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.CookieManager;
public class Main {
static WebClient webClient;
static CookieManager cookieManager;
static String username = "MyUsername";
static String password = "MyPassword";
#Before
public static void init() throws Exception {
webClient = new WebClient();
cookieManager = new CookieManager();
cookieManager = webClient.getCookieManager();
cookieManager.setCookiesEnabled(true);
webClient.getOptions().setTimeout(90000);
webClient.setJavaScriptTimeout(90000);
}
#After
public static void close() throws Exception {
webClient.close();
cookieManager.clearCookies();
}
public static void signIn() throws Exception {
//Acquire location for URI, password, username, submitbutton
HtmlPage page1 = webClient.getPage("https://h3c.mlspin.com/signin.asp#ath");
HtmlForm form = page1.getFormByName("loginform");
HtmlTextInput uName = form.getInputByName("user_name");
HtmlPasswordInput passWord = form.getInputByName("pass");
HtmlButton button = form.getFirstByXPath("//*[#id=\"loginForm\"]/table/tbody/tr[7]/td/button");
uName.setValueAttribute(username);
passWord.setValueAttribute(password);
HtmlPage page2 = button.click();
System.out.println("HTMLUNIT UserText : \n" + uName.getText());
System.out.println("HTMLUNIT PassText : \n" + passWord.getText());
System.out.println("Results p2 " + page2.getTitleText());
System.out.println("Results p2 " + page2.getPage());
}
#Test
public static void givenAClient_gatherInfo() throws Exception {
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setRedirectEnabled(true);
webClient.getCache().setMaxSize(0);
}
public static void main(String[] args) throws Exception {
init();
givenAClient_gatherInfo();
signIn();
close();
}
}
<!-- Latest compiled and minified CSS -->
<LINK href="/css/Signin.css" type=text/css rel=stylesheet>
<script language='javascript'>
window.sessionStorage.clear();
</script>
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,
shrink-to-fit=no">
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE">
<meta http-equiv="expires" content="0">
<title>pinergy - Sign In</title>
<link href="/style.asp" type="text/css" rel="stylesheet">
<script type="text/javascript" src="/shared/scripts/3rdParty/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/shared/scripts/3rdParty/bootstrap-4.1.1/bootstrap.min.js"></script>
<script type="text/javascript" src="/shared/scripts/cookieConsent.js?v=2"></script>
<script language="JavaScript">
var ath;
ath = {}
;
var isMobile = function() {
return /(iphone|ipod|(android.*mobile)|blackberry|windows ce|palm|symbian|nexus 7|xoom|windows phone)/i.test(navigator.userAgent);
}
;
var isIPad = function() {
return /(ipad)/i.test(navigator.userAgent);
}
function CheckSavePassword() {
if (document.loginform.SavePassword.checked) {
document.loginform.SavePassword.checked = false;
} else {
document.loginform.SavePassword.checked = true;
}
}
function parseQueryString(queryString) {
var QueryString = {};
queryString = queryString.slice(queryString.indexOf("?") + 1);
var qsArray = queryString.split("&");
for (var i = 0; i < qsArray.length; i++) {
var arr = qsArray[i].split("=");
QueryString[arr[0]] = arr[1];
}
return QueryString;
}
if (window != top) {
top.location.href = location.href;
}
</script>
<style>
body {
padding: 0;
}
INPUT.login {
height: 22px;
border: 1px solid #808080;
padding: 2px 4px;
background-image: url('images/bg_input.gif');
}
.mobile {
padding: 6px;
align-content: center;
align-self: center;
width: 90%;
height: auto;
display: none;
text-align: center;
border: 4px solid #E7E7E7;
border-radius: 15px;
color: #444;
margin: auto;
background: -moz-linear-gradient(top, #FFFFFF, #E7E7E7);
background: -ms-linear-gradient(#FFFFFF, #E7E7E7);
background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#E7E7E7));
max-width: 25rem;
}
.mobileButton {
font-weight: bold;
border-top: 1px outset grey;
border-left: 1px outset grey;
-moz-border-radius: 10px 10px 10px 10px;
-webkit-border-radius: 10px 10px 10px 10px;
border-radius: 10px 10px 10px 10px;
-webkit-appearance: none;
-moz-appearance: none;
min-height: 2rem;
/*width:90px;
height:54px;
font-family:Arial;
font-size:x-large;*/
}
.yes {
background-color: #FBAF41;
}
.no {
background-color: #BEBEBE;
}
.mobileCheckTable {
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, sans-serif !important;
}
.mobileCheckTable td {
vertical-align: top;
}
.textContent {
font-size: .9rem;
text-align: center;
font-weight: 500;
}
.textContent1Child {
white-space: nowrap;
padding-left: .5rem;
}
.mobilecheck {
height: 1.2rem;
width: 1.2rem;
vertical-align: top;
padding: 0;
border: 1px solid rgba(0, 0, 0, 0.3);
}
.mobilequest {
margin: 0 auto;
max-width: 20rem;
box-sizing: border-box;
float: left;
padding-left: .5rem;
padding-bottom: .5rem;
}
div#remember {
font-size: 0.88rem;
}
.mls-bootstrap-font {
font-size: 1rem;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, sans-serif;
}
.sm-remember {
display: none;
}
#media only screen and (min-width: 476px) {
.mobile {
padding: 15px;
}
.sm-remember {
display: initial;
}
.mobilequest {
padding-bottom: 1rem;
}
.mobilequest,
.textContent1Child {
padding-left: 1rem;
}
}
#media only screen and (min-width: 768px) {
.mobilequest.textContent {
font-size: 1.5rem !important;
}
.textContent1Child {
font-size: 1.2rem !important;
}
}
#media only screen and (min-width: 1024px) {
.mobilequest.textContent {
font-size: 1.6rem !important;
}
.textContent1Child {
font-size: 1.2rem !important;
}
}
</style>
<link rel="icon" href="images/apple-touch-icon-120x120.png" type="image/x-icon" />
<link rel="shortcut icon" href="images/apple-touch-icon-120x120.png" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="css/addtohomescreen.css">
<script src="Scripts/addtohomescreen.js"></script>
<link rel="apple-touch-icon-precomposed" href="images/apple-touch-icon-120x120.png" type="image/x-
icon" sizes="120x120" />
<link rel="apple-touch-icon-precomposed" href="images/apple-touch-icon-152x152.png" type="image/x-
icon" sizes="152x152" />
<link rel="shortcut icon" href="images/apple-touch-icon-152x152.png" type="image/x-icon" sizes="152x152" />
<link rel="apple-touch-icon-precomposed" href="images/apple-touch-icon-57x57.png" type="image/x-
icon" sizes="57x57" />
</head>
<body marginheight="0" marginwidth="0" topmargin="0" leftmargin="0">
<table height="100%" width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td width="100%" height="100%">
<form name="loginform" id="loginForm" method="POST" action="signin.asp" style="margin:
0px" onsubmit="return signInFn.loginFormOnSubmit();
">
<input name="cxzvvfbvvalideguaueff" value="DT: 8/16/2020 8:18:40 PM" type="hidden"><input name="Page_Loaded" value="DT: 8/16/2020 9:25:16 PM" type="hidden">
<table border="0" cellspacing="0" cellpadding="0" class="mls-login">
<tr>
<td><img src="images/MLSPIN_Logo.jpg" width="240" height="60" /></td>
</tr>
<tr>
<td class="text-left pl-4"><span class="h4">Sign In to</span><img src="images/pinergy-logo.jpg" width="90" height="30" /></td>
</tr>
<tr>
<td class="pl-2"><input class="form-control" type="text" style="width: 220px;" name="user_name" maxlength="8" value="MyUsername" placeholder="Enter Your Agent ID"></td>
</tr>
<tr>
<td class="pl-2"><input class="form-control" type="password" style="width: 220px" name="pass" maxlength="20" placeholder="Password"></td>
</tr>
<tr>
<td class="text-left pl-2">Forgot your password?</td>
</tr>
<tr>
<td class="text-left pl-2 mls-login-rem-me"><input type="checkbox" name="SavePassword" value="Y"><span onclick="CheckSavePassword();">Remember My Password</span></td>
</tr>
<tr>
<td><button class="btn btn-sm btn-primary" type="submit">Sign In</button>
<!--<input class="btn btn-sm btn-primary" type="submit" value="Sign In" name="signin"></td>--></tr>
</table>
</form>
</td>
</tr>
<tr>
<td>
<footer class="mls-site-footer">
<div class="footer-content">
<div class="footer-icon MLSPINlogo mr-1"></div>
<div class="mb-1">©
<span>MLS Property Information Network,
Inc.</span></div>
<div class="vert-bar">|</div>
<div>900 Hartford Turnpike, fakeville, TN 01245 </div>
<div class="vert-bar">|</div>
<div>800-700-3189 </div>
<div class="vert-bar">|</div>
<div class="footer-content-group">
<div class="d-inline">Access Notice</div>
<div class="vert-bar d-inline">|</div>
<div class="d-inline">Privacy Policy</div>
<div class="vert-bar d-inline">|</div>
<div class="d-inline">Copyright Policy</div>
</div>
<div class="vert-bar">|</div>
<div class="footer-user-count">2190 users online right now!</div>
</div>
</footer>
</td>
</tr>
</table>
<div id="cookieConsentBootstrapModal" class="modal mls-bootstrap-font" role="dialog" aria-labelledby="cookieConsentTitle" aria-describedby="cookieConsentDesc" aria-hidden="true" data-backdrop="static" tabindex="-1">
<div class="modal-dialog" role="document">
<!-- Modal content-->
<div class="modal-content mls-modal-bgcolor">
<div class="modal-header">
<h1 class="modal-title h5" id="cookieConsentTitle">This website uses cookies</h1>
</div>
<div class="modal-body" id="cookieConsentDesc">This website uses cookies for a number of purposes, including to enhance your browsing experience. Learn more about our use of cookies in our Privacy Policy. </div>
<div class="modal-footer"><button type="button" class="btn btn-sm btn-primary mls-js-cookie-consent-action" data-dismiss="modal">OK</button></div>
</div>
</div>
</div>
<script language="JavaScript">
document.loginform.user_name.focus();
alert("Incorrect password!\nPlease try again.");
</script>
<script>
if (!window.location.hash.match('ath')) {
addToHome = addToHomescreen({
detectHomescreen: true,
autostart: false,
icon: true,
lifespan: 15,
maxDisplayCount: 1,
appID: 'com.mlspin.MobileWeb'
});
addToHome.show();
window.location.hash = '#ath';
}
</script>
<script type="text/javascript">
var signInFn = (function() {
var _suppressCookieConsent = false;
function _loginFormOnSubmit() {
var isValid = true;
if (!_suppressCookieConsent && !cookieConsentUtil.cookieConsentExists()) {
isValid = false;
cookieConsentUtil.showCookieBanner();
}
_enableDisableLoginForm();
return isValid;
}
function _enableDisableLoginForm() {
if (!_suppressCookieConsent && !cookieConsentUtil.cookieConsentExists()) {
document.getElementById("loginForm").action = "signin.asp";
} else {
document.getElementById("loginForm").action = "validate_new.asp";
}
}
function _focusOnFirstElement() {
try {
var focusable = $('button:visible, a[href]:visible, input:visible, select:visible, textarea:visible, [tabindex]:visible:not([tabindex="-1"])');
if (focusable.length > 0) {
var firstFocusable = focusable[0];
firstFocusable.focus();
}
} catch (ex) {}
}
function _docOnReady() {
//_focusOnFirstElement();
cookieConsentUtil.init({
onStoreCookieConsent: function() {
_enableDisableLoginForm();
setTimeout(_focusOnFirstElement, 0);
}
});
cookieConsentUtil.docOnReady();
_enableDisableLoginForm();
}
return {
loginFormOnSubmit: _loginFormOnSubmit,
docOnReady: _docOnReady
};
}
());
$(document).ready(function() {
signInFn.docOnReady();
}
);
</script>
</body>
</html>
Looking in the javascripts there's this section:
if (!_suppressCookieConsent && !cookieConsentUtil.cookieConsentExists()) {
document.getElementById("loginForm").action="signin.asp";
}
else{
document.getElementById("loginForm").action="validate_new.asp";
}
Seems from looking at the http requests validate_new.asp is returning a 302 (redirect) to signin.asp. This might help locate the relevant requests.
I tried looking a bit deeper but I'd need to try running your code which I've not got time to do right now. If I find time I'll come back to this as it should be possible.
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);
}
...
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.
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!