pass value and control from javascript to servlets - javascript

I have a jsp file with google map, place autocomplete and few buttons. The submit Button click calls a method in Javascript which inturn passes the jsp page 'input' data to callServlet() method as 'params'. I want to call a servlet page MyServlet and pass the params to it. However my callServlet() executes perfectly but doesn't pass on the control/params to MyServlet.
Also How to read params in MyServlet?
Please help me solve it.
JS code:
function callServlet(params) {
var xmlhttp = new XMLHttpRequest();
var url = "./mapServlet";
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
console.log(url);
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
console.log("Its perfect");
} else {
alert(xmlhttp.status);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)
// params is of json format with key value pairs
xmlhttp.send(params);
}
Servlet code: (Made no changes to this page. Its a simple servlet template)
public class MyServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { ... }
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.print("aaas");
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
web.xml
<servlet>
<servlet-name>mapServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mapServlet</servlet-name>
<url-pattern>/mapServlet</url-pattern>
</servlet-mapping>

Is there a specific reason you're not using jQuery for that?
Basically, xmlhttp.send(params) expects to receive key=value string, not a Json. If you intend to use bare XMLHttpRequest, you'll need to create this string on your own.
Also, this mapping: var url = "./mapServlet"; may be wrong, as usually you serve code from root, and your JS files are served from resource directory such as /js. Using `var url = "/mapServlet" would be better.
Finally, after you reach your servlet, you can read your parameters using request.getParameter("parameter_name")
To call your server using jQuery start with using jQuery.post() method:
https://api.jquery.com/jquery.post/
$.post( "./mapServlet", params)
.done(function( data ) {
console.log("Got ", data);
});

Related

Referencing a Java list from a Servlet in JavaScript

I have a list which is pulled from a Postgres database and I need to be able to reference/manipulate it with JavaScript.
I have updated the code as shown below:
Here is the Servlet's doGet method:
protected void doGet(HttpServletRequest req, HttpServletResponse json)
throws ServletException, IOException {
List<Employee> employees = uds.findAll();
req.setAttribute("employees", employees);
json.setContentType("application/json");
json.getWriter().write(String.valueOf(employees));
}
And here is what I currently have in JavaScript:
var ajax = new XMLHttpRequest();
ajax.open("GET", "http://localhost:8080/project1attempt/servlet", true);
// send request
ajax.send();
// event to get response
ajax.onreadystatechange = function() {
// Case state is 4 e o http.status for 200, your request is OK.
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
// the return
console.log(data);
}
}
}
The issue I am having at this point is that the client is not receiving data in JSON format. If I log the data as shown above, the log will produce something along the lines of the following:
[Employee{, employee_id='123456', email='lt#gmail.com', firstName='Juan',
lastName='Terri'}, Employee{, employee_id='2', email='sstark#mail.com',
firstName='Sansa', lastName='Stark'}]
This is the correct data, but not in a useful format.
However, if I try to do console.log(JSON.parse(data)), then I receive Uncaught SyntaxError: Unexpected token E in JSON at position 1.
I believe this is a simple syntax error on my part in the servlet, but am unsure of how to fix it.
You should use request.getAttribute():
<%
List<Employee> theEmployees = request.getAttribute("employees");
%>
But if you want to effectively use it in your javascript , it is recommended to convert it to json .
Try change your servlet response to json and get your data with Ajax
This is a sample to do it!
var ajax = new XMLHttpRequest();
ajax.open("GET", "your_url_here", true);
// send request
ajax.send();
// event to get response
ajax.onreadystatechange = function() {
// Case state is 4 e o http.status for 200, your request is OK.
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
// the return
console.log(data);
}
}
For other noobs like me, I've compiled the following complete solution for this issue:
The Servlet should look something like this:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
resp.setContentType("application/json");
List<Employee> employees = uds.findAll();
String json = new ObjectMapper().writeValueAsString(employees);
resp.getWriter().write(json);
uds.findAll() is a method which returns a list of objects. ObjectMapper is a Jackson utility (Gson is another option, I believe). This puts the list into JSON format.
The HTML or JSP should look like this:
var ajax = new XMLHttpRequest();
ajax.open("GET", "http://localhost:8080/project1attempt/servlet", true);
// send request
ajax.send();
// event to get response
ajax.onreadystatechange = function() {
// Case state is 4 e o http.status for 200, your request is OK.
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
// the return
console.log(JSON.parse(data));
}
}
This will get the list of objects in a usable format which you can then manipulate with JavaScript to do whatever you'd like. Hopefully this will help someone!

Send redirect to url in post method

I am trying to add parameter and redirect to a page that only accepts request in post method. I am using this code in my servlet and it is not forwarding me to the url.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String url = "http://www.thisone.com";
InputStream in = null;
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
//Add any parameter if u want to send it with Post req.
method.addParameter("User", "xyz");
method.addParameter("Name", "abc");
int statusCode = client.executeMethod(method);
System.out.println(statusCode);
if (statusCode != -1) {
response.sendRedirect(response.encodeRedirectURL(url));
in = method.getResponseBodyAsStream();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I don't think it's possible to redirect with post method using this approach. what you can do is get the response to the client and therefore set the location header in response. Implementation for the same is given below:
Once your condition is satisfied:
response.setStatus(307);
response.addHeader("Location", "<url>");
also check out the significance of 307 status code.
Here is the javascript code, which starts with an ajax request and hit a servlet to fetch the desired URL, once it receives the URL, creates a HTML form object, sets values and submits the form...
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callURL(this.responseText);
}
};
xhttp.open("GET", "TestServlet", true);
xhttp.send();
function callURL(url){
var form = document.createElement("form");
form.setAttribute('method', 'POST');
form.setAttribute('action', url);
form.setAttribute('id', 'frmProduct');
form.style.display = 'none';
var i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'name');
i.setAttribute('value', 'Neeraj');
form.appendChild(i);
document.getElementsByTagName('body')[0].appendChild(form);
form.submit();
}
</script>
Below is the implementation of my Testservlet
#WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = "http://www.thisone.com";
PrintWriter out = response.getWriter();
out.print(url);
}
}
You can make use of automatic form submit using POST method to do the same.
Please find below sample code:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
sendPOSTRedirect(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
sendPOSTRedirect(request, response);
}
private void sendPOSTRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
String postURL = "url to send data";
String value1 = "value for name1";
String value2 = "value for name2";
String content = "<html><body onload='document.forms[0].submit()'><form action=\"" + postURL + "\" method=\"POST\">"
+ "<INPUT TYPE=\"hidden\" NAME=\"name1\" VALUE=\"" + value1 + "\"/>"
+ "<INPUT TYPE=\"hidden\" NAME=\"name2\" VALUE=\"" + value2 + "\"/>"
+ "</form></body></html>";
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.write(content);
}

Jquery ajax request to server returning error code 405 on live server?

The following code is working fine when I run the application on localhost but it is not working when hosted on the live server, as the ajax request returned a error code
405 HTTP method get is not supported by this url.
I have making a get request and also handling this request in doGet method then what went wrong when I try to run this code on live server.
NOTE: only posting the required code js code
Client side code
$.ajax({
type:"GET",
url:"fetchdata1",
data:"cat="+cat,
success:function(data){
}
});
server side code
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String cat = request.getParameter("cat");
PrintWriter out= response.getWriter();
ArrayList<product> p = new ArrayList();
try {
con=ConnectionManager.getConnection();
ps = con.prepareStatement("Select product_id,images.product_name,image_name,company_name,price "
+ "from images,products where images.product_name = products.product_name AND "
+ "category_name = ?");
ps.setString(1,cat);
rs=ps.executeQuery();
while(rs.next())
{
product pr =new product();
pr.id = rs.getInt("product_id");
pr.name = rs.getString("product_name");
pr.company =rs.getString("company_name");
pr.image = rs.getString("image_name");
pr.price = rs.getDouble("price");
p.add(pr);
}
String json = new Gson().toJson(p);
response.setContentType("application/json");
out.println(json);
}

Getting a json object from HttpServletResponse

I am sending a json object via ajax call.
When I try to print the json's values I am getting nulls.
What am I doing wrong?
Servlet:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("[{\"PARENT\":\"2\",\"VAL\":\"X7280\"},{\"PARENT\":\"2\",\"VAL\":\"X8338\"}]");
}
javascript:
function handleIt() {
var url = "myservlet";
var parameters = "method=method";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4) {
var ddl3 = http.responseText;
for(var key in ddl3){
var id = ddl3[key].PARENT;
var lbl = ddl3[key].VAL;
alert (lbl);
}
}
}
http.send(parameters);
}

error ajax and Jena

When I try to call Jena using AJAX in my servlet I get this error:
java.lang.ClassNotFoundException: com.hp.hpl.jena.sparql.core.Prologue
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361)
at fr.objective.blogomatic.semantic.web.ServletAjax.doGet(ServletAjax.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
This is my Jena code:
class classUsingJena {
public void execute(){
String queryString = PREFIXES
+ " Select ?label "
+ " where {"
+ " ?description j.5:entity-label ?label ." + " } ";
Query query = QueryFactory.create(queryString);
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();
ResultSetFormatter.out(System.out,results, query);
qe.close();}
}
It's running fine, but when I call this function using servlet I get the error described previously.
This is my servlet code:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String service = req.getParameter("service");
classUsingJena jena= new classUsingJena() //bug
return;}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
#Override
public void init() throws ServletException {
ServletConfig config = getServletConfig();
urlAjax = config.getInitParameter("urlAjax");
}
My java script code that runs fine:
$("#Analyser").click(function(){
var article = $("#TxtArea").val();
ajaxFunction("acteur",article);
console.log(article);
});
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction(valeur,txt) {
if(xmlhttp) {
xmlhttp.open("GET","ajax?service=ajax&valeur="+valeur+"&text="+txt,true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
$("#J").text("");
parseXml(xmlhttp.responseXML);
}
else {
//alert("Error during AJAX call. Please try again");
}
}
}
function parseXml(xml)
{
$(xml).find("nom").each(function()
{
$("#J").append($(this).text() + "<br />");
});
}
In the pom I had declared the old version of Arq 1.8.7 instead of 2.8.7. Now it's running fine.

Categories

Resources