Ajax post from JSP to servlet in Java? - java

So, here is what I want to achieve. Lets say I have a form and I fill up the details and click on submit. The data will be inserted to the database. Now,my idea is that I want to display the data I just added to the DB using ajax without having to refresh the page. I am learning the idea of working with ajax and so I am a bit lost. Can someone suggest any advise.
The idea is that when I click on submit, there will be two events that will be triggered. One is inserting the data to the db and the other getting the data from the db and displaying it inside the tags.
This is my get method in my servlet.
Home.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<html><body>");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/apiprovider","root","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from apiinfo");
// out.println("<table border=1 width=50% height=50%>");
// out.println("<tr><th>EmpId</th><th>EmpName</th><th>Salary</th><tr>");
while (rs.next()) {
String n = rs.getString("apiname");
String nm = rs.getString("apiendpoint");
int s = rs.getInt("id");
response.getWriter().write(n);
// out.println("<tr><td>" + n + "</td><td>" + nm + "</td><td>" + s + "</td></tr>");
}
// out.println("</table>");
// out.println("</html></body>");
con.close();
}
catch (Exception e) {
out.println("error");
}
}
Home.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>
</head>
<body>
<div id="ajaxresponse">
</div>
<form>
API Name:<br>
<input type="text" id = "apiname" name="apiname">
API ENDPOINT:<br>
<input type="text" id ="apiendpoint" name="apiendpoint">
<br>
API VERSION:<br>
<input type="text" id="apiversion" name="apiversion">
ACCESSIBLE:<br>
<input type="checkbox" name="source" value="internet"> Internet<br>
<input type="checkbox" name="source" value="vpn"> VPN<br>
<br><br>
<input type="submit" formaction="Home" method="post" value="Submit">
<br>
<input type="submit" name="Submit" value="Submit">
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#Submit').click(function(event) {
console.log("You clicked me");
$.ajax({
url: "Home",
sucess:function(result){
}
});
});
});
</script>
</body>
</html>

I think you don't need to have two events. You should send ajax call to servlet and get from it properly formatted JSON (with data from DB). In that case, when you will receive data you know that insert was successful. After that in you sucess function you need to parse response from servlet and useing javaScrip set data into elements of you form.

you can achieve this in multiple ways based on your fail over scenarios
please go through this link for better understanding of ajax with servlets. On click of submit button first insert the data into db if this call is success then trigger one more ajax call to get data from db to display please check below sudo code
<script type="text/javascript">
$(document).ready(function() {
$('#Submit').click(function(event) {
console.log("You clicked me");
$.ajax({
url: "Home",
sucess:function(result){
// here call another servlet which will get the data
}
});
});
});
</script>
if the insert call fails you can mention generic message like "insertion failed please try again later"

Related

Display error message from Servlet to JSP page without reloading the page

I have an HTML form for user login on a JSP document and I send the input of the user to a Servlet, check the password against a database then redirect the user to a new page if it's correct or show an error message on the page "Incorrect Password" of incorrect.
I want the error message to appear on the same page as the form just below the Password input field. I have tried the code below but it still redirects me to a new page where it displays only the "Incorrect Password" message.
Is there any other way on how to do it?
Thank you in advance.
//SERVLET CODE
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Some code to check if the password matches the one in the DB and redirects to another page.
} else {
String text = "Incorrect Password!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(text);
}
}
}
//JSP PAGE
<!DOCTYPE html>
<html>
<head>
<script>
$('#sButton').click(function() {
$.post('UserServlet', function(responseText) {
$('#msg').text(responseText);
});
});
</script>
<title>User Log in</title>
<%# include file="PageHeader.html" %>
</head>
<body>
<form action = "SomeServlet" method="POST">
<h3 >Enter detailsto Sign In</h3><br>
Email: <input type="text" name="email" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" name="submit" value="Sign in">
<div style="color:red" id="msg"></div>
</form>
</body>
</html>
The error message should appear on this same page as I understand but it just opens a new page showing only the message and not the html form.

Passing variable from a clicked link - jQuery to Servlet using AJAX

I can get the value of a link using jQuery but I am unable to pass it to a servlet, I need that to work on SQL statements.
Main.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div id ="data">
<table border="1">
<tr>
<th>Case Number</th>
<th>Student Number</th>
<th>Surname</th>
<th>Firstname</th>
<th>Middlename</th>
<th>Date</th>
<th>Violation</th>
</tr>
<%
ResultSet rs = (ResultSet)request.getAttribute("resultset");
String str = "";
while(rs.next())
{
str += "<tr><td>"+rs.getString(1)+"</td><td>"+rs.getString(2)+"</td><td>"+rs.getString(3)+"</td><td>"+rs.getString(4)+"</td><td>"+rs.getString(5)+"</td><td>"+rs.getString(6)+"</td><td>"+rs.getString(7)+"</td>";
}
out.println(str);%>
</table>
</div>
<script src="//code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function()
{
$(function()
{
alert("hello");
});
$('.data1').click(function(link)
{
var number = $(this).text();
alert(number);
$.ajax({
type: "GET",
url: "/viewStudentRecords",
data: {studNo:number},
success: function() {
console.log("Success!!");
},
});
});
});
</script>
</body>
When I click a link, alert(number) works.
viewStudentRecords.java
protected void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out = response.getWriter();
String studNo = request.getParameter("studNo");
out.println(studNo);
}
But the servlet returns null
I know that <% %> is not advisable but I have no knowledge about JSTL.
Any help would be nice.
It seems you use "viewStudentRecords" # two places in href & in Ajax request so probably you get null because of this. First Ajax request calls & then href request get fired & you get null value. Try to use either href or Ajax.

