Sending form in json to servlet and doing validation - java

So i have this form with user name and password. I need to convert the form data in json and send it to a servlet, unpack the data do the validation and return the result back in json format to the browser. At the browser end i need to unpack and show the result.
Okay, so far i have written code to generate a json object from the form and send it to the servlet. Now i need help in receiving it at the servlet end to do validation.
<%# 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="js/jquery-1.11.2.js"></script>
<script>
function sendrequest()
{
var fname= document.getElementById("Fname").value;
var password= document.getElementById("pass").value;
alert("inside function" + fname+" "+password);
var jsonstring="{\"fname\":\""+fname+"\",\""+"password\":\""+password+"\"}";
//var jsonstring='{"fname":'+fname+"\",\""+"password:"+password+"}';
alert(" jsonstring " + jsonstring);
document.getElementById("mesg").innerHTML=jsonstring;
var obj = JSON.parse(jsonstring);
$.ajax({
url: 'Chk',
type: 'GET',
data: {jsons: obj},
error: function() {
document.getElementById("mesg").innerHTML="there is error";
},
dataType: 'text',//'json'
success: function(data) {
document.getElementById("mesg").innerHTML="working";
alert("working");
document.getElementById("mesg").innerHTML=data;
}
});
}
</script>
</head>
<body>
User name:<input type="text" id="Fname" name="Fname" maxlength="12" size="12"/> <br/>
Password:<input type="text" id="pass" name="pass" maxlength="12" size="12"/> <br/>
<input type="button" value="fwd" onClick="sendrequest();"/>
<div id="mesg">252</div>
</body>
</html>
Servelet code :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String json = request.getParameter("jsons").toString();
// 1. get received JSON data from request
}
I have looked at many example not sure how to parse this. Any help will be deeply appreciated.

I think, you can use json parse library.
JSON Simple is usually using library for parsing json string.
http://code.google.com/p/json-simple/
If you want to find any other library,
visiting "http://www.json.org/" and find text java.
You can find other libraries.

Related

Unable to log Json response in Ajax from servlet Java?

