Part of my homework for tomorrow is to search and add entries using Java EE. If the search is not existing, an add item option will show as follow:
Supposedly, when the Stock ID is not existing, It will be transfered to the Add Item Text Field of StockID. But I have no idea how to do it. My code is as follows:
Servlet:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Item item = (Item) request.getAttribute("invenItem");
if (item != null) {
out.println("<html><title>Inventory Item</title>");
out.println("<body><h1>Inventory Item Details:</h1>");
out.println("Stock ID : " + item.getStockID() + "<br/>");
out.println("Name : " + item.getItemName() + "<br/>");
out.println("Unit Price: " + item.getUnitPrice() + "<br/>");
out.println("On Stock : " + item.getOnStock() + "<br/>");
out.println("</body>");
out.println("</html>");
} else {
RequestDispatcher rd = request.getRequestDispatcher("/DataForm.html");
rd.include(request, response);
out.println("Sorry Item not found..");
rd = request.getRequestDispatcher("AddEntry.html");
rd.include(request, response);
}
}
}
HTML:
<html>
<head>
<title>Add Entry</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h2>Add Item:</h2>
Stock ID: <input type ="text" name ="stockId" value="???"> <br> <--how to get it?
Item Name: <input type ="text" name ="name"> <br>
Unit Price: <input type ="text" name ="unitPrice"> <br>
On Stock : <input type ="text" name ="stock"> <br><br>
<input type ="submit" value ="Add Item">
</body>
</html>
You're approaching this the wrong way. HTML belongs in JSP files, not in Servlet classes. Also, EL ${} doesn't run in plain HTML files at all, but in JSP files only. Rename your .html files to .jsp. This way EL like ${param.id} will then also work, even though you still have a XSS attack hole open.
See also:
Our JSP wiki page
Our Servlets wiki page
(please read them, they contains hello world examples which should turn on some lights in your head)
You can't use the expression language (i.e. ${param.id}) in plain HTML files. It'll only be interpreted in JSPs (files with a .jsp extension).
Related
In my Quarkus project, I am sending an qute template in an email using mail object.
The data is dynamically added to qute template from my code before sending the mail.
The sample template is
<html>
<head>
</head>
<body class="body">
<br>
Hi <b>Receiver</b>,
<br><br>
{body}
<br><br>
</body>
</html>
The email body is added from code using this
#Inject
#Location("sampleMail")
MailTemplate mailObject;
public void sendMail() {
String emailBody = "First line <br>" +
"Second line \n" +
"Third line \\n" + System.lineSeparator() +
"Fourth line";
mailObject.to(recipient)
.subject("Default subject")
.data("body", emailBody)
.send().subscribe().with(
success -> logger.info("Message sent"),
fail -> logger.error("Exception while sending mail", fail));
}
}
Even after trying <br>, \n, \\n, System.lineSeparator() in body string, the new line is not rendered in qute template in the html that is being sent in the mail. All lines are present in one single line, new line is not created. Have checked the quarkus guides but there was no mention about this.
Any solution or suggestions for solving this issue ?
I believe your problem is related to your values being treated as text by Qute when rendering your template.
The <br> should work if you replace your {body} by {body.raw}, like this :
<html>
<head>
</head>
<body class="body">
<br>
Hi <b>Receiver</b>,
<br><br>
{body.raw}
<br><br>
</body>
</html>
And of course :
String emailBody = "First line <br>" +
"Second line <br>" +
"Third line <br>" +
"Fourth line";
I need to create web scraper utility which get web resources by URL. Then count number of provided word(s) occurrence on webpage and number of characters.
URL url = new URL(urlStr);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
With that I can get all text on page(and html tags) so what I do next?
Can someone help me with that? Some doc or sthg to read. I need use only JavaSE. Can't use 3d party library.
For example, you have page.html:
<!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>Login Page</title>
</head>
<body>
<div id="login" class="simple" >
<form action="login.do">
Username : <input id="username" type="text" />
Password : <input id="password" type="password" />
<input id="submit" type="submit" />
<input id="reset" type="reset" />
</form>
</div>
</body>
</html>
To parse it you can with:
import java.io.File;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
/**
* Java Program to parse/read HTML documents from File using Jsoup library.
*/
public class HTMLParser{
public static void main(String args[]) {
// Parse HTML String using JSoup library
String HTMLSTring = "<!DOCTYPE html>"
+ "<html>"
+ "<head>"
+ "<title>JSoup Example</title>"
+ "</head>"
+ "<body>"
+ "<table><tr><td><h1>HelloWorld</h1></tr>"
+ "</table>"
+ "</body>"
+ "</html>";
Document html = Jsoup.parse(HTMLSTring);
String title = html.title();
String h1 = html.body().getElementsByTag("h1").text();
System.out.println("Input HTML String to JSoup :" + HTMLSTring);
System.out.println("After parsing, Title : " + title);
System.out.println("Afte parsing, Heading : " + h1);
// JSoup Example 2 - Reading HTML page from URL
Document doc;
try {
doc = Jsoup.connect("http://google.com/").get();
title = doc.title();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Jsoup Can read HTML page from URL, title : " + title);
// JSoup Example 3 - Parsing an HTML file in Java
//Document htmlFile = Jsoup.parse("login.html", "ISO-8859-1"); // wrong
Document htmlFile = null;
try {
htmlFile = Jsoup.parse(new File("login.html"), "ISO-8859-1");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // right
title = htmlFile.title();
Element div = htmlFile.getElementById("login");
String cssClass = div.className(); // getting class form HTML element
System.out.println("Jsoup can also parse HTML file directly");
System.out.println("title : " + title);
System.out.println("class of div tag : " + cssClass);
}
}
Output:
Input HTML String to JSoup :<!DOCTYPE html><html><head><title>JSoup Example</title></head><body><table><tr><td><h1>HelloWorld</h1></tr></table></body></html>
After parsing, Title : JSoup Example
Afte parsing, Heading : HelloWorld
Jsoup Can read HTML page from URL, title : Google
Jsoup can also parse HTML file directly
title : Login Page
class of div tag : simple
I am making a small program where user's name will be used all over the pages where he navigates. I have written following code.
JSP file:
<form action="CookieServletOne" method="post">
User Name:<input type="text" name="username">
<input type="submit" value="Go">
</form>
Servlet One (under post method):
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
String username=request.getParameter("username");
pw.println("Welcome " +username);
Cookie ck=new Cookie("un",username);
response.addCookie(ck);
pw.print("<form action='CookieServletTwo'>");
pw.print("<input type='submit' value='go'>");
pw.print("</form>");
pw.close();
Servlet2:
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
Cookie[] ck=request.getCookies();
pw.write("Hello" +ck[0].getValue());
I want to take the value which is written in text box to the Servlet2 by using cookies. But,
At the end it is printing value something like this:
Hello5BD0268F522455DA719130360F74A969
What I am doing wrong here ???
Server: Apache Tomcat.
Jdk: 1.7
Os: lubuntu.
Thanks.
You should be adding below code to your servlet2 to get your desired result.The output which you are getting is JSESSIONID.
Cookie[] ck=request.getCookies();
for(int i=0; i<ck.length; i++) {
if("un".equals(ck[i].getName())) {
pw.write("Hello" +ck[i].getValue());
}
}
I have two jsp pages: search.jsp and update.jsp.
When I run search.jsp then one value fetches from database and I store that value in a variable called scard. Now, what I want is to use that variable's value in another jsp page. I do not want to use request.getparameter().
Here is my code:
<%
String scard = "";
String id = request.getParameter("id");
try {
String selectStoredProc = "SELECT * FROM Councel WHERE CouncelRegNo ='"+id+"'";
PreparedStatement ps = cn.prepareStatement(selectStoredProc);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
scard = rs.getString(23);
}
rs.close();
rs = null;
} catch (Exception e) {
out.println(e.getLocalizedMessage());
} finally {
}
%>
How can I achieve this?
Using Query parameter
<a href="edit.jsp?userId=${user.id}" />
Using Hidden variable .
<form method="post" action="update.jsp">
...
<input type="hidden" name="userId" value="${user.id}">
you can send Using Session object.
session.setAttribute("userId", userid);
These values will now be available from any jsp as long as your session is still active.
int userid = session.getAttribute("userId");
Use sessions
On your search.jsp
Put your scard in sessions using session.setAttribute("scard","scard")
//the 1st variable is the string name that you will retrieve in ur next page,and the 2nd variable is the its value,i.e the scard value.
And in your next page you retrieve it using session.getAttribute("scard")
UPDATE
<input type="text" value="<%=session.getAttribute("scard")%>"/>
Use below code for passing string from one jsp to another jsp
A.jsp
<% String userid="Banda";%>
<form action="B.jsp" method="post">
<%
session.setAttribute("userId", userid);
%>
<input type="submit"
value="Login">
</form>
B.jsp
<%String userid = session.getAttribute("userId").toString(); %>
Hello<%=userid%>
How can I send data from one JSP page to another JSP page?
One of the best answer which I filtered out from above discussion.
Can be done in three ways:
using request attributes:
Set the value to send in request attribute with a name of your choice as request.setAttribute("send", "valueToSend") and retrieve it on another jsp using request.getAttribute("send");
using session attributes
Similar to above but using session object instead of request.
using application attributes
Same as 1 and 2 above but using application object in place of request and session.
Suppose we want to pass three values(u1,u2,u3) from say 'show.jsp' to another page say 'display.jsp'
Make three hidden text boxes and a button that is click automatically(using javascript).
//Code to written in 'show.jsp'
<body>
<form action="display.jsp" method="post">
<input type="hidden" name="u1" value="<%=u1%>"/>
<input type="hidden" name="u2" value="<%=u2%>" />
<input type="hidden" name="u3" value="<%=u3%>" />
<button type="hidden" id="qq" value="Login" style="display: none;"></button>
</form>
<script type="text/javascript">
document.getElementById("qq").click();
</script>
</body>
// Code to be written in 'display.jsp'
<% String u1 = request.getParameter("u1").toString();
String u2 = request.getParameter("u2").toString();
String u3 = request.getParameter("u3").toString();
%>
If you want to use these variables of servlets in javascript then simply write
<script type="text/javascript">
var a=<%=u1%>;
</script>
Hope it helps :)
I have a gallery of images, and when I hover the mouse over any of the images, the image pulls back revealing some text.
When I have the following HTML code (at bottom of post) inside the HTML document, everything works fine.
However, when I put the exact same HTML code inside a Java servlet and have it returned to the page, everything looks normal, but the image pullback doesn't work anymore.
Any idea why that would occur? Perhaps I need to do some kind of refresh to make it work properly?
relevant code for one of the items in the gallery:
<li>
<div class="header"><p>Product 1 Shirt</p></div>
<div class="gallery_item">
<img src="gallery/thumb/gallery_01.jpg" width="214" height="194" class="cover" alt="" />
<p>Highlight 1</p>
<p>Highlight 2</p>
<p>Highlight 3</p>
More Info
Enlarge
</div>
<div class="p2"><p>Price: $10</p></div>
<div class="p2"><p>In Stock: Yes</p></div>
</li>
As requested: the servlet:
public void service(HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException
{
PrintWriter out = response.getWriter();
response.setContentType("text/html");
String requestType = request.getParameter("type");
String result;
if(requestType.equals("getproductlist"))
{
Products products = Products.getProductsInstance();
String keywords = request.getParameter(("keywords"));
String organization = request.getParameter(("organization"));
String price = request.getParameter(("price"));
String sort = request.getParameter(("sort"));
result = products.getProducts(keywords, organization, price, sort);
//this next lines of html are actually what is returned from products.getProducts. I'm just putting it here for clarity. All the variables (name, h1, etc) are okay.
result += "<li>"
+ "<div class=\"header\"><p>"+ name +"</p></div>"
+ "<div class=\"gallery_item\">"
+ "<img src=\"gallery/thumb/gallery_01.jpg\" width=\"214\" height=\"194\" class=\"cover\" alt=\"\" />"
+ "<p>"+ h1 +"</p>"
+ "<p>"+ h2 +"</p>"
+ "<p>"+ h3 +"</p>"
+ "More Info"
+ "Enlarge "
+ ""
+ "</div>"
+ "<div class=\"p2\"><p>Price: "+ itemPrice +"</p></div>"
+ "<div class=\"p2\"><p>In Stock: "+ inStock +"</p></div> "
+ "</li>";
out.println(result);
out.close();
}