JSP not working in Eclipse Orion WebIDE - java

Does Eclipse Orion WebIDE support JSP? I am trying to create a simple application and jsp files are not working.
index.html
<html>
<head>
<script type="text/javascript" src="jquery-1.12.4.js"></script>
<script>
function getInput()
{
$.ajax({
type:"GET",
url: "./test.jsp",
success: function(success) {
console.log(success);
}
});
}
</script>
</head>
<body onload="getInput()">
test.jsp
<%#import="./javaMethod*"%>
<%javaMethod a = new javaMethod();
var value = a.initiate();
%>
<input type="hidden" id="test" value="<%=value%>">
javaMethod.java
public class javaMethod
{
public int initiate()
{
return 1;
}
}
This should add a hidden input field which will hold the value from the java method. However, it is not working and the jsp is just displaying as plain text.

This should add a hidden input field - no, this should log anything comes from test.jsp to the browser console. To add the output of the JSP to the body element, use $(document.body).append(success);.

Related

Why my web application does not redirect correctly?

I am trying to pass an attribute from a java servlet to jsp and write this attribute on jsp file. However it does not redirect to jsp file url but it writes the content of the jsp file. Here is my related codes:
Control.java:
#WebServlet("/Control")
public class Control extends HttpServlet{
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Key key = MacProvider.generateKey();
long time = System.currentTimeMillis();
try{
String jwt = Jwts.builder()
.signWith(SignatureAlgorithm.HS256, key)
.setSubject("username")
.setIssuedAt(new Date(time))
.setExpiration(new Date(time+6000000))
.claim("password","password")
.compact();
req.setAttribute("jwt", jwt);
req.getRequestDispatcher("/Home.jsp").forward(req,resp);
}catch (Exception e){
e.printStackTrace();
}
}
}
Home.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
${jwt}
</body>
</html>
Here, browser stays on http://localhost:8080/Control but it writes the content of Home.jsp file which is just a java web token result string.
2) My second question is when I tryed to store this jwt result string in browser local storage and then write it in jsp file in order to check if it stored in browser or not. But it does not prints anything. To do this, I just changed the Home.jsp file as follow:
(I took both of the code snippets from here)
Home.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<script>
localStorage.setItem("jwt", ${jwt});
console.log(localStorage.getItem("jwt"));
var jjwt = localStorage.getItem("jwt");
document.write(jjwt);
</script>
</body>
</html>
Another try:
<html>
<head>
<script>
function myFunction() {
localStorage.setItem("jwt", ${jwt});
console.log(localStorage.getItem("jwt"));
var jjwt = localStorage.getItem("jwt");
document.getElementById("myText").innerHTML = jjwt;
}
</script>
</head>
<body onload="myFunction()">
<span id="myText"></span>
</body>
</html>
Where am I doing wrong?
1) When you use RequestDispatcher.forward(request,response), your servlet will still have control but your jsp page will be loaded so this is nothing to worry about.
If you want your browser URL to show your JSP page URL, do response.sendRedirect("URL TO LOAD");
2)Since you are using JSP, try accessing the request variables like below and print it
<% String jwt = (String) request.getAttribute("jwt");%>
We need to set it as
localStorage.setItem('jwt', <%=jwt%>);

How to make a JSP function to run only when called?

