Java ajax passing values from jsp to servlet - java

I am trying to pass basic values such as id from jsp to the servlet through ajax. I tried everything but only null is being passed. Even console.log(val) does not print anything to browser console.
My understanding is: Web page has form values which onsubmit calls js file. js has ajax which calls the servlet and passes the data of the form. The servlet grabs data from ajax by request.getParameter(val)
Here is my code:
Main.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>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript">
<script src="js/main.js" type="text/javascript"></script>
</head>
<body>
<form method="post" action="Main" id="firstform">
<h1>Enter name:</h1>
<input type="text" name="id" id="id" />
<input type="submit" name="submit"/>
</form>
</body>
</html>
main.js
var form = $('#firstform');
console.log("gi");
form.submit(function()
{
$.ajax({
url: 'Main',
data: form.serialize(),
type: 'post',
success: function(data){
console.log(data);
}
});
//return false;
});
Main.java
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
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 Main
*/
#WebServlet("/Main")
public class Main extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Main() {
super();
// 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
int ids;
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String val = request.getParameter("id");
System.out.print(val);
if(val != null){
ids = Integer.parseInt(val);
out.print(ids); //
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
**Problems:
1)values passed from jsp to servlet
2)console.log doesnt print anything on browser console
1) works but 2) still doesnt.**

in main.js type is type: 'post' and you have written code in get method
do type:'get'

there is no name attribute in your input field. when you are doing
String val = request.getParameter("id");
then in servlet then it will search for the input field having name="id" but in your form there is nothing so it will return null;
give name to the input field like
<input type="text" id="id" name="id"/>
also as sanjay has said your ajax has type post so change it to get as well

Just for the console.log(data) problem, may be $.ajax() function get confused with response type, try this:
Ajax
$.ajax({
url: 'Main',
data: form.serialize(),
type: 'post',
dataType:'text/plain',
success: function(data){
console.log(data);
}
});
Servlet
response.setContentType("text/plain;charset=UTF-8");

Related

asking to use GET in a servlet where i have only used POST method

This is my html code
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>New Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form method="post" action="display">
I have used POST method above for servlet action
Enter Name: <input type="text" name="name">
Enter City <input type="text" name="city">
<input type="submit" name="submit">
</form>
</body>
</html>
Servlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class servlet1 extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
used "doPost" for the POST method defined in the html form
{
response.setContentType("text/html");
Cookie c1 = new Cookie("name",request.getParameter("name"));
Cookie c2 = new Cookie("city",request.getParameter("city"));
response.addCookie(c1);
response.addCookie(c2);
redirecting to 2nd servlet through this form
response.sendRedirect("servlet2");
}
}
servlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class servlet2 extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
I am getting an error saying "HTTP GET Method is not supported by this url", however I have nowhere mentioned GET in my code.
{
response.setContentType("text/html");
Cookie c[] = request.getCookies();
PrintWriter pw = response.getWriter();
for(Cookie cookie : c)
{
if(cookie.getName().equals("name") ||
cookie.getName().equals("city"))
{
pw.println(cookie.getValue()+"<br>");
}
}
pw.println("Print using cookie");
}
}
the servlet works perfectly fine if I use "doGET" method in servlet2.java. However I am using POST method then why does it require "doGET"??
I get the below error for the above code.
HTTP Status 405 - HTTP method GET is not supported by this URL
type: Status report
message: HTTP method GET is not supported by this URL
description: The specified HTTP method is not allowed for the requested
resource.
Apache Tomcat/7.0.56

