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

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.

Related

Ajax post from JSP to servlet in 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"

Why am I getting Bad Request kind error when uploading file using jquery with spring mvc?

When I am using Jquery with spring MVC I got an error at browser side "Bad Request" and control not going to the controller.While I am using simple form and sending a request to same controller then it is going.
Below is my code please tell me where am I going wrong?
<%# 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="files/jquery-1.10.2.js"></script>
<script src="files/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var isJpg = function(name) {
return name.match(/jpg$/i)
};
var isPng = function(name) {
return name.match(/png$/i)
};
$(document).ready(function() {
var file = $('[name="file"]');
var imgContainer = $('#imgContainer');
$('#btnUpload').on('click', function() {
var filename = $.trim(file.val());
if (!(isJpg(filename) || isPng(filename))) {
alert('Please browse a JPG/PNG file to upload ...');
return;
}
$.ajax({
url: 'FileData.htm',
type: "POST",
data: new FormData(document.getElementById("fileForm")),
enctype: 'multipart/form-data',
processData: false,
contentType: false
}).done(function(data) {
imgContainer.html('');
var img = '<img src="data:' + data.contenttype + ';base64,'
+ data.base64 + '"/>';
imgContainer.append(img);
}).fail(function(jqXHR, textStatus) {
//alert(jqXHR.responseText);
alert('File upload failed ...');
});
});
$('#btnClear').on('click', function() {
imgContainer.html('');
file.val('');
});
});
</script>
</head>
<body>
<!-- <form name="dlgContent" action="FileData.htm" id="dlgcon" enctype="multipart/form-data" method="POST">
<input type="file" name="excelfile"/>
<input type="submit"/>
</form> -->
<div>
<form id="fileForm">
<input type="file" name="file" />
<button id="btnUpload" type="button">Upload file</button>
<button id="btnClear" type="button">Clear</button>
</form>
<div id="imgContainer"></div>
</div>
</body>
</html>
And my Controller Class in spring mapping given below
#RequestMapping(value="/FileData.htm", method = RequestMethod.POST)
public void FileData(Model model, #RequestParam CommonsMultipartFile[] excelfile, HttpServletRequest request, HttpServletResponse response){
System.out.println("bhjsbfjhsbfbdesfbsfb");
response.setContentType("application/json");
FileData fd = new FileData();
//Map<String, String> data = fd.submitFileData(excelfile);
Gson gson = new Gson();
// String values = gson.toJson(data);
try {
//response.getWriter().write(values);
//System.out.println(values);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Thanks.
Actually you are sending Json and not html you should use #ResponseBody
#RequestMapping(value="/upload", method = RequestMethod.POST)
public #ResponseBody
FileData upload(MultipartHttpServletRequest request,
#RequestParam String albumName,
HttpServletResponse response) {
Iterator<String> itr = request.getFileNames();
//others code here
Also Don't forget !! to config multipart data ,
Plus send back Object using jackson lib to jquery done function to be work
Gson lib is not good to use with #ResponseBody , we are using Gson with RestTemplate instead.

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

Assigning a value to the checkbox (true or false)

How do I set a value to the checkbox, true or false.
<% Boolean inactive = Boolean.valueOf(request.getParameter("isCheckedUnmatch"));
boolean isChecked = inactive.booleanValue();
%>
<script language = javascript>
function chgFlag(isChecked){
alert(isChecked);
isChecked = true;
}
</script>
<td align = "left">
<input name = "chkUnmatch" type = "checkbox" value = "<%=isChecked%>" onclick = "if (this.checked==true){chgFlag(<%=true%>)}">
<font face = "verdana" size = "2"><b>Unmatch Payment</b></font>
</td>
I have tried this code and even if I checked the box, the value of the boolean from the java controller is still false, its default value.
NOTE: I am using Java 1.3, the latest version of Java when the application was developed.
First of all, in JSP java codes and Scriptlets (<% %>, <%! %>, <%= %>), expression ${} etc.. all are processed before the HTML, javascripts and css are processed.
even if I checked the box, the value of the boolean from the java
controller is still false, its default value.
If you want to change the server side variable value (i.e. Controllers, Models, Servlets etc) on checked/unchecked of a checkbox, there is some ways:
1) Use a AJAX to send a request to server for variable value changes:
HTML page like:
<form id="myForm" action="servletUrlPattern" method="post">
<input name="chkUnmatch"
type="checkbox"
onclick="if (this.checked==true){chgFlag(true)}">Check Box
<input type="submit"/>
</form>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
function chgFlag(isChecked){
console.log('isChecked: '+isChecked);
$.post( $('#myForm').attr('action'), { valueToChange : isChecked }).done(function( data ) {
alert( "Data Loaded: " + data );
});
}
</script>
and in Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost() invoked..");
Boolean valueToChange = Boolean.valueOf(request.getParameter("valueToChange"));
System.out.println("valueToChange:"+valueToChange);
//Here, Do your works..
response.getWriter().write("successfully changed.");
}
2)
Use form with submit button.
See also:
jquery post doc
u may try this:
<input type="checkbox" name="chkUnmatch" onclick="chgFlag(this.checked)" value="" id="box"/>
<script>
function chgFlag(chk){
var box = document.getElementById("box");
box.value = chk;
}
<%
Object tmp = request.getParameter("isCheckedUnmatch");
if (null != tmp) {
boolean mrk = Boolean.valueOf(tmp);
%>
chgFlag(<%=mrk%>);
<%}%>
</script>
This should help.
EXSAMPLE
<html>
<head>
<script type="text/javascript">
function refreshCheckboxValue(checkbox){
checkbox.value = checkbox.checked;
}
</script>
</head>
<body>
<input type="checkbox" onclick="refreshCheckboxValue(this)" value="false"/>
</body>
</html>