I'm having a JSP page as follows :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Admin Tools</title>
<jsp:include page="/basic/nav.jsp"/>
<link rel="stylesheet" type="text/css" href="tools.css"/>
</head>
<body>
<div class="container">
<h2>Admin Tools</h2>
<br/><br/><br/><br/>
<%#page import="java.sql.ResultSet"%>
<%
boolean def_admin = false, def_admin_changed = false;
conn.connect.main(null);
conn.dbc.main(null);
ResultSet rstools = conn.connect.st.executeQuery("select * from admins where uname='admin'");
if (rstools.next()) {
if (rstools.getString("uname").equals("admin") && rstools.getString("password").equals("123")) {
def_admin = true;
}
if (rstools.getString("uname").equals("admin") && !rstools.getString("password").equals("123")) {
def_admin_changed = true;
}
}
%>
<%if (def_admin == false) {%>
Add Default Admin Account :<br/>
<input type="button" value="Add" onclick="<% add_admin(); %>"/>
<% } else if (def_admin == true && def_admin_changed == false) { %>
Delete Default Admin Account :<br/>
<input type="button" value="Delete" onclick="<% delete_admin(); %>"/>
<% } else if (def_admin == true && def_admin_changed == false) { %>
The Default Admin Password Exists but the password has been changed<br/>
Do you still want to delete the Default Admin Account?<br/>
<input type="button" value="Even so, Delete it" onclick="<% delete_admin(); %>"/>
<% }%>
<div id="tools_error"></div>
<%!
boolean insert_success = false;
void add_admin() {
try {
int Urows;
Urows = conn.connect.st.executeUpdate("insert into admins(uname,password) values('admin','123');");
if (Urows == 1) {
insert_success = true;
} else {
insert_success = false;
}
%>
<script>
(function () {
boolean i_s = "<%=insert_success%>";
if (i_s == false) {
document.getElementById("tools_error").value = "There has been an error in Adding Default Admin";
}
});
</script>
<%!
} catch (Exception e) {
}
}
void delete_admin() {
}
%>
</div>
</body>
<jsp:include page="/basic/footer.jsp"/>
</html>
As you can see when the button is clicked I have made it to run the declared JSP functions. But when the JSP file is loaded the functions run automatically and the insert MYSQL query runs which automatically inserts the values given in the query.
I don't want it the functions add_admin() and delete_admin() to run automatically on load. Any suggestions?
The events in the webpage (onclick event for example) is executed client side when someone opens your webpage and clicks the button. The JSP scriplets are executed when the webpage is opened and their result is the actual page that the client receives. So your method executes ONLY when the page is loaded (and the JSP is compiled). The java code is not even visible in the webpage you generate. If you open it in browser and check the source you will see what I mean.
TL;DR: You can't
Your Java code is executed once, when the page is loaded. The page is not on the server anymore, so you can't use its back-end capabilities. Otherwise, that would mean someone reewriting your HTML could make your page execute any code on your back-end.
Once your page is loaded, all there is on it is HTML and Javascript (CSS if you want to bicker).

eclipse is showing error on render() in play2

i am new on Play Framework and i am trying to develop sample java application
i have created new html page test.html
in controllers it is working if we simply return result in the form of string i.e. return ok("hello world") but it simply format all the styling/text and just shows "hello world" on the UI.
public static Result test() {
return ok("hello world");
}
// working fine
but it gives errors when i try this
public static Result test(){
return ok(test.render());
}
// giving error
it gives following errors
[error] /opt/ahsen/play-2.2.3/testapp/app/controllers/Application.java:15: render(java.lang.String,play.api.templates.Html) in views.html.test cannot be applied to ()
[error] return ok(test.render());
[error] (compile:compile) javac returned nonzero exit code
here is my test.html file
#(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<script src="#routes.Assets.at("javascripts/jquery-1.9.0.min.js")" type="text/javascript">
</script>
</head>
<body>
#content
</body>
</html>
help please
Your test.html template requires two parameters
#(title: String)(content: Html)
So you need to pass them to the template in your controller
public static Result test(){
String title = "test title";
Html content = // create content
return ok(test.render(title, content));
}
Better solution
Test.html looks rather as a more general layout template. I would create a separate file for generating content instead passing it directly from a controller.
content.html
#(title: String)
#test(title){
<span>this is the content</span>
}
And in the controller it would look like this.
public static Result test(){
String title = "test title";
return ok(content.render(title));
}

Forward from JSP to another JSP without using a servlet between them?

