HttpServlet - add context to html page - java

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);

Related

I am sending form data using jsp ajax to servlet and But ajax response gets disappear within nano seconds

I am sending form data using Jsp through AJAX on Servlet.
reg.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form>
Enter name:<input type="text" id="name" /> <br />
<button onclick="callJqueryAjax()">Save</button>
</form>
<span id="result"></span>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function callJqueryAjax() {
location.reload(false);
var name = $('#name').val();
console.log(name);
$.ajax({
url : 'Save',
method : 'POST',
data : {
name : name,
},
success : function(resultText) {
$("#result").html(resultText);
}
});
}
</script>
</body>
</html>
SaveMe.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Save")
public class SaveMe extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection makeCon;
private Statement stmt;
public void init(ServletConfig config) throws ServletException {
JdbcCon jdbcCon = new JdbcCon();
makeCon = jdbcCon.makeCon();
try {
stmt = makeCon.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
String name = request.getParameter("name");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String sql = "insert into users (name) Values('" + name + "')";
System.out.println(sql);
try {
int result = stmt.executeUpdate(sql);
if (result > 0) {
out.print("Inserted");
} else
out.print("Not Inserted");
} catch (SQLException e) {
}
}
}
I receive the output in ajax but the thing is JSP gets reload by itself and removes the response as well as removes the data from Textbox from which my response gets disappear by itself.
Please provide me the solution and also a better way for writing an ajax call
First of all I didn't understand why you are using "location.reload(false);" in your JSP page before submitting the ajax request.
You could remove it.
In addition a good practice when using ajax request is to specify the "dataType", in your case "html".
Here is an example:
$.ajax( {
type : 'POST',
url : 'SaveMe',
success : function(result) {
$("#result").html(result);
},
dataType : "html"
});

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

Send ajax post request to servlet

I can not send a simple request to the servlet to jQuery tools. But at the same time if I go through the form, then everything works on hurray. Here is the index.html from which I want to send the user's login. Login.js, in which I form the request itself, SerletStore.java itself servlet. And the structure of the whole project.
login.js
$(document).ready( function(){
$("#login-submit").click(function(){
var data = {
username: $("#user").prop("value")
}
$.ajax({
method: "POST",
url: "http://localhost:8080/ChallengeClient/store",
data: {
username: $("#user").prop("value")
},
success: function(data) {
alert('Success');
},
error: function(xhr, str){
alert('Возникла ошибка: ' + xhr.responseCode);
}
}).done(function() {
alert('Success');
});
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Form</title>
<link rel="stylesheet" href="css/login.css">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400,700">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/login.js"></script>
</head>
<body>
<div id="login">
<form name="form-login">
<span class="fontawesome-user"></span>
<input type="text" id="user" name="username" placeholder="Имя пользователя">
<span class="fontawesome-lock"></span>
<input type="password" id="pass" placeholder="Пароль">
<input type="submit" id="login-submit" value="Вход">
</form>
</div>
</body>
</html>
ServletStore.java
package servlet;
import server.service.HelloWebService;
import server.service.HelloWebServiceImplService;
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 java.io.IOException;
#WebServlet(name="store", urlPatterns = "/store")
public class ServletStore extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// подключаемся к тегу service в wsdl описании
HelloWebServiceImplService helloService = new HelloWebServiceImplService();
// получив информацию из тега service подключаемся к самому веб-сервису
HelloWebService hello = helloService.getHelloWebServiceImplPort();
// обращаемся к веб-сервису и выводим результат в консоль
/*String error = hello.getHelloString("!! Challenge !!");*/
String error = "";
String username = (String) req.getParameter("username");
if (username.equals("")) {
error = "Не было введено имя пользователя";
}
req.setAttribute("error", "Не было введено имя пользователя");
req.getRequestDispatcher("jsp/loginError.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

Ajax response doesn't display in JSP page

I'm Trying to Save small record using JSP ajax in technology. The project working procedure is like this.
01. index.jsp : Send data to SaveStudent servlet
02. SaveStudent : Get request form jsp and send it to validation java class
03. Validation : Validate data and Send to DaoImpl java class
04. DaoImpl : Override the method in StudentDAO, Do the save SQL query.
05. StudentDAO : A interface has all the database related methods.
Here is the image of the project.
Given below is index.jsp files source code.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<form action="SaveStudent" method="post">
<label>Enter Name:</label>
<input type="text" name="name" id="txtName"/>
<br/>
<label>Enter City:</label>
<input type="text" name="city" id="txtCity"/>
<br/>
<input type="submit" value="Send" id="btnSave"/>
<div id="response"></div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
var $name = $("#txtName").val();
var $city = $("#txtCity").val();
$.post('SaveStudent', {
name: $name,
city: $city
}, function(responseText) {
if (responseText !== null) {
$('#response').text(responseText);
} else {
alert("Invalid Name");
}
});
});
});
</script>
</body>
Here is SaveStudent java class's source code.
package Control;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Model.Validation;
public class SaveStudent extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String record = "";
try {
Validation val = new Validation();
record = val.validateSave(request, response);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
if (record != null) {
out.write(record);
} else {
out.print("Error Occured..!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
}
Save record is working fine. Database is also updating. But the problem is The "Save Successful" message is appears in servlet page. Not under the jsp page.
Please help me on this. Thank you.
I figure out a way. I put replace "submit" type to "button". Now working perfectly. Thank you for your Time.

Java ajax passing values from jsp to servlet

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");

Categories

Resources