I am trying to log a json response from my servlet in my ajax call. Now, here is the thing, I tried experimenting with logging string response in my ajax and things seemed to work fine but then I try to log the json response, I see nothing in my console. I am wondering if I am missing out on something.I tried calling my servlet from POSTMAN and I got the proper json response.
HomeServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Map<String, String> options = new LinkedHashMap<>();
String text = "some text";
PrintWriter out = response.getWriter();
response.setContentType("text/html");
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");
options.put("value1", n);
options.put("value2", nm);
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
// 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" id="check" name="check" value="Check">
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
console.log("I was clicked");
$.get("HomeServlet", function(responseText) {
console.log("response",responseText);
// Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
</script>
</body>
</html>
You will need to write a callback, this will be fired when your ajax call completes, try like below
function success(data) {
console.log( data );
}
function failure(err) {
console.error( err );
}
ajax( "http://some.url.1", success, failure );

I have to send the javascript object to jsp with the help of ajax and then convert jsp objects to java objects and print it to xmlhttpresponse?

index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script type="text/javascript">
function sendData()
{
var data={"id":101,"name":"suraj"};
var xmlhttp=new XMLHttpRequest();
var url="File1.jsp";
url = url + "?data="+data;
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
}
</script>
</head>
<body>
<h3> To send data through json : </h3>
<input type="button" value="sendData" onClick="sendData()"/>
<div id="myDiv">
</div>
</body>
</html>
// the javascript object has to be sended to jsp page with the help of ajax , and i have to convert that javascript object to java objects , how can i perform that task
File1.jsp
<%#page import="org.json.simple.JSONValue"%>
<%#page import="org.json.simple.JSONObject"%>
<%#page import="org.json.simple.parser.JSONParser"%>
<%
String data=request.getParameter("data");
out.println("<h3>data sended successfully <h3>"+data);
String jsonn=JSONValue.toJSONString(data);
out.println(jsonn);
JSONParser parser=new JSONParser();
JSONObject json=(JSONObject)parser.parse(jsonn);
String name=(String)json.get("name");
int id=(int)json.get("id");
out.println(id+" "+name);
%>
here i tried to parse it to json object and then convert it to java object, which is not happening ...
// I cant convert that javascript object to java variables . Help me out with the piece of code . what should i do to convert the javascript object to java objects

Set Ajax response on jsp not working

Last few hours i am trying to solve this but i can not.I am sending ajax request using jquery and based on response i set data on jsp.actully i am checking login detail so if login fail it set error message on label problem is that error message is set for few second and removed i mean to say error message is set for few second i want that if login fails the message is set on label still user enter valid details
thanks in advance
Here is my code
LoginDemo.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">
<link href="css/firstpage.css" rel="stylesheet" type="text/css" /><!-- <style> -->
<script src="js/jquery.min.js"></script>
<title>Insert title here</title>
<script>
$(document).ready(function(){
$("#submit").click(function(){
$.ajax({
type: "POST",
url: "AddInspServlet",
cache:false,
data: { userid: $('#username').val(), password: $('#password').val(),btn:$('#submit').val() },
success:function(data,textstaus){
alert("success:"+data);
if(data == "no"){
alert( document.getElementById("error").innerHTML);
document.getElementById("error").innerHTML= "UserName OR Password is incorrect";
alert( document.getElementById("error").innerHTML);
}else{
location.href = 'Home.jsp';
}
},
error:function(data){
alert("error"+data);
},
});
});
});
</script>
</head>
<body>
<form id="login" name="Loginform" method="post">
<h1><b>Log In</b></h1>
<fieldset id="inputs">
<input id="username" type="text" placeholder="Username" autofocus required>
<input id="password" type="password" placeholder="Password" required>
</fieldset>
<fieldset id="actions">
<input type="submit" id="submit" value="login">
Forgot your password?
</fieldset>
<label id="error" style="color: red;font: bolder; font-size: 18px;">
</label>
</form>
</body>
AddInspServlet
Here i m adding code which server executed and retrieve response
if(btn.equals("login"))
{
System.out.println("***** login condition checking ******");
String password =request.getParameter("password");
UserVO v =op.loginCheck(username, password);
if(password.equals(v.getPassword()))
{
System.out.println("inside true condition");
HttpSession session = request.getSession();
session.setAttribute("userid",v.getUser_id());
session.setAttribute("username",v.getUsername());
session.setAttribute("user", v.getFirst_name()+" "+v.getLast_name());
session.setAttribute("roleid", v.getRole_id());
// response.sendRedirect("Home.jsp");
System.out.println("submitting data success fully");
out.print("yes");
}
else
{
System.out.println("false condition");
out.print("no");
}
}
Get rid of the form tags.
By adding a type="submit" input element without using the action attribute in the form tag, the page will be reloaded.
Or you could keep the form tags and change the type of the submit button to type="button". The form will then not be executed and the page will not reload.
It would be better if you be more specific about the problem. I assume your problem is Label is getting displayed for few seconds and then get disappeared. Is that is true? then try to return "false" inside you data == "no" logic.
Thanks.

Ajax with Spring MVC not working

This is my jsp from where I try to inser the user
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Add Users using ajax</title>
<script src="/Spring3MVC/js/jquery.js"></script>
<script type="text/javascript">
function doAjaxPost() {
// get the form values
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
$.ajax({
type: "POST",
url: "/insert",
data: "firstName=" + firstName + "&lastName=" + lastName,
success: function(response) {
// we have the response
$('#info').html(response);
$('#firstName').val('');
$('#lastName').val('');
},
error: function(e) {
alert('Error: ' + e);
}
});
}
</script>
</head>
<body>
<h1>Add Person</h1>
<table>
<tr><td>First Name : </td><td> <input type="text" id="firstName" name="firstName" /><br/></td></tr>
<tr><td>Last Name : </td><td> <input type="text" id="lastName" name="lastName" /> <br/></td></tr>
<tr><td colspan="2"><input type="button" value="Add Users" onclick="doAjaxPost()"><br/></td></tr>
<tr><td colspan="2"><div id="info" style="color: green;"></div></td></tr>
</table>
Show All Users
</body>
</html>
And this is my controller code
#RequestMapping(value="/insert", method = RequestMethod.POST)
public String insertPerson(ModelMap model, HttpServletRequest request, HttpServletResponse response, #RequestParam("firstName") String firstName, #RequestParam("lastName") String lastName ) {
personDao.savePerson(firstName,lastName);
model.addAttribute("nameAdded", firstName+" "+lastName);
return "personAdded";
}
When I click the 'Add Users' button, nothing happens. Can anyone please help me in fixing this?
You are using contextual URLs everywhere except the Ajax post.
Should
url: "/insert",
maybe be
url: "/SpringMVC/insert",
or even better
url: "<spring:url value='/insert' />",
Try
data: {firstName: firstName, lastName: lastName},
instead of
data: "firstName=" + firstName + "&lastName=" + lastName,
in your ajax call.
Use the url in JSP for AJAX request as:
url: "insert"
in place of:
url: "/insert"
You are using absolute URL which is pointing to the root of the server and not to your controller.
I have tested it and it's working fine for me with your code.
what is the absolute url for the two pages, and if you hit f12 key on you keybourd you can trace the ajax call and trace the response code, if it's 200 it's ok nothing wrong with your server side code now check the success function otherwise check the server code and ofcourse 404 means it didn't reach the server.

Error while using Uploadify

I am new to Jquery, I have a problem regarding uploading the files using Uploadify. Iam trying to send a file to the Java Servlet which uploads the file using apache commons.
But while executing the code, it is not all going to servlet. I actually took this sample example from web and trying it. Can anyone advice what am i missing? I am pasting the client code below:
My understand is "script" parameter in uploadify function will call the servlet. so, I have written my Servlet name in script parameter.
Please advice me how to proceed further.
<%#page contentType="text/html" 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>SimpleFileUpload</title>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.uploadify.v2.1.0.min.js"></script>
<link rel="stylesheet" href="css/uploadify.css" type="text/css" media="screen"/>
<script type="text/javascript">
$(function() {
$('#file_upload').uploadify({
'uploader' : 'swf/uploadify.swf',
'script' : 'fileupload',
'cancelImg' : 'img/cancel.png',
'multi' : false
});
});
</script>
</head>
<body>
<h1>Simple File Upload</h1>
<h3>Multiple file upload made easy</h3>
<div id="file_upload"></div>
<br/>
<input type="button" value="Clear Queue" onclick="$('#file_upload').uploadifyClearQueue();"/>
<input type="button" value="Submit Queue" onclick="$('#file_upload').uploadifyUpload();"/>
</body>
and my servlet code is
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(request)){
// Parse the HTTP request...
try {
ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
List fileItemsList = servletFileUpload.parseRequest(request);
Iterator itr = fileItemsList.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
// check if the current item is a form field or an uploaded file
if(item.isFormField()) {
// get the name of the field
String fieldName = item.getFieldName();
// if it is name, we can set it in request to thank the user
if(fieldName.equals("name"))
request.setAttribute("msg", "Thank You: " + item.getString());
} else {
File fullFile = new File(item.getName());
String filename = item.getName();
File targetdir = new File("E:/");
File savedFile = new File(targetdir,fullFile.getName());
item.write(savedFile);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
} //end servletFileUpload
Thanks,
I just used swfupload... Using fiddler i was seeing my basic example only was submitting 1 file with uploadify so i gave up on it.

Categories