I am learning Java EE technologies. Is there a way I can use Eclipse debugger to step through the code and see how it works step by step? For instance, this is a simple html5 + restful service.
Is there any way I can debug from the index.html java script, and step through the code little by little in Eclipse? That would be the best way to study this stuff.
Thanks a lot.
/**
* A simple CDI service which is able to say hello to someone
*
* #author Pete Muir
*
*/
public class HelloService {
String createHelloMessage(String name) {
return "Hello " + name + "!";
}
}
#Path("/")
public class HelloWorld {
#Inject
HelloService helloService;
#POST
#Path("/json/{name}")
#Produces("application/json")
public String getHelloWorldJSON(#PathParam("name") String name) {
System.out.println("name: " + name);
return "{\"result\":\"" + helloService.createHelloMessage(name) + "\"}";
}
/** A simple rest service saying hello */
#POST
#Path("/xml/{name}")
#Produces("application/xml")
public String getHelloWorldXML(#PathParam("name") String name) {
System.out.println("name: " + name);
return "<xml><result>" + helloService.createHelloMessage(name) + "</result></xml>";
}
}
Then, the front end html 5 + java script.
<html>
<head>
<title>HTML5 + REST Hello World</title>
<link rel="stylesheet" href="css/styles.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready( function() {
$( '#sayHello' ).click( function( event ) {
event.preventDefault();
var result = $( '#result' ),
name = $.trim( $( '#name' ).val() );
result.removeClass( 'invalid' );
if( !name || !name.length ) {
result.addClass( 'invalid' ).text( 'A name is required!' );
return;
}
//console.log("clicked: " + name);
$.ajax( 'hello/json/' + name, {
dataType:'json',
data:{},
type:'POST',
success:function ( data ) {
//console.log("success: " + data.result);
$( '#result' ).text( data.result );
}
})
.error( function() {
//console.log("error");
});
});
}); // (document).ready
</script>
</head>
<body>
HTML5 + REST Hello World<br>
<form name="theForm">
<fieldset>
<label for="name" id="name_label">Name</label>
<input name="name" id="name" type="text" required placeholder="Your Name"/>
<input type="submit" id="sayHello" value="Say Hello"/><span id="result"></span>
</fieldset>
</form>
Usually for any html/css/javascript code, I debug using the Chrome Browser's built in Dev Tool. You can also install plugins for Eclipse that will allow you to step through Javascript.
https://www.youtube.com/watch?v=_uzSw_fb7NQ
http://www.eclipse.org/webtools/jsdt/debug/
The Rhino Debugger has been around for many years.
As for stepping in through the Web Service, you can write test classes and/or set breakpoints in eclipse.
This tutorial will help.... http://wso2.com/library/tutorials/debug-your-axis2-web-service-3-steps-using-eclipse/
Related
How do I query for a particular BusStopCode from within a JSON object in a JSON array
"value": [
{
"BusStopCode": "01012",
"RoadName": "Victoria St",
"Description": "Hotel Grand Pacific",
"Latitude": 1.29684825487647,
"Longitude": 103.85253591654006
},
{
"BusStopCode": "01013",
"RoadName": "Victoria St",
"Description": "St. Joseph's Ch",
"Latitude": 1.29770970610083,
"Longitude": 103.8532247463225
},
for example if I want to find only the first object then the bus stop code I would query is 01012
my current URL query request looks like this-
http://transport/dataservice/BusStops?BusStopCode=01012
here http://transport/dataservice/BusStops is my URL
and ?BusStopCode=01012 is my path
tl;dr: You can't unless they implemenet it on the server side.
Postman is only the client side.
When you are sending a URL - the server reads it and have an implementation for this specific url / url + parameters in our case.
If the server have an implementation for something like http://transport/dataservice/BusStops?BusStopCode=01012 They should expose it to you. You can't guess what is their API.
You can filter your response data using JSONpath Visualizer in Postman.
To enable the Visualizer, please paste the following code in the Test section of Postman where you are creating your request.
let template = `
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/jsonpath#1.0.2/jsonpath.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.4.1/dist/jquery.min.js"></script>
</head>
<body>
<div>
<div>
<input id="filter" style="width:450px;" type="text" placeholder="Example query: $..name.first">
</div>
<div>
<button id="resetButton" style="background-color:red;color:white;">Reset</button>
<input id="showErrors" type="checkbox" value="1"/>
<span class="item-text" style="font-family:courier;">Show Evaluation Errors</span>
</div>
<div id="errors" style="font-family:courier;color:red;display:none;"></div>
<div>
<p id="content" style="font-family:courier;color:green;font-size:18px;"></p>
</div>
</div>
</body>
</html>
<script>
pm.getData( (error, value) => {
const extractedData = jsonpath.query(value, '$');
$(function() {
$('#filter').keyup(function() {
try {
let filteredData = jsonpath.query(extractedData, $(this).val());
$("#content, #errors").empty();
$("#content").append("<pre><code>" + JSON.stringify(filteredData, null, 4) + "</code></pre>");
} catch (err) {
console.info(err);
$("#errors").empty();
$("#errors").append("<pre><code>" + err + "</code></pre>");
}
});
});
$( "#resetButton" ).click(function() {
$("#content, #errors").empty();
$("#filter").val('');
$("#content").append("<pre><code>" + JSON.stringify(extractedData, null, 4) + "</code></pre>");
})
})
$(function() {
$("#showErrors").on("click",function() {
$("#errors").toggle(this.checked);
});
});
</script>`
pm.visualizer.set(template, pm.response.json())
Here is the example.
Sample data is also provided for better understanding.
in the belwo code "code_2" I have a controller that applies http method DELETE, to remove a specific product based on the provided id.
in "code_1", I am trying to create ajax call that shows or present to the user a dialog or pop-up with YES and NO BEFORE the controller in code_2 is executed. in other words, when the client call
/product/remove/2
he should be presented with a popup or dialog with YES and No. When he clicks YES, then the controller in code_2 should be executed normally. If he click NO, nothing should happen..only the dialog or the pop-up disappears.
For the pop-up or the dialog, I did the following as shown below:
<body>
<form action="http://www.google.com/search">
<input type="text" name="q" />
<input type="submit" value="Go" onclick="return confirm('Are you sure you want to search Google?')"/>
</form>
</body>
i could not not find a form with YES and NO buttons...can you help me to correct it
I have implemneted the below code_1 and code_2.
please let me know if the code is correct or needs to be modified...i do not have access to server moreover, I am new to ajax and spring mvc technologies.
code_1:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Ajax confirm delete prodcut</title>
<script
src="${pageContext.request.contextPath }/resources/js/jquery-1.6.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#confirmremoveform').click(function() {
var idx = $('#idx').val();
var ans = confirm("Are you sure you want to delete this Record?");
if (ans) {
$.ajax({
type: "DELETE",
url: "/product/remove/" + idx,
dataType : 'json',
contentType : 'application/json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#onsuccessfuldelete").text(data);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
});
}
</script>
</head>
<body>
<form action="http://www.google.com/search">
<input type="text" name="q" />
<input type="submit" value="Go" onclick="return confirm('Are you sure you want to search Google?')"/>
</form>
</body>
</html>
code_2
#Controller
#RequestMapping("/product/remove")
public class RemoveProductPageController {
public final static String sRemoveProductFromListAttributeName = "removeProductFromList";
public final static String CONTROLLER_URL = "/product/remove";
public final static String DO_REMOVE_HANDLER_METHOD_URL = CONTROLLER_URL + "/{idx}";
#Autowired
private ProductService productService;
#RequestMapping(value = "/{idx}",
method = RequestMethod.DELETE)
#ResponseBody
public ResponseEntity<String> doRemove(#Validated #Size(min = 0) #PathVariable(required = true) int idx,
Model model) {
Product productToBeRemove = productService.getProductFromListByIdx(idx);
if (productToBeRemove == null) {
return new ResponseEntity<String>("no product is avaialble at index:" + idx, HttpStatus.NOT_FOUND);
}
model.addAttribute(RemoveProductPageController.sRemoveProductFromListAttributeName, productToBeRemove);
productService.removeProdcutFromListBxIdx(idx);
return new ResponseEntity<String>("product removed from index: " + idx, HttpStatus.OK);
}
}
Try using SWAL(SweetAlert). It is a customizable replacement for javascript popups.
There are a lot of options you can choose from.
Example:
JSP,
On click of your delete button
$('#[idOfDeleteButton]').click(function (e) {
e.preventDefault();
swal({
title: 'Are you sure you want to delete this record',
type: 'warning',
showCancelButton: true
}).then(function () {
//execute once user confirms else nothing happens
var deleteLink = "[link to controller]?id="+[idTobeDeleted];
$.ajax({
url: deleteLink ,
contentType: "application/json",
type: 'GET',
success: function (res) {
//res is the string returned in the controller
if (res === "Success!") {
swal({
title: res,
text: "Delete Successful!",
type: 'success'
});
} else {
swal({
title: res,
text: "Deleting record Failed!",
type: 'error'
});
}
}
});
});
});
This question already has answers here:
Passing an object from JSP page back to Servlet
(3 answers)
Closed 6 years ago.
I have one Java Web Application.
My User_Objects class is given below
public class User_Objects {
public String firstName;
public String middleName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
}
I forward request with my Java User_Objects to JSP with using following code
User_Objects fillObj = fillData(request);
request.setAttribute("reqObj", fillObj);
RequestDispatcher view = request.getRequestDispatcher("/organization.jsp");
view.forward(request, response);
public User_Objects fillData(HttpServletRequest request) {
User_Objects fillObj = new User_Objects();
try {
fillObj.setFirstName(request.getParameter("txtFirstname"));
} catch (Exception e) {
}
try {
fillObj.setMiddleName(request.getParameter("txtMiddlename"));
} catch (Exception e) {
}
return fillObj;
}
I successfully receive this Object into my JSP form. But I want to send this Object again to the Servlet and When I click on Submit button on my JSP form and try to get this Object into my Servlet using below code
User_Objects obj = (User_Objects) request.getAttribute("reqObj");
request.getAttribute("reqObj") gives me null
My JSP form code is given below
<%# page import="otn.aitc.io.User_Objects" %>
<%# 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>Organization</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.12.4.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
$(function() {
var reqObj = '${reqObj}';
var reqStatus = '${orgStatus}';
var orgJson = '${reqOrgJson}';
orgJson = orgJson.replace("/", "'");
if(reqStatus != "" || orgJson != "") {
if(reqStatus == "false") {
document.getElementById("lblError").style.display = '';
}
else {
document.getElementById("lblError").style.display = 'none';
}
var availableTutorials = [];
if(orgJson != "") {
var parsed = JSON.parse(orgJson);
for(var x in orgJson) {
if(parsed[x] != undefined) {
availableTutorials.push(parsed[x]);
}
}
}
$("#txtOrgName").autocomplete({source: availableTutorials});
}
else {
window.location.href = "index.jsp";
}
});
function validateOrg() {
var orgName = document.getElementById("txtOrgName");
if (orgName.value.trim().length == 0) {
alert("Enter Org Name");
return false;
}
}
</script>
</head>
<body>
<form name="orgname" action="org_name" method="post">
<table align="center">
<tr align="center">
<td colspan="4"><img src="images/logo.jpg" /></td>
</tr>
<tr>
<td>Organization :</td>
<td><input type="text" id="txtOrgName" name="txtOrgName" /><label style="color: red;">*</label></td>
</tr>
<tr>
<td align="center" colspan=2><br/><input type="submit" name="btnOrgName" id="btnOrgName"
value="Validate" onclick="return validateOrg();" /></td>
</tr>
</table>
<p align="center"><label id="lblError" style="color: red;">Error Message.</label></p>
</form>
</body>
</html>
I am using Java with Eclipse.
Don't mix and match the different execution scopes.
The serlvet and the JSP page are executed on server side (actually the JSP page is compiled to a servlet, too). Once the HTTP request is finished all request based objects are discarded, including the request attributes.
In the end it is a templating engine producing HTML text.
This HTML text (with embedded JavaScript) is executed by the client's browser. This execution scope is totally different to your server request scope, which has created this HTML page. So in your JavaScript code all the Java objects used to create that page on server side are unknown and unaccessable.
So you have two alternatives.
While creating the HTML include enough information to recreate your server side object. E.g. if you have a Person object with name and age attributes, you can include name and age as hidden form fields. After submitting the form you can recreate the Person object with the hidden field values coming in as request parameters.
Pro: Simple to implement.
Con: Only feasable for small data. Data is exposed to the client and can be manipulated.
Store the object on server side inside the session.
Pro: Data is not exposed to the client.
Con: Implementation more complex because of possible concurrent access to the session variables (browser can do multiple requests for the same session at the same time).
I was able to send a simple String from javascript/local html in Webview to Java.
How do I send the whole form object to Java ?
public class JFXTest1 extends Application {
WebView webview = new WebView();
webview.getEngine().load(JFXTest1.class.getResource("local1.html").toExternalForm());
JSObject jsobj = (JSObject) webview.getEngine().executeScript("window");
Local1JSBridge bridge = new Local1JSBridge();
bridge.setWindow(jsobj);
jsobj.setMember("java", bridge);
And my bridge.
public class Local1JSBridge {
public void printFormData(String data1){
System.out.println( data1);
}
}
The javascript part that calls the method in the Java class.
<html>
<head></head>
<body>
hi :)
<form id="form1" name="form1">
<input type="text" id="text1">text value</input>
</form>
<button onclick="java.printFormData(document.getElementById('text1').value);">Submit</button>
<br/>
<button onclick="java.exit()">Exit</button>
</body>
I can't find a way to actually get the form data without executing Javascript back in the HTML document, but the following seems to basically work:
public void printFormData(Object form) {
System.out.println(form.getClass() + " " + form);
if (form instanceof Element) {
NodeList inputs = ((Element)form).getElementsByTagName("input");
for (int i = 0 ; i < inputs.getLength(); i++) {
Node input = inputs.item(i);
Element inputEl = (Element)input ;
String id = inputEl.getAttribute("id");
String value = (String) engine.executeScript(id+".value");
System.out.printf("%s : %s %n", id, value);
}
}
}
and then in the HTML:
<html>
<head></head>
<body>
hi :)
<form id="form1" name="form1">
<input type="text" id="text1">text value</input>
</form>
<button onclick="java.printFormData(document.getElementById('form1'));">Submit</button>
<br/>
<button onclick="java.exit()">Exit</button>
</body>
</html>
i'm new in a web service. i'm trying to make a simple web service REST on java for a simple login application.. here's my code:
Server side:
package com.testingws.webservices;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/login/{username}/{password}/{datetime}")
public class webServicesClass {
#GET // this method process GET request from client
#Produces("application/json") // sends JSON
public String getJson( #PathParam("username") String username, #PathParam("password") String password) { // empno represents the empno sent from client
if (username.equalsIgnoreCase("admin") && password.equalsIgnoreCase("admin")){
return "{'loginstatus':'success'}";
}
else{
return "{'loginstatus':'failed'}";
}
} // end of
}
Client side :
<!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>Client Login</title>
<script type="text/javascript">
function loginProcess(){
var tempUser = document.getElementById("loginUsername");
var tempPass = document.getElementById("loginPassword");
var dateTime = new Date();
var url = "http://localhost:8181/TestWSProject/authentication/login/" + tempUser.value + "/" + tempPass.value + "/" + dateTime.toUTCString();
var xmlhttp = new XMLHttpRequest(); //#slaks: i put it here
xmlhttp.open('GET',url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if ( xmlhttp.status == 200) {
var det = eval( "(" + xmlhttp.responseText + ")");
//alert(det.loginstatus);
if(det.loginstatus=="success")
{
setCookie("login", "yes", 1);
window.location="main.html";
}
else
{
alert("incorrect username or password");
}
}
else
alert("Error ->" + xmlhttp.status + xmlhttp.responseText);
}
}
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie()
{
var loginStatus=getCookie("login");
//alert(loginStatus);
if (loginStatus=="yes")
{
//alert("Masuk pengecekan")
window.location="main.html";
}
}
</script>
</head>
<body onload="checkCookie()">
<h2>LOGIN FORM</h2>
<BR>
Username : <input type="text" id="loginUsername"/>
<BR>
Password : <input type="password" id="loginPassword"/>
<BR>
<input type="button" value="Login" onclick="loginProcess()"/>
</body>
</html>
when i access my client from webContent url (http://localhost/TestWSProject/index.html) that service works perfectly, but if i access my client from stand alone HTML file (file:///D:/+Prog/webservice/TestWSProject/WebContent/index.html) it give me xmlHTTPStatus = 0 and that service is not works.. any solution for this problem?? really thanks..
Some browsers have security restrictions which restrict files from performing certain actions if they are being accessed directly from the file system.
This could be what is causing the error.