I have a JEditorPane set to edit html input and I would like to change the newline behavior so that when I go to a new line it inserts <\br> instead of surrounding the text in <p></p>. At the moment I have the following.
newSignatureScrollPane = new javax.swing.JScrollPane();
newSignatureEditorPane = new javax.swing.JEditorPane();
newSignatureEditorPane.setContentType("text/html"); // NOI18N
newSignatureEditorPane.setDocument(new HTMLDocument());
newSignatureEditorPane.setEditorKit(new HTMLEditorKit());
newSignatureScrollPane.setViewportView(newSignatureEditorPane);
This results in the following when I do a newSignatureEditorPane.getText() in my saveChangesButtonAction:
<html>
<head>
</head>
<body>
<p style="margin-top: 0">
Line 1
</p>
<p style="margin-top: 0">
Line 2
</p>
</body>
</html>
Related
index.html
<html>
<head>
<title>AddModule | Home page</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<form action="op.jsp">
<div class="card">
<div class="card-header bg-dark text-white">
<h3>Provide me a number</h3>
</div>
<div class="card-body">
<div class="form-group">
<input name="n1" type="number" class="form-control" placeholder="Enter n1">
</div>
<div class=form-group>
<input name="n2" type="number" class="form-control" placeholder="Enter n2">
</div>
</div>
<div class="card-footer text-center">
<button type="submit" class="btn btn-primary">Divide</button>
</div>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
Getting an exception in op.jsp named java.lang.NumberFormatException
HTTP Status 500-Internal Server Error
op.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Jsp Page</title>
</head>
<body>
<%
String n1= request.getParameter("n1");
String n2= request.getParameter("n2");
int a=Integer.parseInt(n1);
int b=Integer.parseInt(n2);
int c=a/b;
%>
<h3>Result is <%=c %></h3>
</body>
</html>
While converting value from string to integer it is generating an exception
Also Tried below code but still not working
<%int n1=Integer.parseInt(request.getParameter("n1"));
int n2=Integer.parseInt(request.getParameter("n1"));
int c=n1/n2 %>
The problem is not with your code, but rather how you run it.
You need to access index.html first to allow you to input numbers, then hit Divide. This will invoke op.jsp with n1 and n2 as parameters.
If you try to access op.jsp directly, your code will run without values for n1 and n2. If you don't have input, then trying to parse input as integers will obviously fail.
If you want to simplify testing, you can manually specify HTTP GET query parameters in the URL using op.jsp?n1=42&n2=7
<%
String n1 = request.getParameter("n1");
String n2 = request.getParameter("n2");
int n1Val,n2Val;
if(n1 != null){
n1Val=Integer.parseInt(n1);
}
if(n2!=null){
n2Val=Integer.parseInt(n2);
}int c;
if(n1 != null && n2!=null)c=n1Val + n2val;
%>
I need to create a method that reads a html file then display the number of word occurrence.
for example: String [] words = {"happy", "nice", "good"};
The word happy was used 7 times.
The word nice was used 1 times.
The word happy was used 2 times.
This is what I did:
public static void ReadWriteDisplay() {
Path in = Paths.get("E:\\TextToHTML.html");
Path out = Paths.get("E:\\HTMLToText.txt");
String s = "";
String str = "";
try {
InputStream input = new BufferedInputStream(Files.newInputStream(in));
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = new BufferedOutputStream(Files.newOutputStream(out, CREATE, WRITE, TRUNCATE_EXISTING));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
s = reader.readLine();
while(s != null) {
str += s;
writer.write(s);
writer.newLine();
s = reader.readLine();
}
reader.close();
writer.close();
String a[] = str.split(" ");
System.out.println("str: "+str);
String [] positive = {"happy", "nice", "good", "joy", "love"};
int [] count = {0, 0, 0, 0, 0};
for (int i = 0; i < a.length; i++) {
if(positive[0].equalsIgnoreCase(a[i]))
count[0]++;
if(positive[1].equalsIgnoreCase(a[i]))
count[1]++;
if(positive[2].equalsIgnoreCase(a[i]))
count[2]++;
if(positive[3].equalsIgnoreCase(a[i]))
count[3]++;
if(positive[4].equalsIgnoreCase(a[i]))
count[4]++;
}
for (int x = 0; x < 5; x++) {
System.out.println("The word "+positive[x]+" was used "+count[x]+" times.");
}
} catch(Exception e) {
System.err.println("Message: "+ e);
}
}
My method runs but it does not provide accurate number of occurrence. The reason because some words in html are enclosed in <> which caused <>Hello<> to be stored in my string array instead of the word Hello.
Here is the sample output:
str: <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta http-equiv="content-language" content="en" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="google-site-verification" content="rUp8isOBygjhxPJ2qyy6QtBi9vWRFhIboMXucJsCtrE" /> <title>JustPaste.it - Share Text & Images the Easy Way</title> <link rel="preload" href="/static/img/jp_logo_1_en_v4.png" as="image" /> <meta name="robots" content="noindex, nofollow" /> <meta name="googlebot" content="noindex, nofollow" /> <link rel="preload" href="/build/global.395f53d0.css" as="style" /> <link rel="stylesheet" type="text/css" href="/build/global.395f53d0.css" /> <link rel="shortcut icon" href="/static/other/fav.ico" /> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <script> window.article = {"id":42017684,"url":"https:\/\/justpaste.it\/6fn9m","shortUrl":"https:\/\/jpst.it\/2wiek","pdfUrl":"https:\/\/justpaste.it\/6fn9m\/pdf","qrCodeData":"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFcAAABXCAIAAAD+qk47AAAACXBIWXMAAA7EAAAOxAGVKw4bAAACCklEQVR4nO2by27DMAwEx0X\/\/5fTAwFdaNB8SEmB7BzjSDEWy4ikpOv1evH1\/Hz6Bf4FUgGkgiEVQCoYv\/6j67omM65FJzOPX6HWKD9PaebSj8oLIBWMm4hYlBIq79Jg+Pqyd3vpR4dvuJAXQCoYUUQsAi9lPOlt74dnloZzbygvgFQwUhExpJft9EKjh7wAUsF4R0QE+Bh5g\/898gJIBSMVEUNzDjOiDMN55AWQCkYUEcOWTqlrtL18KCEvgFQwbiJie7qSMXkpELa\/obwAUsFI7UcEpXHw397bmMh0cXtJVzBKXgCpYFyB3xYlT\/Ye3bzZ7q264EflBZAKRmqHLmPyYJR\/5IeXEqrt8SgvgFQwojoiY9feEpN5VCLo4maQF0AqGLVzTcM\/50UpEdpVj+sUxwNSAao7dJk6erHrhN65umYhL4BUMGoRUTJ56TsBw\/UoM0peAKlg1CrrRamgLnEu6VLW9IBUgLj7Ouz\/DJePHr16RF4AqWA096yDc92lCXs3hjzDyJIXQCoYB+\/Q9Q4vDS9cBPOojnhAKsDRO3R+nl3dp94uhrKmB6QCHL1Dlznp1GsWbUdeAKlgvOPGUK8juqt5mymx5QWQCsbBiCglS5+9KCEvgFQwDt6hO3djdHtfV14AqWAcvEO36B1M6mVNvQpFXgCpYNzs0H0h8gJIBUMqgFQwpALAH\/JvmLtnlWjnAAAAAElFTkSuQmCC"}; window.statsUrl = 'https\u003A\/\/stats.justpaste.it'; window.viewKey = 'x6ER'; window.barOptions = {"isLoggedIn":false,"hasPublicProfile":false,"displayOwnership":false,"isArticleOwner":false,"isPasswordProtected":false,"isCaptchaRequired":null,"isCaptchaEntered":false,"captchaSettings":null,"premiumUserData":null,"isPrivate":false,"isExpired":false,"expireAfterRead":false,"isShared":false,"defaultAvatar":"\/static\/img\/avatar60.jpg","createdText":"6h","showLastEdit":false,"modifiedText":"6h","isInTrash":false,"viewsText":"2","favouritesCount":0,"onlineText":"1","getFavouriteArticleUrl":"https:\/\/justpaste.it\/api\/account\/v1\/favourite-article\/42017684","addFavouriteArticleUrl":"https:\/\/justpaste.it\/api\/account\/v1\/favourite-article","removeFavouriteArticleUrl":"https:\/\/justpaste.it\/api\/account\/v1\/favourite-article-delete\/42017684","apiShowArticleDynamicUrl":"\/api\/v1\/article-dynamic","voteUrl":"\/api\/account\/v1\/vote","contentLang":"en","positiveVotes":0,"negativeVotes":0,"currentVote":"empty","linkSharingUrl":null,"linkSharingSecret":null}; </script> <script src="/build/runtime.a1e5a72a.js" async></script> <script src="/build/1676.2c557867.js" async></script> <script src="/build/8452.a9a1e0c5.js" async></script> <script src="/build/5936.ad26e56d.js" async></script> <script src="/build/9412.4a605741.js" async></script> <script src="/build/showarticlewidget.3bbca334.js" async></script> </head><body marginwidth="0" dir="ltr" marginheight="0"><!-- Static navbar --><div class="navbar navbar-default navbar-static-top mainTableTopMiddle" role="navigation"> <div class="container"> <div class="navbar-header pull-left"> <img src="/static/img/jp_logo_1_en_v4.png" width="186px" height="54px" alt="JustPaste.it" /> </div> <div class="navbar-header pull-left"> <div class="nav navbar-nav mainTableTopMiddleRight hidden-xs hidden-sm"> <img src="/static/img/jp_logo_2_en_v5.png" width="390px" height="54px" /> </div> </div> <div class="navbar-header pull-right" style="padding-top:8px"> <div id="mainPanelButtons"></div> </div> </div><!--/.nav-collapse --></div><div id="headContainer" class="container" style="max-width: 960px"> <div class="row"> <div class="col-md-12"> <div id="mainTableContent"> <div style="max-width: 960px; vertical-align: top"> <div id="showArticleWidget"><div class="showArticleWidgetPlaceholder"></div></div> <div id="articleContent"> <p>happy</p> <p>nice nice</p> <p>good good good</p> <p>joy Joy joy Joy joy</p> <p>Love love Love love Love</p> </div> <div id="showArticleBottomWidget"><div class="articleBottomWidgetPlaceholder"></div></div> <span style="visibility:hidden" class="glyphicon glyphicon-link"></span></div> </div> </div> </div> <!-- /row --></div> <!-- /container --><div id="footer" style="min-height: 30px;"> <div class="container" style="vertical-align: middle"> <div class="col-md-3 col-xs-5 col-sm-4 text-muted" style="font-size: 95%;" align="left"> © 2021 <span class="hidden-xs">justpaste.it</span> </div> <div class="col-md-9 col-xs-7 col-sm-8 text-muted" align="right"> <ul class="list-inline basePageFooterList"> <li class="hidden-xs"> Account </li> <li class="hidden-xs"> Terms </li> <li class="hidden-xs"> Privacy </li> <li class="hidden-xs"> Cookies </li> <li> Blog </li> <li> About </li> </ul> </div> </div></div> <script> window.mainPanelOptions = { addArticleUrl: '/', loginUrl: '/login', logoutUrl: '/logout', favouriteArticlesUrl: '/account/favourite', subscribedArticlesUrl: '/account/subscribed', sharedArticlesUrl: '/account/shared', manageAccountUrl: '/account/manage', messagesUrl: '/account/messages', articlesStatsUrl: '/account/articles-stats', premiumUrl: '/premium/subscription', unreadMessagesUrl: 'https://msg.justpaste.it/api/v1/conversation/unread', profileSettings: '/account/settings', isLoggedIn: false, userEmail: null, userPermalink: null, userProfileIsPublic: false, userProfileLink: null }; </script> <script src="/build/mainpanelwidget.80530742.js" async></script> </body></html>
The word happy was used 0 times.
The word nice was used 0 times.
The word good was used 1 times.
The word joy was used 3 times.
The word love was used 3 times.
How do I properly split or count the number of occurrence? Thank you!
You can simply use jsoup: Java HTML Parser library to fetch all text of html structure.
Download jar file from: https://jsoup.org/download
Below code will count occurrences of words:
static void countOccurance(String htmlStructure) {
String[] positive = { "happy", "nice", "good", "joy", "love" };
Document document = Jsoup.parse(htmlStructure);
String[] text = document.body().text().split("\\s+");
for (String word : positive) {
int wordCount = countWord(text, word);
System.out.println("The word " + word + " was used " + wordCount + " times.");
}
}
static int countWord(String[] documentText, String wordToFind) {
int count = 0;
for (int i = 0; i < documentText.length; i++) {
if (wordToFind.equalsIgnoreCase(documentText[i]))
count++;
}
return count;
}
This will help you to remove special characters, this will only allow alphabets for example : <>Hello<> will be replaced like Hello
String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
i am looking for some better solutions. I am making a matching word game for my school project, but i have some issues. Instead of this code style, i want to my values be displayed from sql database randomly, but without repeating same words. I try something, but it doesnt work, so i will appreciate any of your help.
Here is screenshot of my litlle game: when i click start words will be open, and the game will start...
My code is:
<!DOCTYPE html>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.util.*" %>
<%! String[] wordsleft ={"Belgrade","Zagreb","Sarajevo", "Washington", "Paris" };
%>
<%! String[] wordsright ={"Serbia","Bosnia","Croatia","France","USA"};
%>
<%!
String printleft(){
Random rand = new Random();
int a = rand.nextInt(4 - 0 + 1) + 0;
return String.valueOf(wordsleft[a]);
} %>
<%!
String printright(){
Random rand = new Random();
int a = rand.nextInt(4 - 0 + 1) + 0;
return String.valueOf(wordsright[a]);
} %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="cssstyle.css" rel="stylesheet">
<title>Matching Words</title>
</head>
<body>
<h1 id="welcome">Welcome!</h1>
<p class="tekst">Spojnica je igra sa rečima. <br><br>U dve kolone je prikazano po 5 reči.
Svaka reč u levoj koloni ima svoj par u desnoj koloni. Za svaki spojen par dobijate 3 poena.
</p>
<div id="container">
<div class="containerlevo">
<input type="submit" class="leftword" name="prvo" id="firstleft" value="?" />
<input type="submit" class="leftword" name="drugo" id="secondleft" value="?" />
<input type="submit" class="leftword" name="trece" id="thirdleft" value="?" />
<input type="submit" class="leftword" name="trece" id="fourthleft" value="?" />
<input type="submit" class="leftword" name="trece" id="fifthleft" value="?" />
</div>
<div class="containerdesno">
<input type="submit" class="rightword" name="prvo" id="firstright" value="?" />
<input type="submit" class="rightword" name="drugo" id="secondright" value="?" />
<input type="submit" class="rightword" name="trece" id="thirdright" value="?" />
<input type="submit" class="rightword" name="drugo" id="fourthright" value="?" />
<input type="submit" class="rightword" name="trece" id="fifthright" value="?" />
</div>
<form action="Rezultat" method="post" >
<input class="button start" type="button" id="start" onclick = "printright(); printleft();" value="START" name="start"/>
<input class="button" type="submit" id="end" value="END" name="end"/>
</form>
</div>
</body>
</html>
<script>
function printleft(){
document.getElementById("firstleft").value = "<%= printleft() %>";
document.getElementById("secondleft").value = "<%= printleft() %>";
document.getElementById("thirdleft").value = "<%= printleft() %>";
document.getElementById("fourthleft").value = "<%= printleft() %>";
document.getElementById("fifthleft").value = "<%= printleft() %>";
document.getElementById("start").disabled = true;
}
function printright(){
document.getElementById("firstright").value = "<%= printright() %>";
document.getElementById("secondright").value = "<%= printright() %>";
document.getElementById("thirdright").value = "<%= printright() %>";
document.getElementById("fourthright").value = "<%= printright() %>";
document.getElementById("fifthright").value = "<%= printright() %>";
document.getElementById("start").disabled = true;
}
To use a database on the names is a lot of stuff to add and learn. Maybe you want to start out with name-files - that seems easier to start with.
Nevertheless. First you need to create a database and depending on the jdbc driver used, you will create jdbc connection string to your database (here a mysql).
String connurl = "jdbc:mysql://localhost:3306/riddle?profileSQL=true";
Then you open need to load the driver class once in your application, usually at init() or even better as a context listener. As you are using JDBC it will be best practice to define a datasource in the application deployment descriptor.
Describing all details of this is clearly out of scope here, and definitely has been written up better somewhere else. You can find numerous samples: Netbeans has a tutorial showing this here https://netbeans.org/kb/docs/web/mysql-webapp.html
You should then start with a class that provides you the list of words, a model class. The model class will hide all the data fetching from your JSP page.
And this is where you should go from where you are: Remove all the functions from your JSP and put the data handling in a model class. That model class is then used in your JSP to provide the arrays.
When you got that going, you only need to change the model to read from file instead of const array. If you have that working, tackle the database.
Given the following code :
<%# page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>Bank application</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Web Bank application</th></tr>
</table>
<br/>
<script>
function verifyEmptyString()
{
var username = document.forms["loginForm"]["username"].value;
var password = document.forms["loginForm"]["password"].value;
return !(username == null || username == "" || password == null || password == "");
}
</script>
<fieldset>
<legend>Login Page - please enter your Username and Password</legend>
<form id="loginForm" action="loginPage" onsubmit="verifyEmptyString()" >
<p style="font-size:15px"> <span style="color:red;font-weight:bold;">*</span> Username: <input type="text" name="username"><br> </p>
<p style="font-size:15px"><span style="color:red;font-weight:bold;">*</span> Password : <input type="password" name="password"><br> </p>
<input type="submit" value="Login">
</form>
</fieldset>
<br/>
<br/>
<br/>
<br/>
<br/><br/><br/><br/><br/><br/>
</body></html>
I'm trying to call the JS function verifyEmptyString() , but the JSP doesn't call the function.
Any idea what's wrong with the code ?
The function is being called (I added an alert to verify). But you want to return the value of the function in the onclick event:
<form id="loginForm" action="loginPage" onsubmit="return verifyEmptyString(this)" >
Try something like this : http://jsfiddle.net/daguru/RBYnc/1/
var myForm = document.getElementById('loginForm');
myForm.addEventListener("submit", function(ev) {
ev.preventDefault(); // to stop the form from submitting
var username = document.forms["loginForm"]["username"].value;
var password = document.forms["loginForm"]["password"].value;
if(!(username == null || username == "" || password == null || password == "")){
this.submit(); // If all the validations succeeded
alert("submiting")
}
});
Here is the solution :
<form onsubmit="return verifyEmptyString(this)" id="loginForm" action="loginPage" >
For anyone who might encounter this problem in the future , you need to change the onsubmit ...
From this :
onsubmit="verifyEmptyString()"
To this :
onsubmit="return verifyEmptyString(this)"
I do not quite understand why we need to pass thisas a parameter to the function, because it is not accepted in the actual function definition function verifyEmptyString() . You are directly referring the form elements inside the function.
On the otherhand, if your code is similar to the below scenario,
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm(obj) {
var x = obj["firstname"].value;
alert(x);
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="action.jsp"
onsubmit="return validateForm(this)" method="post">
First name: <input type="text" name="firstname"> <input
type="submit" value="Submit">
</form>
</body>
</html>
In this scenario, we are making use of the passed parameter this.
It refers to the current context, In our case, it is the form whose name is myForm
But in your original scenario, you are directly referring the form inside the javascript function by calling document.forms["loginForm"]["username"].value.
I am using JTextPane to store some HTML text:
private static final String HTML_STR = "<html><div>plot(<b><font color=#3775B9>X</font></b>,Y)</div><div>plot(<b><font color=#3775B9>X</font></b>,Y,LineSpec)</div></html>"
JTextPane textPane = new JTextPane();
textPane.setContentType("text/html");
textPane.setText(HTML_STR);
After that, every time I call the textPane.getText(). the html content will show the html tag in different order occasionally. Like:
sometimes, < b> is inside of < font>:
<head>
</head>
<body>
<div>
plot(<font color="#3775B9"><b>X</b></font>,Y)
</div>
<div>
plot(<font color="#3775B9"><b>X</b></font>,Y,LineSpec)
</div>
</body>
</html>
some other times, < font> is inside of < b>:
<head>
</head>
<body>
<div>
plot(<b><font color="#3775B9">X</font></b>,Y)
</div>
<div>
plot(<b><font color="#3775B9">X</font></b>,Y,LineSpec)
</div>
</body>
</html>
Can anybody explain a little bit for me why JTextPane behaviors like this? Is there any way to let JTextPane return the same order constantly?
Thanks!