How to map JSON object to Spring Object

How to map JSON object to Spring Object... I have AJAX, posting a JSON object to my Spring Controller but how do I make Spring turn that JSON into a Object in java
Java Code:
#RequestMapping(method=RequestMethod.POST, value="/employee")
public ModelAndView addEmployee(#RequestBody String body) {
System.out.println("in post: " + body);
Source source = new StreamSource(new StringReader(body));
System.out.println("source: " + source.toString());
//
// how do I turn the JSON String into a Java Object?
//
return new ModelAndView(XML_VIEW_NAME, "object", body);
}
JavaSript/html code:
<%# 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>This is a project to show how to use RESTful</title>
</head>
<body>
<script type="text/javascript">var contexPath = "<%=request.getContextPath()%>";</script>
<script src="<%=request.getContextPath()%>/js/jquery.js"></script>
<script type="text/javascript">
function doAjaxPost() {
var queryString = $('#htmlform').serialize();
alert("doAjaxPost Called :" + queryString +":");
$.ajax({
contentType : "application/json",
dataType : 'json',
type : "POST",
url : contexPath + "/service/employee",
data : queryString, //json serialization (like array.serializeArray() etc)
success : function(data) {
alert("Thanks for submitting. \n\n" + response.result);
// response
},
error : function(request, status, error) {
alert('Error: ' + e);
}
});
}
</script>
<H1>Add Employee</H1>
<p>
<form name="htmlform" id="htmlform">
<table border=1>
<thead><tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr></thead>
<tr>
<td><input type="text" name="ID" maxlength="5" size="3"></td>
<td><input type="text" name="Name" maxlength="10" size="10"></td>
<td><input type="text" name="Email" maxlength="10" size="10"></td>
</tr>
</table>
<input type="button" value="Save Employee" onclick="doAjaxPost();" />
<p>
<p>
</form>
[List all Employees | Employee Form Test]
</body>
</html>
Make sure to:
send JSON object, not JSON String
included Jackson on your classpath
Then you can add #RequestBody Employee employee at the controller's method signature.
I suppose you're using Spring 3.0+. Take a look at Spring Source blog post on JSON simplifications. It seems that you're half way there already.
Use JSON mapping library such as Jackson or Gson
Your code would look approximately as :
Employee e;
try {
e = objectMapper.readValue(body, Employee .class);
} catch (IOException e) {
throw new IllegalArgumentException("Couldn't parse json into a employee", e);
}
If you using Spring 3 or higher, there is even simpler way to do it:
http://blog.springsource.org/2010/01/25/ajax-simplifications-in-spring-3-0/

Categories

Resources