html requested resource not available for servlet [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 5 years ago.
I am trying to connect html to a servlet to get the user input but I get an error that says The requested resource is not available. I even put the servlet on the same folder as the html file, but the error keeps coming. I have the servlet both in Java resources and in html folder (web content). It should be visible. Below is my code for html file and servlet.
html file:
<!DOCTYPE html>
<html>
<!--This is the login page.-->
<head>
<meta charset="ISO-8859-1">
<title>Login Page</title>
<style>
body {
background-color: lightblue;
backroung-repeat: repeat-1 ;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body background="https://cdn4.iconfinder.com/data/icons/gray-user-management/512/login-512.png" >
<h1>Autentification</h1>
<form action="ConnectionMaker" method="post">
User name:<Input type="text" name="user"><br/><br/>
Password:<Input type="password" name="pass"><br/><br/>
<input type="submit" value="Submit">
login
</form>
</body>
</html>
and servlet:
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 ConnectionMaker
*/
#WebServlet("/DBConnection")
public class ConnectionMaker extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ConnectionMaker() {
super();
// 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
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
String user = request.getParameter("user");
String pass= request.getParameter("pass");
System.out.println(user+" "+pass);
}
}
Change <form action="ConnectionMaker" method="post"> to <form action="DBConnection" method="post"> or maybe /DBConnection (with slash). You hit the URL, not the class name.
Also, why call doGet inside doPost?

HttpServlet - add context to html page

I want to understand how a html page can call a servlet to add elements to its body but i can't find the right way to achieve that can you give me or refer me to an example of doing this?
Example:
lets suppose there is an html page with a form that contains a button with:
name="I am"
value="the button"
Example scenario:
click this button
call a servlet
add a message to this page saying "I am the button"
many thanks for any guidance.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$("#btn").click(function() {
$.post("buttonServlet", function (response) {
alert(response);
});
});
</script>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>My Button</title>
</head>
<body>
<input type="button" name="btn" id ="btn" value="The Button" />
</body>
</html>
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/buttonServlet")
public class ButtonServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("I am the button");
}
}
You can do this by using Ajax.
In your html page contain a button ,
<input type="submit" id="button1" value="the button" name="I am" onclick="showMsg()" />
Implement ajax,
function showMsg() {
var buttonMsg = document.getElementById("button1").name + document.getElementById("button1").value;
$.ajax({
url: "yourservlet",
type: "post",
data:{'msgVar': buttonMsg} ,
cache: false,
success: function (data) {
//depends on the method you want to show your message
//the variable data contain the message you want
alert(data); //to show in popout message
}
});
}
Assuming your servlet POST method contain following variable
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String message = request.getparameter("msgVar");
out.println(message);

HTTP Status 404. description The requested resource is not available [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I've got a page here. When I click the submit button, I get the 404 page saying:
HTTP Status 404 - /Email/EmailGet
type Status report
message /Email/EmailGet
description The requested resource is not available.
Apache Tomcat/7.0.47
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>
</head>
<body>
<form action="EmailGet" method="GET">
Email: <input type="text" name="email"> <br> Password: <input
type="password" name="password"> <br> <input
type="submit" value="Submit">
</form>
</body>
</html>
Here's the EmailGet code:
package email;
import java.io.IOException;
import javax.mail.Session;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class Controller
*/
#WebServlet("/EmailGet")
public class EmailGet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public EmailGet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Gets the entered email and password
String username = request.getParameter("email");
String password = request.getParameter("password");
//Creates the session and sets the session attributes
HttpSession session = request.getSession();
session.setAttribute("username", username);
session.setAttribute("password", password);
RequestDispatcher dispatcher;
//Calls the setCredentials method to check if entered credentials are valid
boolean result = SendSMTPMail.setCredentials(username, password);
//if valid, forwards to send page
if (result == true) {
dispatcher = request.getRequestDispatcher("send.jsp");
dispatcher.forward(request, response);
}
//if not valid, forwards to index page with error message displayed
else {
dispatcher = request.getRequestDispatcher("indexerror.jsp");
dispatcher.forward(request, response);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Any ideas? It used to forward the page fine, but seems not to be working now.
Each jsp page runs fine individually, it's just the forwarding that isn't working.
It seems. . . that the requested page does not exist. I don't know the names of you files, so i can only guess that you have a typo somewhere, try to check your url bar and check if this is really the url you wanted.

neglect it--------------Sending an array to servlet from jsp page and recieving it in servlet------------ neglect it

*
neglect it
*
I am lerner in JSP and java field. I am stuck in a problem. I hv mentioned my code below.
My JSP 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>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$("#save").click( function ()
{
var arrayxx= new Array(5);
arrayxx[0]=0;
arrayxx[1]=3;
arrayxx[2]=4;
arrayxx[3]=9;
$.get('Save1',{arrayX:arrayxx},function(responseJson)
{
} );
});
});
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<input type="button" id="save" value="save" ></input>
</body>
</html>
My servlet:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Save1 extends HttpServlet {
private static final long serialVersionUID = 1L;
public Save1() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("INSIDE SERVLET");
String [] yourList = request.getParameterValues("arrayX");
System.out.println(request.toString());
System.out.println(yourList[0]);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
I cant able to pass the array from JSP to servlrt.
Please help me with this. When i receive the array, i found that array does not contain any element.
Thanks in advance
As per your requirement I would suggest you to go for ajax like this way
$.ajax(
{
type: "POST",
url: "servlet", //Your full URL goes here
data: { parametername: parametervalue},
success: function(data, textStatus, jqXHR){
//alert(data);
}

Categories

Resources