I'm calling my Java Servlet with an AJAX call, but I'm not able to read the input parameter from the request. I've tried two ways but with no luck:
var id;
$("#scan").click(function() {
id = 1;
$.ajax({
type: "POST",
data: id,
url: "http://10.1.42.249:8080/test-notifier-web/RestLayer"
});
});
And:
id = 1;
$.post('http://10.1.42.249:8080/test-notifier-web/RestLayer', {
reqValue: id
}, function(responseText) {
// $('#welcometext').text(responseText);
alert("OK!!!");
});
My servlet code is a simple log print of the request parameter, but the return value is always null:
String reqID = "";
log.info("Servlet called");
reqID = request.getParameter("reqValue");
log.info("reqID = " + reqID);
How can I get this working?
The only way I've found to get the code working is manually add the parameter to servlet url, like http://10.1.42.249:8080/test-notifier-web/RestLayer?reqValue=1
i have check you code.this is my working code.
<%# 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>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var id;
function fun() {
alert("aaaa");
id = 1;
$.ajax({
type : "POST",
data : {
reqValue : id
},
url : "/WebProject/callAjax"
});
}
</script>
</head>
<body>
<button id="scan" onclick="fun()">Sacn</button>
</body>
</html>
//Servlet
#WebServlet(urlPatterns = {"/callAjax",})
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameter("reqValue"));
}
}
var id;
$("#scan").click(function() {
id = 1;
$.ajax({
type: "POST",
data: { reqValue : id},
url: "http://10.1.42.249:8080/test-notifier-web/RestLayer"
});
});
There are different methods you need to override in servlet. Those are doPost(), doGet(), service() and etc.
I suspect you are using doGet() method that's why when you add parameter to the URL your java code is working and in other two cases as you are using type : "POST" java code is unable to read the data from Request Body( in post method the data will be added to Request Body).
I suggest you to use doPost() or service() methods instead doGet().
Related
I just started learning JSP and Java servlets and I stumbled upon an issue. I will use a simple example to show this unexpected behavior.
I have a .jsp file which has a button and makes an ajax request when clicking the button:
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP - Hello World</title>
</head>
<body>
<button class="btn">Test button</button>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(".btn").click(function () {
$.ajax({
url: "hello-servlet",
method: "GET",
data: {action: "action", arg: "someData"}
})
}
);
</script>
</html>
And this is the servlet that the above .jsp file references:
package com.example.demo;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
public HelloServlet() {
super();
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
String data = req.getParameter("arg");
System.out.println(action + ", " + data);
}
}
And there is no issue. It works. If I run it, or use the debugger to test it, I get the expected behavior. It prints action, someData so the parameters of the request were successfully retrieved in the servlet.
Now, I will change just this: the method argument in the ajax call from GET into PUT and the method I override in the servlet from doGet into doPut:
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP - Hello World</title>
</head>
<body>
<button class="btn">Test button</button>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(".btn").click(function () {
$.ajax({
url: "hello-servlet",
method: "PUT",
data: {action: "action", arg: "someData"}
})
}
);
</script>
</html>
And the servlet:
package com.example.demo;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
public HelloServlet() {
super();
}
#Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
String data = req.getParameter("arg");
System.out.println(action + ", " + data);
}
}
I expected it to work in the same way. This does not happen. The output is null, null. The request parameters cannot be retrieved if I use PUT in the ajax call. I added the previous function doGet to the servlet to see if maybe the request doesn't make it to the PUT handler and defaults to GET. I used the debugger and I noticed that the execution does indeed enter the doPut handler, which is good, since that's what we expect to happen. It's just that at each req.getParamter() call I get null returned. I cannot retrieve the parameters if I use PUT, but I can retrieve them if I use GET (or POST for that matter, I tried it). This is weird to me and unexpected. What is going on and what can I do to solve it?
I have a JPS page from which I want to execute a shell script placed on server:
Below code works fine and "/tmp/Sample.sh" script is getting executed on server.
Now I want to do 2 things:
1.The script is getting executed as soon as page is loaded, but i want to execute it only when button is clicked.
2.I understand that use of scriplets is discouraged, what I googled is that I should call a servlet, when button is clicked, in which i can move the java code.
I'm new to these terminologies as my primary skill is not java.
I have readed theory of servlet but , not getting how exactly i can achieve above two functionality.
Any help in achieving above two points would be greatly appreciated
<%# 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></title>
</head>
<body>
<%
String unixCommand = "sh /tmp/Sample.sh";
Runtime rt = Runtime.getRuntime();
rt.exec(unixCommand);
%>
</body>
</html>
UPDATED CODE AS PER SUGGESTIONS:
http://10.111.24.21:7001/Project_1/Test_1.jsp
<%# 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></title>
</head>
<body>
<button onclick="location.href = 'http://10.111.24.21:7001/Project_1/JavaServletClass.java';" id="RedirectButton" > Execute</button>
</body>
</html>
http://10.111.24.21:7001/Project_1/JavaServletClass.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class JavaServletClass extends HttpServlet
{
public void init() throws ServletException { }
private void ExampleMethod() throws IOException
{
String unixCommand = "sh /tmp/Sample.sh";
Runtime rt = Runtime.getRuntime();
rt.exec(unixCommand);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ExampleMethod();
out.println("<h1>" + "Method Executed" + "</h1>");
}
public void destroy() { }
}
Jsp page translates to servlet eventualy so ofc it is possible to do same thong that you did in servlet. If usage of JSP page is absolutely necessery you can do fallowing things:
Create servlet follow tutorial on Create Servlet
create method to execute command
private void ExampleMethod() {
String unixCommand = "sh /tmp/Sample.sh";
Runtime rt = Runtime.getRuntime();
rt.exec(unixCommand);
}
Call method from doGet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Call commands
PrintWriter out = response.getWriter();
ExampleMethod();
out.println("<h1>" + Method Executed + "</h1>");
}
Replace scriptlet in body of jsp with:
<button onclick="location.href = 'http://localhost:8080/SERVLETNAME';"
id="RedirectButton" > Execute</button>
Replace server name, location (localhost:8080) with youre values ...
FORGET ALL OF THAT AS SERVLETS AND SCRIPTING IN HTML IS SO OLD AND OBSOLETE IT SHOULD NOT BE USED ANY MORE
I have made an AJAX call to a JSP, which in turn calls a Java method in a separate Java class. All files are in the same folder.
For some reason, I can't get the correct value returned to AJAX. It simply prints the whole JSP content.
JavaScript:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(true){
alert('hello!');
var response = xhr.responseText;
alert(response);
document.getElementById('newgame').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'javaconnect.jsp', true);
xhr.send(null);
JSP:
<%# page import="com.example.Server"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
Server tc = new Server();
out.print(tc.highScore());
%>
</body>
</html>
Java class:
package com.example;
public class Server {
public String highScore() {
return "hello!!!";
}
}
The best solution is to use a Servlet to make the control layer in place of jsp that instantiates the Server class, like:
public class HelloWorld extends HttpServlet {
protected void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Server tc = new Server();
String txt = tc.highScore();
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(txt);
}
}
Do not forget to map the servlet and change the url of the ajax call.
You can test call
Im trying pass specific element from my Model to servlet to jsp.
This is working in my servlet: System.out.println(beanModel.getSortedDomainList().get(0).split(";")[1]) When I go to http://localhost:8080/Comparebet/Controller
But I dont know what Im doing wrong since I dont get it to my jsp. All tutorials ive been watching is mostly input parameters or they put code in the JSP.
UPDATE EDIT
Tried with this in my JSP and I get "null"
<%= request.getAttribute("rank1") %>
SERVLET
#WebServlet("/Controller")
public class Controller extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ArrayList<String> sortedDomainList = new BeanModel().getSortedDomainList();
BeanModel beanModel = new BeanModel();
request.setAttribute("rank1", beanModel.getSortedDomainList().get(0).split(";")[1]);
RequestDispatcher view = request.getRequestDispatcher("view.jsp");
view.forward(request, response);
//TESTING SERVLET
System.out.println(beanModel.getSortedDomainList().get(0).split(";")[1]);
System.out.println("CONTROLLER CALLED");
// System.out.println(${rank1});
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
}
}
JSP
<%# 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>CompareBet</title>
</head>
<body>
<form action="/Controller/*" method="get">
<h1>${rank1.getSortedDomainList().get(0).split(";")[1] } </h1>
</form>
</body>
</html>
In your JSP try this, instead of rank1.getSortedDomainList().get(0).split(";")[1]
<h1>${request.rank1 } </h1>
You have already done beanModel.getSortedDomainList().get(0).split(";")[1] in your servlet and have added the result to the request scope object.
Try to replace this line in your jsp:
<h1>${rank1.getSortedDomainList().get(0).split(";")[1] } </h1>
To this:
<h1>${rank1} </h1>
In JSP you can access this data using the expression language like ${rank1}.
And take it out from the <form like this:
<form action="/Controller/*" method="get">
...
</form>
Try to use <h1><%= request.getParameter("rank1")%></h1>
i have requirement i.e., i need to pass array of javascript to servlet. please guide me thanks
qwe.js
<script type="text/javascript">
var array2 = [];
function getTotalTests() {
console.log("called");
console.log("called"+array1.length);
for (i=0; i < array1.length; i++) {
array2[i] = array1[i];
console.log(array2[i]);
}
};
</script>
i need pass array2 to servlet
You will need to make a request of some sort to achieve this. If you do not wish to make a complete request, you can look at https://api.jquery.com/jQuery.ajax/ to make an asynchronous request and display the changes made(if required).
JSP page
<%# 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>Insert title here</title>
</head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function func()
{
var arr=[2,3,3];
var form = $('<form action="Test" method="get">' +
'<input type="hidden" name="id" value="'+arr+'">' +
'</form>');
alert( $(form));
$(form).submit();
}
</script>
<body>
<button onclick="func()">Deepak</button>
</body>
</html>
Servlet
package test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Test
*/
#WebServlet("/Test")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public Test() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println(request.getParameter("id"));
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
you can pass by using ajax
$.ajax({
type: "POST",
url: "servletname", //Your full URL goes here
data: {
dataname: datavalue
},
success: function (data, textStatus, jqXHR) {
},
error: function (jqXHR) {
}
});