using getClass().getResourceAsStream() in servlet to access json file data

Hi I have a json file stored in the project folder "project/file.json". How can I first, access and read the json file's data from the servlet's doGet()method. Second I want to print the returned data in a separate JSP file. I'm posting here as the last resort since I could not find anything on how to do this. here is my files and my attempt so far
here is file.json
{
"person": {
"title": "manager",
"questions": [
"name ?",
"age ?",
"hobby ?"
]
}
}
here is the doGet () method from fileServlet.java
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
response.setContentType("text/json");
/* here I'm accessing the external file JSON file*/
getClass().getResourceAsStream("project/file.json");
/* here is where I run into trouble. the StringReader() only
accepts strings and I cannot figure out how to read the table form
file.json here*/
JsonReader reader = Json.createReader(new StringReader(person));
/*the reader needs to be set inorder to create a JsonObject*/
JsonObject jsonObject = reader.readObject();
}
and finally, the JSP file. I want the file.json items to appear in this form like so
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form>
"name ?" get displayed here <br>
<input type="text" name="firstname" value="">
<br>
"age ?" get displayed here <br>
<input type="text" name="age" value="">
<br>
"hobby ?" get displayed here <br>
<input type="text" name="hobby" value="">
<br><br>
<input type="submit" value="Done">
</form>
</body>
</html>
Any help or tips will be appreciated

My record is not inserting into database?

I'm trying to insert my data into database using Textbox, Sometime it inserts the data in only using Internet Explorer but not in Mozilla firefox.
It's strange.....
My data sometime gets uploaded but only using Internet Explorer and sometimes it stops working. Please help what's that mean?
Here is my code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" >
$(function() {
$(".update_button").click(function() {
var boxval = $("#content").val();
var dataString = 'content='+ boxval;
if(boxval=='')
{
alert("Please Enter Some Text");
}
else
{
$.ajax({
type: "POST",
url: "demo.jsp",
data: dataString,
cache: false
});
}
});
});
</script>
</head>
<body>
<div>
<form method="post" name="form" action="">
<h3>What are you doing?</h3>
<textarea name="content" id="content" ></textarea><br />
<input type="submit" value="Update" name="submit" class="update_button" />
</form>
</div>
<%
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/poststatus", "root", "1234");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from messages order by msg_id desc");
while(rs.next()){
String msg=rs.getString("msg");
%>
<ol id="update" class="timeline"><%=msg %></ol>
<%
}
}
catch(Exception e){
e.printStackTrace();
}
%>
</body>
</html>
and here is my demo.jsp:
<%# page import="java.sql.*" errorPage="" %>
<%
String content=request.getParameter("content");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/poststatus", "root", "1234");
Statement st=con.createStatement();
int i=st.executeUpdate("insert into messages(msg) values('"+content+"')");
}
catch(Exception e){
e.printStackTrace();
}
%>
And yes, I can fetch my data from database ..as you could see my code. But i'm unable to insert data..
Surely, Help would be appreciated!
EDITED:
Here is my created table:
create database if not exists poststatus;
use poststatus;
create table messages(
msg_id INT auto_increment,
msg VARCHAR(1000) NOT NULL,
primary key(msg_id)
);
The update button that sends the AJAX request is also the form's submit button, so when you click it, it begins submitting the form, which navigates away from the current page, cutting off the code before it can run the AJAX request.
Modify the beginning of your click handler to:
$(".update_button").click(function(e) {
e.preventDefault();
Calling preventDefault() on the event will prevent the form from submitting, giving your AJAX function the chance to run.
Additionally, there is a serious problem in the Java code; because the value is inserted with string concatenation, it creates a blatant SQL injection vulnerability, and also will not work if someone innocently types an apostrophe. Change:
Statement st=con.createStatement();
int i=st.executeUpdate("insert into messages(msg) values('"+content+"')");
to:
PreparedStatement st = con.prepareStatement("insert into messages(msg) values(?)");
st.setString(1, content);
int i = st.executeUpdate();

Reload a jsp page from servlet when form data is involved

I have a jsp that calls a servlet. This servlet does some tasks and then I want to return to the page I was just at and reload it. This would be simple if I knew the exact url it would be each time using the redirectUrl. However, I can't hard code a value in this as it is dynamically created. Is there a way to do this when the previous url is Not known to me?
I am not sure if I understood you correctly, do you need move from jsp to servlet, and return to the same jsp? If this is what you need, I would put some hidden input in jsp form with path
<input type="hidden" name="jspPath" value="${pageContext.request.requestURI}"/>
So full solution is below:
page1.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${requestScope.dataFromServlet }
<form action="${pageContext.request.contextPath}/HelloWorldServlet " method="POST">
<input type="hidden" name="jspPath" value="${pageContext.request.requestURI}"/>
<input type="hidden" name="param1" value="value1"/>
<input type="submit" value="Submit">
</form>
</body>
</html>
HelloWorldServlet.java
public class HelloWorldServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String jspPath = request.getParameter("jspPath");
if(jspPath == null || "".equals(jspPath))
jspPath = "errorPage.jsp";
request.setAttribute("dataFromServlet", "Hello World");
RequestDispatcher rd = request.getRequestDispatcher(jspPath);
rd.forward(request, response);
}
}

Categories

Resources