I have a JSP page :
employee5_searchByName.jsp
<%#page import="java.util.Iterator"%>
<%#page import="java.util.List"%>
<!-- EMPLOYEE wants to search items by their name -->
<!DOCTYPE html>
<html>
<head>
<title>Employee - Search for items by name</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
<script src="js/jquery.autocomplete.js"></script>
<style>
input
{
font-size: 120%;
}
</style>
</head>
<body>
<h1>Employee - Search for items by name</h1>
<h1>
Search for items by name
</h1>
<fieldset>
<legend>Please enter the item's name :</legend>
<form action="Employee5_After">
Item's name : <input type="text" name="prod_name" id="myProduct"><br>
<script>
$("#myProduct").autocomplete("autocompleteFromDb.jsp");
</script>
<input type="submit" value="Register">
</form>
</fieldset>
</body></html>
It forwards to this servlet :
Employee5_After
package controller.employee;
/**
* Retrieve the record of a given product by its name
* using hibernate
* #author X
*
*/
#WebServlet("/Employee5_After")
public class Employee5_After extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// grab the product's name that the user entered
String productName = request.getParameter("prod_name");
// create DB instance
DatabaseInventory inventory = new DatabaseInventory();
// get the details
String details = inventory.getProductDetailsByName(productName);
HttpSession session = request.getSession();
// forward answer to JSP
synchronized(session)
{
if (details != null) // then the product has been found
{
session.setAttribute("foundProd", details);
String addressPath = "/WEB-INF/results/employee/employeeResult5.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(addressPath);
dispatcher.forward(request, response);
}
}
}
}
That servlet is doing his stuff , and then forwards to a 2nd JSP ,called :
employeeResult5.jsp
<!-- Employee - get a description of a product by its name -->
<!DOCTYPE html>
<html>
<head><title>The details for the product you requested are below</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<h1>Here are the details from the product you request :</h1>
<h2>${foundProd}</h2>
<h1>We wish you well - bye bye!</h1>
<fieldset>
<legend>Go back to Employee's web-page</legend>
<form action="blablabla">
Press here to continue
</form>
</fieldset>
</body></html>
I guess that I can use the <% and %> in the JSP to do the logic side of the servlet (contacting to DB and retrieve data) . How can I avoid using a servlet in between , and just pass the data from one JSP to another JSP ?
You can use the request.redirect(URL) method to do it.
Or you can use request. forward(req, resp).
See example
Separate the business logic from the font end, there is no need to redirect to an intermediate servlet. The best practice is to put the business logic in a separate class and instantiate that class in the destination page. Here is one example:
mainPage.jsp - create the page similar to your employee5_searchByName.jsp. Now this page posts the data you enter.
Create a backing class called - dbData.java (DatabaseInventory in your case)- put all your database query here and functions to retrieve what your want. A function like public String searchText(String param) (similar to getProductDetailsByName(productName)) which will essentially fetch your search results from database.
Now the most important part - Instantiate this class in your destination SearchResults.jsp page and show whatever data you get in a manner similar to this:
<%#page import="mysource.dbData"%>
<%
searchParam = request.getParameter("searchStr");
dbData data = new dbData();
String result = data.searchText(searchParam);
%>
<HTML>
<BODY>
The result is: <% out.print(result); %>
</BODY>
</HTML>
The industry standard is to follow an MVC Architecture. Following that will create applications which are clear to understand and easy to maintain.
Try this code to forward with parameteres
<jsp:forward page="URL">
<jsp:param nama="param1" value="hello"/>
<jsp:param nama="param2" value="hello2"/>
<jsp:param nama="param3" value="hello3"/>
<jsp:param nama="param4" value="hello4"/>
.
........... and so on
</jsp:forward

how can get response from <form target="IFrame">

There is a simple web page which sends request, handles & manipulated by a servlet class and send back the response text.while i want ajax type handleing the request at client side that is why i am giving the response target to a invsible iframe. *but i want to print success on the page after iframe gets the response *
<html> <body>
<form action="test" method="post" target="IFrame"> /*response target is iframe*/
<input type="text" name="logic" />
<input type="submit" value="Submit" />
</form>
<iframe name="IFrame" style="width:0; height:0"> </iframe>
</body> </html>
i think this can be done using javascript or jquery, please guid me if you have any idea.
In the page which loads in the iframe, you will need to invoke a parent function.
<!-- This is the Parent. Call it JSTest1.html -->
<html>
<head>
</head>
<body>
<script type="text/javascript">
function parentAlert() {
alert('hey there from the parent');
}
</script>
I'm the parent
<iframe src="/JSTest2.html"></iframe>
</body>
<!-- this is the iframe html loaded. Call it JSTest2.html-->
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready( function() {
window.parent.parentAlert();
});
</script>
In the Iframe.
</body>
To send a message from Iframe to Parent window page:
<script type="text/javascript">
$(document).ready( function() {
//Message part is two parts Event name and Data you want to send
// Example message = "my_action,my_data"
message = "my_action,my_data"
parent.postMessage(message, "*");
});
</script>
At the parent window you can do the following to listen to this message and capture it:
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
// Youe message which you send is captured here in e.data will split it on ',' to get the event and the data
message = e.data.split(',')[0]
value = e.data.split(',')[1]
if ( message === "my_action" ) {
myParentFunction(value)
}
},false);

Categories