Tunnelling DELETE through XMLHttpRequest.setRequestHeader() for a REST call - java

I'm unable to perform "delete" from the HTML form. This is my HTML, what's incorrect here? , also included the RESTservice method that performs deletion. I see the POST is getting invoked after every button click. Any inputs or suggestions ?
create_todo.html
<!DOCTYPE html>
<html>
<head>
<title>Form to create a new resource</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script>
document.getElementById("delete").addEventListener("click", function () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8080/com.dcr.jersey.first/rest/todos", true);
xhr.setRequestHeader("Content-Type", "application/xml");
xhr.setRequestHeader("X-HTTP-Method-Override", "DELETE"); //X-HTTP-Method-Override
xhr.send();
},true);
</script>
</head>
<body>
<form id= "myForm" action="../com.dcr.jersey.first/rest/todos" method="post" >
<label for="id">ID</label>
<input name="id" />
<br/>
<label for="summary">Summary</label>
<input name="summary" />
<br/>
Description:
<TEXTAREA NAME="description" COLS=40 ROWS=6></TEXTAREA>
<br/>
<input type="submit" id="submit" value="Submit" /> <br/>
<button id="delete">Delete</button>
</form>
</body>
</html>
REST method for DELETE from form
#DELETE
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void delTodo(#FormParam("id") String id,
#Context HttpServletResponse servletResponse) throws IOException {
Todo c = TodoDao.instance.getModel().remove(id);
if(c==null)
throw new RuntimeException("Delete: Todo with " + id + " not found");
else servletResponse.sendRedirect("../create_todo.html");
}
RESTResourceClient to post and delete which works fine
Form form = new Form();
form.param("id","45");
form.param("summary","Summary for id 45");
response = target.path("rest").path("todos").request().post(Entity.form(form));
System.out.println("\nPost by FORM response code is "+ response.getStatus()+"\n");
response = target.path("rest").path("todos/45").request().delete();

Related

eventpreventDefault() not working I need to show the results on same page

I have added the java script file in the html for a form and it is connected to the java file I want to show data on same page after submit i.e index.html but after the submission it takes me to the register page.
html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<title>Register form</title>
</head>
<body>
<form method="post" action="register">
Name:<input type="text" name="name" /><br/>
Email ID:<input type="text" name="email" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="submit" />
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#register").bind('submit',(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post with element id name and name2*/
var posting = $.post( url, { name: $('#name').val(), email: $('#email').val(),pass: $('#pass').val() } );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
</form>
</body>
</html>
The forms needs an id in order to be called with the query selector #register.
<form method="post" action="register" id="register">

Calling method onClick of Jsp form Jsp

I wish to call a method in JSP onClick, the method is on the same JSP inside scriptlet.
How should I archive this?
<%# page import="java.io.*,java.lang.*,java.util.*,java.net.*,java.util.*,java.text.*"%>
<%# page import="javax.activation.*,javax.mail.*,org.apache.commons.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*"%>
<%!
public String sendMail(String to, String sub, String msg) {
String res = null;
System.out.println("HI");
return res;
}%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<form>
<label>Email To</label><br />
<input type="text" name="to" /><br />
<label>Subject</label><br />
<input type="text" name="sub" /><br />
<label for="body">Message</label><br />
<input type="text" name="msg" /><br />
<input type="submit" onClick="sendMail( to, sub, msg )"/>
</form>
</body>
</html>
Note
The methods name is "sendMail", It's called on submit button
I want to do the whole code in JSP only.
The onclick event occurs when the user clicks on an element. This attribute has the ability to call JS functions (front end)
In your case, you want to call a JAVA function (server side) so the best way is to move the java code to a servlet and use it.
Anyway if you want to keep the JAVA function in the jsp, you can do this via ajax in this way
<script type="text/javascript">
$(document).ready(function() {
$('#sendMailBtn').click(function (){
$.ajax({
type: "post",
url: "/path",
data: "email=" + $('#email').val() + "&subject="+$('#subject').val() + "&msg=" + $('#msg').val(),
success: function(msg){
//
}
});
});
});
</script>
AJAX is a developer's dream, because you can
Update a web page without reloading the page
Request data from a server - after the page has loaded
Receive data from a server - after the page has loaded
Send data to a server - in the background
Check the full code here
<%# page import="java.io.*,java.lang.*,java.util.*,java.net.*,java.util.*,java.text.*"%>
<%# page import="javax.activation.*,javax.mail.*,org.apache.commons.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*"%>
<%!
public String sendMail(String to, String sub, String msg) {
String res = null;
System.out.println("HI");
return res;
}
%>
<html>
<head>
<title>Send Email using JSP</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<form>
<label>Email To</label><br />
<input id="email" type="text" name="to" /><br />
<label>Subject</label><br />
<input id="subject" type="text" name="sub" /><br />
<label for="body">Message</label><br />
<input id="msg" type="text" name="msg" /><br />
<input id="sendMailBtn" type="submit" />
</form>
</body>
<script type="text/javascript">
$(document).ready(function() {
$('#sendMailBtn').click(function (){
$.ajax({
type: "post",
url: "/path",
data: "email=" + $('#email').val() + "&subject="+$('#subject').val() + "&msg=" + $('#msg').val(),
success: function(msg){
//
}
});
});
});
</script>
</html>
For more information check
AJAX Introduction: http://www.w3schools.com/xml/ajax_intro.asp
onclick Event: http://www.w3schools.com/tags/ev_onclick.asp
JSP- Executes on Server.
JavaScript - executes in browser.
No you cannot call that JSP magically from JS. However you can send an Ajax request or post the form to jsp. BTW, I strongly suggest you to move the java code to a servlet and use it.
This is what I ended up doing
<%# page import= "java.io.*,java.lang.*,java.util.*,java.net.*,java.util.*,java.text.*"%>
<%# page import="javax.activation.*,javax.mail.*,org.apache.commons.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*"%>
<%!
public String sendMail(String to, String sub, String msg) {
String res = null;
System.out.println("HI");
return res;
}
%>
<%
String a = request.getParameter("to");
if(a != null){
sendMail(request.getParameter("to"),request.getParameter("sub"),request.getParameter("msg"));
}
%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body><center>
<form action="#" method="post">
<label>Email To</label><br />
<input type="text" name="to" /><br /> <br />
<label>Subject</label><br />
<input type="text" name="sub" /><br /> <br />
<label for="body">Message</label><br />
<input type="text" name="msg" /><br /> <br />
<input type="submit"/>
</form>
</center></body>
</html>
The action="#" reloads the page, and there is a if condition which calls the required method if the parameter is not blank( Please keep in mind that by default on first call the parameter will be null ).

