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 );
Related
When user enters wrong password i need to show error and then load login.html using request dispatcher but i am getting login form without any error.
Like this
When user enters correct password it is showing correct output but it is showing login.jsp in the url rather than welcome.jsp
Like this
This is my login.html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
</head>
<body>
<div>
<h1>Login Here</h1>
<form action="login.jsp" method="post">
<div>
<label for="username">Username: </label>
<input type="text" name="username" id="username">
</div>
<div>
<label for="password">Password: </label>
<input type="password" name="password" id="password">
</div>
<div>
<input type="submit" value="Login">
</div>
</form>
</div>
</body>
</html>
This is my login.jsp code:
<%#page import="java.util.*, java.io.*, java.sql.*, javax.sql.*, java.time.format.DateTimeFormatter, java.time.LocalDateTime"%>
<html>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "saiakhil");
Statement st = conn.createStatement();
String sql = "select * from myusers where username = '" + username + "' and password = '" + password + "'";
ResultSet rs = st.executeQuery(sql);
if (rs.next() == false)
{
out.println("<h2>Invalid Username or Password!</h2>");
RequestDispatcher rd = request.getRequestDispatcher("login.html");
rd.include(request, response);
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
rd.forward(request, response);
}
st.close();
conn.close();
}
catch (SQLException se)
{
out.println(se);
}
catch (Exception e)
{
out.println(e);
}
%>
</body>
</html>
This is my welcome.jsp code:
<%#page import="java.util.*, java.io.*, java.sql.*, javax.sql.*, java.time.format.DateTimeFormatter, java.time.LocalDateTime"%>
<html>
<body>
<%
String username = request.getParameter("username");
out.println("<h2>Logged in successfully</h2>");
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
out.println("<h3>Welcome " + username +"</h3>");
out.println(dtf.format(now));
%>
</body>
</html>
I am new to Ajax, Jquery, JSON stuff. I have created one login page in jsp servlet technology. On login page, when user presses submit button, data gets collected in JSON and transferred to controller through AJAX. Now, in controller if on some condition, login name found to be correct, then it should use RequestDispatcher to dispatch it to success page. However if condition not satisfied, then it should write the message in JSON object and return it as content type json. Now the problem is that I am able receive JSON data on controller, but not able to redirect on success and also not able to show alert box to user if he entered wrong data. Below are the files:
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
function validateAndSet()
{
var jsonRequest = {};
var login_name = $.trim($('#loginName').val());
var password = $.trim($('#password').val());
if(login_name=='' || login_name.length==0 ){
alert("Please enter login name.");
$('#loginName').focus();
return false;
}
if(password=='' || password.length==0 ){
alert("Please enter password.");
$('#password').focus();
return false;
}
jsonRequest["login_name"] = login_name;
jsonRequest["password"] = password;
return jsonRequest;
}
</script>
</head>
<body>
<jsp:include page="commonResources/Header.jsp">
<jsp:param value="none" name="headerMenu"/>
</jsp:include>
<script>
$(document).ready(function(){
$("#but").click(function(){
var formData=validateAndSet();
var strUrl="rwcntrlr.do?action=loginForm";
$.post(strUrl, {jsonData: JSON.stringify(formData)},function(response){
response = jQuery.parseJSON( response);
if(response.status=='NOT OK')
{
alert("not ok");
}
else{
alert('OK');
}
});
});
});
</script>
<br><br>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<div class="container-fluid">
<div class="panel panel-default" id="p1">
<div class="panel-heading"><h3>Login</h3></div>
<div class="panel-body">
<center>
<table>
<tr>
<td height="50">LoginName:</td><td height="50"><input type="text" id="loginName" name="loginName"/></td>
</tr>
<tr>
<td height="20">Password:</td><td height="20"><input type="password" id="password" name="password"/></td>
</tr>
<tr><td height="50" colspan="2" align="right"><input type="submit" id="but" name="subBut" value="Go>" /></td></tr>
</table>
</center>
</div>
</div>
</div>
</div>
<div class="col-sm-4"></div>
</div>
</body>
</html>
controller servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String formName=request.getParameter("action");
if(formName.equalsIgnoreCase("loginForm")){
String strJSONData = request.getParameter("jsonData");
System.out.println(strJSONData);// data received correctly...
JSONObject jsonResponse = new JSONObject();
try{
JSONObject requestedJSONObject = new JSONObject(strJSONData);
String login_name = requestedJSONObject.getString("login_name");
String password = requestedJSONObject.getString("password");
if(login_name.equalsIgnoreCase("u2")){
RequestDispatcher rd=request.getRequestDispatcher("employeeSection/employeeDailySheet.jsp");
response.setContentType("text/html");
rd.forward(request, response);
}
else{
jsonResponse.put("status", "NOT OK");
response.setContentType("application/json");
response.getWriter().write(jsonResponse.toString());
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
When I presses submit button on login.jsp, nothing happens. No console error is shown. What should I do to resolve this problem.
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.
I am working with resteasy with war file deployed on jboss (6.0.2 EAP)
I have the following workflow :
URL hit calls a servlet(doGet() method)
this servlet is supposed to deliver a jsp page to the client
JSP page resides in WebContent/customFolder
I use the requestDispatcher().forward() method to invoke the JSP
The path given in forward("/customFolder/name_of_jsp")
the jsp has a form, whose action attribute points to another servlet
the problem is , once the forward() method is called, the browser returns a 404 resource not found error.
I have followed some questions already posted on this forum and was not able to solve this issue.
Can anyone please guide me.
Edit:
JSP page :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="javax.servlet.*,java.lang.String"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Password Reset Page</title>
</head>
<body>
<form method="GET" action="Resteasy">
<%!String userId;%>
<%userId = (String)getServletContext().getAttribute("userid"); %>
<p>User Id:<%= userId %></p>
Password: <input type="password" name="pwd" id="pass">
<br>
Confirm Password: <input type="password" name="rePwd" id ="c_pass" onblur="confirmPass()"><br>
<script type="text/javascript">
function confirmPass() {
var pass = document.getElementById("pass").value
var confPass = document.getElementById("c_pass").value
if(pass != confPass) {
alert('Wrong confirm password !');
document.getElementById("c_pass").focus();
}
}
</script>
<input type="submit" value="Submit">
</form>
</body>
</html>
The servlet which has to deliver the jsp :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.info("Received request for popup jsp page");
String userId = request.getParameter("userid");
String utc = request.getParameter("utc");
log.info("Recieved userid = "+ userId);
log.info("Received utc is = "+ utc);
ServletContext requestContext = request.getServletContext();
requestContext.setAttribute("userid", userId);
requestContext.setAttribute("UTC", utc);
String htmlfileName = null;
try {
htmlfileName = new DeltaPropertyHandler(
DeltaConstants.LINK_HTML_FILE).getPropertyValue(DeltaConstants
.USER_PASSWORD_RESET_HTML);
File file = new File(requestContext.getRealPath(htmlfileName));
if(file.exists()){log.debug("file exists!!");}
else{log.warn("file does mot exist");}
} catch (Exception e) {
log.error("failed to present the jsp page " + e.getMessage());
}
log.info("File name is "+htmlfileName);
RequestDispatcher rd = requestContext.getRequestDispatcher(htmlfileName);
rd.forward(request, response);
}
your code:
RequestDispatcher rd = requestContext.getRequestDispatcher(htmlfileName);
you should change:
RequestDispatcher rd = requestContext.getRequestDispatcher(programname.jsp);
if your using the get method as following as:
RequestDispatcher view=request.getRequestDispatcher(forward);
view.forward(request, response);
if your using the post method like as:
private static String LIST_USER="/listUser.jsp";
RequestDispatcher view=request.getRequestDispatcher(LIST_USER);
request.setAttribute("users", dao.getAllUsers());
view.forward(request, response);
User will be reference from this format. And just look at the simple format are following as:
A.jsp> conntroller.java > dao.java>dbUtil.java
you want the reference for that list as following link to click
index.jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<h1>
<font color=orange ><center> Authentification </font> </h1>
<form name"loginform" action="login" method="post">
<p> Enter your ID: <input type="text" name="id"><br>
<input type="submit">
</form>
</body>
</html>
Authentification.java:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
int IdUser = Integer.valueOf(request.getParameter("id"));
session.setAttribute("ide", IdUser);
try {
if(auth.authen(IdUser)){
session=request.getSession();
request.getRequestDispatcher("acceuil.jsp").forward(request, response);
System.out.println("found");}
else{
request.getRequestDispatcher("index.jsp").forward(request, response);
System.out.println("not found");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
acceuil.jsp: Where I want to display IdUser
<% Integer idUser = (Integer)session.getAttribute("IdUser"); %>
<!--some HTML code-->
<div id="corps"><h1>
Welcome <%=idUser%> </h1></div>
So what I want to have is after the user enter's his id and if the id is found in the database(this operation works) there would be a message ncluding the user's id. the get.Attribute doesn't return a value instead in my page the result is "Welcome NULL".
You saved the attribute in session with name "ide" but try to recover it with name "IdUser". Use the same attribute name in both places.