I am trying to read a json response from my python based backend. I am using this code for accessing the information.
URL for first call
public static final String JSON_RESPONSE_STRING="http://192.168.2.5:8000/mobile/";
URL forsecond call
public static final String PICKUP_DETAILS="http://192.168.2.5:8000/mobile/shippments/";
common method using
public static String GetJSONResponse(String stringUrl) throws IOException
{
StringBuilder response = new StringBuilder();
URL url = new URL(stringUrl);
HttpURLConnection httpconn = (HttpURLConnection)url.openConnection();
if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()),8192);
String strLine = null;
while ((strLine = input.readLine()) != null)
{
response.append(strLine);
}
input.close();
}
return response.toString();
}
django url patterns
urlpatterns = patterns('mobile_api.views',
url(r'^$','login_authenticate'),
url(r'^shippments/(?P<id>\w+)','pickup_details'),
url(r'^report/post/','pickup_report')
)
I am using this method twice in my code. For the first time this code is working absolutely fine and parsing the json response .
When I am using this method at other place I am call it
pick_up_id=getIntent().getStringExtra("pickup_id");
String stringUrl=Constants.PICKUP_DETAILS+"555";
String response = null;
try {
response = PickupList.GetJSONResponse(stringUrl);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//String response=GetPickUpDetails(pick_up_id);
System.out.println("second call response"+response);
and getting this response
03-22 12:19:37.979: I/System.out(20703): second call response<!doctype html> <!--[if IE 7]> <html class="no-js ie7 oldie" lang="en"> <![endif]--> <!--[if IE 8]> <html class="no-js ie8 oldie" lang="en"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> <head> <meta charset="utf-8"> <title>ECOM</title> <meta http-equiv="X-UA-Compatible" content="IE=Edge;chrome=1" > <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /> <meta property="og:image" content="http://www.domain.com/images/logo.png"/> <meta property="og:title" content="-- description here --"/> <meta property="og:url" content="http://www.domain.com"/> <link rel="shortcut icon" href="/static/assets/img/favicon.ico" /> <link rel="apple-touch-icon" href="/static/assets/img/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="72x72" href="/static/assets/img/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="114x114" href="/static/assets/img/apple-touch-icon-114x114.png"> <link rel="stylesheet" href="/static/assets/css/styles.css" /> <script src="/static/assets/js/libs/modernizr.custom.60077.js"></script> <link rel="stylesheet" href="/static/assets/css/popup.css" /> <script src="/static/assets/js/jquery-1.7.2.min.js"></script> <script src="/static/assets/authentication/js/popup.js"></script> </head><body><div id="backgroundPopup"></div> <div class="header" style="text-align:center; padding-top:10px;"> <img src="/static/assets/img/Ecomlogo.png"/> </div> <div class="container-fluid" roll="main" id="main"> <div class="span6">Track Shipment <div class="login"> <div class="title"> Login </div> <div class="content-login"> <form action="." method="POST"> <div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='p0SPV6QzpX2nP2p588V5lDU9s9LLWZDO' /></div> <input type= "text" name ="username" placeholder="Username" class="user-name"/> <input type= "Password" name="password" placeholder="Password"/> <input type="submit" class="button-login"/> Forgot Your Password? </form> </div> </div> </div> <div class="span6"> <div class="login"> <div class="title"> Ecom Express News </div> <div class="content-login"> </div> </div> </div> </div> <!-- modal --> <div class="modal hide modal-add-revlet" id="add-revlet"> <div class="modal-header"> <a class="close" data-dismiss="modal">×</a> <h3>Record</h3> </div> <div class="modal-body"> </div> </div><!--modal end--> <div id="popupContact"> <a id="popupContactClose">x</a> </div> <!-- uncomment pre-deloy --> <!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>--> <script>window.jQuery || document.write('<script src="assets/js/libs/jquery-1.7.1.min.js"><\/script>')</script> <!-- bootstrap --> <script src="/static/assets/js/bootstrap-transition.js"></script> <script src="/static/assets/js/bootstrap-alert.js"></script> <script src="/static/assets/js/bootstrap-modal.js"></script> <script src="/static/assets/js/bootstrap-dropdown.js"></script> <script src="/static/assets/js/bootstrap-scrollspy.js"></script> <script src="/static/assets/js/bootstrap-tab.js"></script> <script src="/static/assets/js/bootstrap-tooltip.js"></script> <script src="/static/assets/js/bootstrap-popover.js"></script> <script src="/static/assets/js/bootstrap-button.js"></script>
P.S Also, if there is any problem with the code then why is it working for first call.
NOTE 1 Both the response are json objects I have verified several times.my backend is dJango. On hitting the url on browser I am getting the correct response in .json format
check for csrf_exempt or proper permission for access to the url from app
Related
I'm trying to desingn login page by angular in my java Spring Boot Aplication. My problem is when I try login to panel page,username and password is ok and send to application by api controller and set user token correctly,but token don't set by cookeis in page, therefor panel page don't open and i have this error in inspect console :
my login page:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Online Shop App | login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<script src="libs/angular.min.js"></script>
<script src="libs/jquery.min.js"></script>
<script src="libs/angular-cookies.js"></script>
<script src="scripts/app.js"></script>
<script src="scripts/controllers/loginController.js"></script>
<script src="scripts/services/ApiHandler.js"></script>
<link href="libs/bootstrap-5.1.3-dist/css/bootstrap.min.css" rel="stylesheet">
<script src="libs/bootstrap-5.1.3-dist/js/bootstrap.min.js"></script>
<link href="styles/login.css" rel="stylesheet">
</head>
<body ng-app="onlineShopApp">
<div class="container-fluid" ng-controller="loginCtrl">
<div class="row">
<div class="col-3"></div>
<div class="col login-box-holder">
<form>
<h3>Login To Panel</h3>
<div class="form-group">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" ng-model="user.userName">
</div>
<div class="form-group">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" autocomplete="false"
ng-model="user.password">
<div id="emailHelp" class="form-text">Do not share your username and password</div>
</div>
<button type="submit" class="btn btn-primary" ng-click="doLogin()">Login</button>
</form>
</div>
<div class="col-3"></div>
</div>
</div>
</body>
</html>
my login controller:
app.controller("loginCtrl", function ($scope, apiHandler, $cookies) {
$scope.user = {};
$scope.doLogin = () => {
apiHandler.callPost(
'user/login',
$scope.user,
(response) => {
var token=response.datalist[0].token;
$cookies.put("userToken",token);
if(token==null || token=="")
{
alert("invalid token");
return;
}
$cookies.put("uerToken",token);
alert("token is:");
location.href="/panel";
}, (error) => {
});
}
});
my panel page:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Online Shop App | panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<script src="libs/angular.min.js"></script>
<script src="libs/jquery.min.js"></script>
<script src="libs/angular-cookies.js"></script>
<script src="scripts/app.js"></script>
<script src="scripts/controllers/panelController.js"></script>
<script src="scripts/services/ApiHandler.js"></script>
<link href="libs/bootstrap-5.1.3-dist/css/bootstrap.min.css" rel="stylesheet">
<script src="libs/bootstrap-5.1.3-dist/js/bootstrap.min.js"></script>
</head>
<body ng-app="onlineShopApp">
<div class="container-fluid" ng-controller="panelCtrl">
<div class="row">
<h3>Panel</h3>
</div>
</div>
</body>
</html>
my panel controller:
app.controller("panelCtrl", function ($scope, apiHandler, $cookies) {
$scope.checkAccess = () => {
var token=$cookies.get("userToken");
if(token==undefined || token==null || token==""){
location.href="/login";
}
}
$scope.checkAccess();
});
i type wrong dataList in loginController file: (i change response.datalist[0] to=> response.dataList[0] )
We have a web application in which we need to show one header if we are logged in, and another one if we are not logged in. I would like to render these server side in a JSP file.
Here is my first attempt:
WebDelivery.java
package xyz.toold.cuebox.web;
import java.util.HashMap;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.glassfish.jersey.server.mvc.Viewable;
#Path("/")
public class WebDelivery {
#Path("/")
#GET
public Viewable index() {
HashMap<String, Object> model = new HashMap<>();
model.put("LoggedIn", true);
return new Viewable("/index", model);
}
#Path("/search/")
#GET
public Viewable search() {
return new Viewable("/search/index", true);
}
#Path("/user/")
#GET
public Viewable user() {
return new Viewable("/user/index");
}
#Path("/board/details/")
#GET
public Viewable boardDetails() {
return new Viewable("/board/details/index");
}
#Path("/board/")
#GET
public Viewable board() {
return new Viewable("/board/index");
}
#Path("/admin/")
#GET
public Viewable admin() {
return new Viewable("/admin/index");
}
}
index.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta http-equiv="Content-Security-Policy" content="default-src: https: 'unsafe-inline'" />
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="robots" content="index,follow" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="css/bulma.min.css">
<link rel="stylesheet" href="css/style.css">
<title>CueBox</title>
</head>
<body>
<%--TODO: Add logic to decide which header to set--%>
<c:if test="${model.LoggedIn}">
<jsp:include page="assets/partials/header-nologin-popups.jsp"/>
</c:if>
<section class="hero has-plant-image-background is-fullheight">
<div class="title-position">
<div class="hero-body">
<div class="container">
<h1 class="title-size has-text-white">NEW ERA OF<br/>FEEDBACK</h1>
<h2 class="hr subtitle-size has-text-white">GET YOUR FEEDBACK WITH EASE</h2>
</div>
</div>
</div>
</section>
<section class="section is-fullheight has-text-black has-background-grey-light has-text-centered">
<div class="column is-half is-offset-one-quarter">
<div class="hero-body">
<h1 class="title is-1">WHAT TO EXPECT</h1>
<hr class="line has-background-white">
</div>
</div>
<div class="hero-body">
<div class="container">
<div class="columns">
<div class="column">
<div class="content">
<i class="icon is-large fas fa-2x fa-comments"></i>
<h1 class="title is-size-4">Honest Feedback</h1>
<p class="is-size-5">The users can write anonymous posts, so it will be more honest.</p>
</div>
</div>
<div class="column">
<div class="content">
<i class="icon is-large fas fa-2x fa-cogs"></i>
<h1 class="title is-size-4">Easy administration</h1>
<p class="is-size-5">Don't waste time be configuring stupid settings.</p>
</div>
</div>
<div class="column">
<div class="content">
<i class="icon is-large fas fa-2x fa-users"></i>
<h1 class="title is-size-4">Scalable</h1>
<p class="is-size-5">CueBox works for living communities, small companies and lare groups.</p>
</div>
</div>
</div>
</div>
</div>
</section>
<jsp:include page="assets/partials/footer.html"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT" crossorigin="anonymous"></script>
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" integrity="sha384-kW+oWsYx3YpxvjtZjFXqazFpA7UP/MbiY4jvs+RWZo2+N94PFZ36T6TFkc9O3qoB" crossorigin="anonymous"></script>
<script src="js/main.js"></script>
<script src="js/validation.js"></script>
<script src="js/helper.js"></script>
</body>
</html>
The problem is my if never fires, so the header never gets shown. I know that the else is missing. I would have implemented it via having another if, which is inverted.
I also tried not passing a HashMap but a plain boolean, but it did not work either.
This is a link to my GitLab project.
What am I doing wrong, or is this entirely the wrong way to do it?
I am sending an xlsx file over http request but the file becomes corrupt.
I just dont understand why the file becomes corrupt just sending across.
Please help, I am new at this.
Here is the jsp file :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="myApplication">
<head>
<!-- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> -->
<title>Preptune</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
angular.module('myApplication',["ngRoute"]).
directive('fileInput',['$parse',function($parse){
return {
restrict:'A',
link: function(scope,elm,attrs) {
elm.bind('change',function() {
$parse(attrs.fileInput)
.assign(scope,elm[0].files)
scope.$apply()
})
}
}
}])
.controller('myController',['$scope','$http',
function($scope,$http) {
$scope.message = "Test message";
$scope.filesChanged = function(elm) {
$scope.files=elm.files;
$scope.$apply();
};
$scope.upload = function() {
var fd = new FormData();
angular.forEach($scope.files,function(file){
fd.append('file',file);
})
$http.post('http://localhost:80/simple-web-services/uploadQuestions', fd,{
transformRequest : angular.identity,
headers:{'Content-Type':undefined}
})
.success(function(d){
console.log(d);
})
};
}
])
.config(function($routeProvider) {
$routeProvider
.when("/preptune", {
templateUrl : "/webPortal/homePage/welcome"
})
.when("/upload", {
templateUrl : "/webPortal/resources/html/uploadQuestion.html"
})
.when("/download", {
templateUrl : "/webPortal/resources/html/downloadTemplate.html"
})
.otherwise({redirectTo:'/'});
});
</script>
</head>
<body ng-controller="myController">
<nav class="navbar navbar-default">
<div class="container-fluid bg-info">
<div class="navbar-header">
<a class="navbar-brand" href="#prep">Prep</a>
</div>
<ul class="nav navbar-nav">
<li>Upload Question Paper</li>
<li>Download Question Template</li>
</ul>
</div>
</nav>
<div ng-view></div>
</body>
</html>
Here is the form : (uploadQuestion.html)
<form method="post">
<input type="file"
file-input="files"
multiple></input>
<button ng-click="upload()"> Upload </button>
<li ng-repeat="file in files" >{{file.name}} </li>
</form>
The exception says
java.lang.RuntimeException: org.apache.cxf.interceptor.Fault: Your InputStream was neither an OLE2 stream, nor an OOXML stream
I am trying to export a table from jsp page to pdf. jspdf is also not working for this.
my jsp page goes as below, nothing is happening when I click the button export to pdf
Hi, I am trying to export a table from jsp page to pdf. jspdf is also not working for this.
my jsp page goes as below, nothing is happening when I click the button export to pdf
<!DOCTYPE html>
<%
HeadCountReport hcOb = new HeadCountReport();
String groupName = request.getAttribute("gn").toString();
%>
<%#page import="com.mypay.ApplicationConstants"%>
<%#page import="com.reports.HeadCountReport"%><html dir="ltr" lang="en-US">
<%#taglib uri="http://displaytag.sf.net" prefix="display" %>
<head>
<meta charset="ISO-8859-1">
<script src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="./js/tableExport.js"></script>
<script type="text/javascript" src="js/jquery.base64.js"></script>
<script type="text/javascript" src="js/sprintf.js"></script>
<script type="text/javascript" src="js/jspdf.js"></script>
<script type="text/javascript" src="js/base64.js"></script>
<title>Groupwise Head Count</title>
<meta name="viewport"
content="initial-scale = 1.0, maximum-scale = 1.0, user-scalable = no, width = device-width">
<!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<link rel="stylesheet" href="css/style.css" media="screen">
<!--[if lte IE 7]><link rel="stylesheet" href="style.ie7.css" media="screen" /><![endif]-->
<link rel="stylesheet" href="css/style.responsive.css" media="all">
<link rel="stylesheet" type="text/css" href="css/reports.css"/>
<script type="text/javascript" src="js/sortable.js"></script>
<script src="js/jquery.js"></script>
<script src="js/script.js"></script>
<script type="text/javascript">
function loadTable(){
document.getElementById('tbldiv').width=screen.availWidth;
document.getElementById('tbldiv').height=screen.availHeight;
}
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
<script type="text/javascript">
function printPDF() {
var printDoc = new jsPDF();
printDoc.fromHTML($('#tblGrp').get(0), 10, 10, {'width': 180});
printDoc.autoPrint();
printDoc.output("dataurlnewwindow"); // this opens a new popup, after this the PDF opens the print window view but there are browser inconsistencies with how this is handled
}
</script>
<script >
function open_win(url_add)
{
window.open(url_add,'welcome','width=300,height=200,menubar=no,status=no,location=no,toolbar=no,scrollbars=no');
}
function myNewWindow(url_add) {
window.open(url_add, "newWindow", "height=200,width=200,status=yes,menubar=no,status=no,location=no,toolbar=no,scrollbars=no")
}
</script>
</head>
<body>
<div id="art-main">
<div class="art-sheet clearfix"><header
class="art-header clearfix"> <%#include file="header.jsp"%>
</header> <nav class="art-nav clearfix"> <%#include file="hmenu.jsp"%>
<jsp:include page="auth.jsp"></jsp:include> </nav>
<div class="art-layout-wrapper clearfix">
<div class="art-content-layout">
<div class="art-content-layout-row">
<div class="art-layout-cell art-content clearfix"><article
class="art-post art-article">
<div class="art-postcontent art-postcontent-0 clearfix">
<div class="art-content-layout">
<div class="art-content-layout-row">
<div class="art-layout-cell layout-item-0" style="width: 100%">
<div class="clearfix" align="center"> <h2 align="left">Group Break HC Report</h2>
<p> </p>
<input type="button" onclick="tableToExcel('tblGrp', 'Groupwise Break Up')" value="Export to Excel"><input type="button" onClick ="javascript:printPDF();" value="Export to PDF"><br/>
<div id="tblGrp">
<table width="70%" id="tblGrp" align="center" class="sortable">
<tr>
<th width="35" scope="col">SLNo</th>
<th width="89" scope="col">Group</th>
<th width="190" scope="col">Division</th>
<th width="84" scope="col">Staff Type</th>
<th width="107" scope="col">Head Count</th>
</tr>
<%
java.util.List<String[]> listDetail=null;
listDetail = hcOb.getGroupwiseReport(groupName);
Iterator<String[]> itemplid = listDetail.iterator();
int count = 0;
while(itemplid.hasNext()){
String[] sepEmpDet = itemplid.next();
%>
<tr>
<td><%=++count%></td>
<td><%=sepEmpDet[1] %></td>
<td><%=sepEmpDet[3] %></td>
<td><%=sepEmpDet[2] %></td>
<td><%=sepEmpDet[0] %></td>
</tr>
<% }
%>
</table>
</div>
</div>
</div>
</div>
</div>
</article></div>
</div>
</div>
</div>
<%#include file="footer.jsp"%></div>
</div>
</body>
</html>
thanks.
I see the javascript function calls id="tblGrp". However,
<div id="tblGrp">
<table width="70%" id="tblGrp" align="center" class="sortable">
The id appears multiple times, perhaps giving a problem with jspdf. Without more information of the javascript error, Here are a couple of java alternatives.
1) You can build everything using iText.
2) You can design a report in iReport by constructing a jrxml and use the jasper engine for independent pdf exporting/rendering in your application.
3)Here is additional post for alternative to iText.
[Are there any Java PDF creation alternatives to iText?
Without more info of the javascript error, there isn't much to solve here.
I have a jsp page which takes user name and password and then it redirect to a servlet. Below is jsp code,
<%# 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>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>DeliverMe</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/sb-admin.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery Version 1.11.0 -->
<script src="js/jquery-1.11.0.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn-login').click(function() {
var userName = $('#userName').val();
var password = $('#password').val();
var datastr='userName='+userName+'&password='+ password;
$.ajax({
url : 'LoginCheck',
data :datastr,
success : function(responseText) {
$('#ajaxGetUserServletResponse').text(responseText);
},
error:function(url){
window.location = url;
}
});
});
});
</script>
</head>
</head>
<body>
<div class="container">
<span style="color: #000099"><center><h2>DeliverMe Admin Panel</h2></center></span>
<div id="loginbox" style="margin-top:50px;" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-info" >
<div class="panel-heading">
<div class="panel-title">Sign In</div>
</div>
<div style="padding-top:30px" class="panel-body" >
<div style="display:none" id="login-alert" class="alert alert-danger col-sm-12"></div>
<form id="loginform" class="form-horizontal" role="form">
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="userName" type="text" class="form-control" placeholder="username or email">
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="password" type="password" class="form-control" name="password" placeholder="password">
</div>
<div style="margin-top:10px" class="form-group">
<!-- Button -->
<div class="col-sm- 12 controls">
<a id="btn-login" class="btn btn-success">Login</a>
</div>
</div>
<span id="ajaxGetUserServletResponse" style="color: red;"></span>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Then my servlet checks user name and password and if it is wrong then it gives error text but if it is true then it should be redirect to success page. But it doesn't effect. Below is servlet code,
if(db.loginCheck(userName, password))
{
request.getRequestDispatcher("/main.jsp").forward(request, response);
}else
{
String greetings = "Invalid Username/Password";
response.setContentType("text/plain");
response.getWriter().write(greetings);
}
I got solution. I have changed response of my servlet like this,
if(db.loginCheck(userName, password))
{
response.getWriter().write("1");
}else
{
greetings = "Invalid Username/Password";
response.setContentType("text/plain");
response.getWriter().write(greetings);
}
and on my jsp page i have put this,
<script type="text/javascript">
$(document).ready(function() {
$('#btn-login').click(function() {
var userName = $('#userName').val();
var password = $('#password').val();
var datastr='userName='+userName+'&password='+ password;
$.ajax({
url : 'LoginCheck',
data :datastr,
success : function(responseText) {
if(responseText == "1"){
window.location.assign("/main.jsp");
}else{
$('#ajaxGetUserServletResponse').text(responseText);
}
},
});
});
});
</script>
Try this:
Servlet
if(db.loginCheck(userName, password))
{
String greetings = "Success";
response.setContentType("text/plain");
response.getWriter().write(greetings);
}
else
{
String greetings = "Invalid Username/Password";
response.setContentType("text/plain");
response.getWriter().write(greetings);
}
Jquery:
$.ajax({
url : 'LoginCheck',
data :datastr,
success : function(responseText) {
if(responseText == "Success"){
windows.location.href='/main.jsp';
}else{
windows.location.href='/error.jsp';
});