Use web service in background of HTML

I have a web service and a html page and i want to calculate two values and show on the third text field but this code shows me on the next page. Any one help me for my FYP.
My index.html
<!DOCTYPE html>
<html>
<head>
<title>TO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>JAX-RS</h1>
<form action="http://localhost:8080/ConnectingToNode/webapi/myresource?ID" method="post" target="_self">
<p>
Number1 : <input type="text" name="number1" />
</p>
<p>
Number2 : <input type="text" name="number2" />
</p>
<p>
Number3 : <input type="text" name="number3" />
</p>
<input type="submit" value="Add" />
<p>
Total : <input type="text" name="number3" />
</p>
</form>
</body>
</html>
My web service
#Path("myresource")
public class MyResource{
HashMap<String, String> map= new HashMap<String, String>();
#POST
#Produces(MediaType.TEXT_PLAIN)
public Response addNumber(
#FormParam("number1") int number1,
#FormParam("number2") int number2
) {
int total=number1+number2;
return Response.status(200).entity("Total : " + total).build();
}
}
You want perform an ajax call instead of submitting the form. So just build a javascript function e.g. using Jquery:
$.post("<your servlet here>", $("#y<ourFormIdHere>").serialize(),callback);
Where callback is a function like this:
function(data){
console.log("Data",data); // do what you want with response data
}
Off course you have to bind the $.post function to your form button.

Liferay: How to make enctype="multipart/form-data" and method="post" work together?

I'm developing a web app using liferay portal server 6.2
JSP code -
<form id="mainForm" action="<portlet:actionURL/>" method="post" enctype="multipart/form-data" >
<input type="hidden" id="varImport" name="varImport"/>
<div class="tab-pane" id="uploadFile">
<p>Please upload a file</p>
<div id="inputFileDiv">
<input type="file" name="uploadFile" />
</div>
</div>
<input type="submit" class="btn btn-info" onClick="import()" value="IMPORT" />
</form>
<script>
function import() {
console.log("importing");
document.getElementById("varImport").value = "IMPORTFILE";
document.getElementById("mainForm").submit();
}
</script>
Servlet code -
#Override
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
System.out.println("myPortlet.processAction() >> " + request.getParameter("varImport"));
//... rest of the code.
}
If I remove enctype from jsp form, I get the value of varImport in my servlet.
But if i keep it, it returns null.
What am i missing?
import com.liferay.portal.util.PortalUtil;
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
System.out.println("myPortlet.processAction() >> " + uploadRequest.getParameter("varImport"));

How to redirect to pop-up after form submission with spring validator messages?

I have one JSP page test.jsp in which one button is there "show Form". After clicking "show Form" a form is opening in pop-up which is a jsp page "form.jsp".
For validating the fields of form.jsp I am using Spring validator.
I want to submit the form page in pop-up and show the same "form.jsp" in same popup with spring validator error messages. Anybody having sugestions for this ??
test.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
function showForm()
{
var requestUrl="${pageContext.request.contextPath}/test/show/form;
try{
$.ajax(
{
type: 'GET',
url: requestUrl,
success: function(data){
$("#dialog_form").html(data);
$("#dialog_form").dialog( "open" );
},
error: function(xhr, ajaxOptions, thrownError){
console.log("Error in displaying rights");
}
});
}catch(e){
console.log("Error in displaying rights");
}
}
</script>
</head>
<body>
<input class="button" value="Show Form" type="button" onClick="showForm();">
<div id="dialog_form"></div>
</body>
</html>
form.jsp
<form:form method="post" commandName="employee" id="employeeForm" action="${pageContext.request.contextPath}/test/submit">
<p>
<label>Name</label>
<span ><form:input path="name" id="nameId" /></span>
<span class="required" id="nameErrors"><form:errors path="name"/></span>
</p>
<p>
<label>Last Name</label>
<span ><form:input path="lastName" id="lastNameId" /></span>
<span class="required" id="lastNameErrors"><form:errors path="lastName"/></span>
</p>
<input class="button" value="Submit" type="submit" id="submitButton">
</form:form>
in TestController.java
#RequestMapping(value = "/show/form", method = RequestMethod.GET)
public ModelAndView showForm() {
mav = new ModelAndView();
Employee emp = new Employee();
mav.addObject("employee", emp);
mav.setViewName("show_form");
return mav;
}
#RequestMapping(value = "/submit", method = RequestMethod.GET)
public ModelAndView subForm(#ModelAttribut Employee employee, BindingResult result, HttpServletRequest request) {
mav = new ModelAndView();
validator.validate(employee);
mav.addObject("employee", employee);
mav.setViewName("show_form");
return mav;
}

Categories

Resources