how to export a table from jsp page to pdf - java

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.

Related

i have angular.min.js:129 TypeError: Cannot read properties of undefined (reading '0') error in my spring boot aplication

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] )

displaying the group by id with respect driverid and name

#Controller
#RequestMapping(value ="/provider" ,method=RequestMethod.POST)
public String welcome(Model model){
Transaction trans=new Transaction();
ArrayList<Transaction> asd=new ArrayList<Transaction>();
List<Transaction> list=driverService.groupby();
model.addAttribute("list1",list);
return "NewFile";
}
public interface DriverService {
public List<Transaction> groupby();
}
#Service("driverService")
public class DriverServiceImpl implements DriverService{
#Autowired
private DriverDAO driverDAO;
#Override
public List<Transaction> groupby() {
return driverDAO.groupby();
}
}
public interface DriverDAO {
public List<Transaction> groupby();
}
#Repository("driverDAO")
public class DriverDAOImpl implements DriverDAO{
#Autowired
private HibernateTemplate hibernateTemplate;
#SuppressWarnings("unchecked")
#Override
public List<Transaction> groupby() {
String hql="select count(tx.driver.driverid),tx.driver.drivername from Transaction tx group by driver";
return (List<Transaction>)hibernateTemplate.find(hql);
}
}
pojo class
#Entity
#Table(name="driver_registration")
public class DriverDetails {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="driver_id")
private String driverid;
#Column(name="driver_name")
private String drivername;
#OneToMany(mappedBy="driver", cascade = CascadeType.ALL)
private List<Transaction> items;
//setter and getters
}
#Entity
#Table(name="transaction")
public class Transaction {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="transaction_id")
private String transactionid;
#ManyToOne()
#JoinColumn(name="driver_id")
private DriverDetails driver;
//setter and getters
}
jsp page
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</body>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="resources/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="resources/css/style.css" rel="stylesheet" type="text/css">
<link href="resources/css/core.css" rel="stylesheet" type="text/css">
<link href="resources/css/themify.css" rel="stylesheet" type="text/css">
<link href="resources/css/dashboard.css" rel="stylesheet" type="text/css">
<title>RajaRatha Provider List</title>
<link href="resources/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css">
<link href="resources/css/buttons.dataTables.min.css" rel="stylesheet" type="text/css">
<!-- pdf and excel plugins -->
<script type="text/javascript" src="resources/js/jquery-1.12.4.js"></script>
<script type="text/javascript" src="resources/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="resources/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="resources/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="resources/js/pdfmake.min.js"></script>
<script type="text/javascript" src="resources/js/jszip.min.js"></script>
<script type="text/javascript" src="resources/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="resources/js/buttons.print.min.js"></script>
<script type="text/javascript" src="resources/js/vfs_fonts.js"></script>
<script>
$(document).ready(function(){
$('#myTable').DataTable({
'ordering':false,
dom: 'Bfrtip',
buttons:[
{
extend: 'excelHtml5',
title: 'Data export'
},
{
extend: 'pdfHtml5',
title: 'Data export'
},
{
extend: 'csvHtml5',
title: 'Data export'
},
{
extend: 'print',
title: 'Data export'
}
]
});
});
</script>
</head>
<body >
<div class="wrapper">
<div class="preloader" style="display: none;"></div>
<div class="site-overlay"></div>
<!--Navigation panel starts here -->
<%#include file="navigation.jsp" %>
<!--Navigation panel ends here -->
<div class="site-content">
<div class="content-area py-1">
<div class="container-fluid">
<div class="box box-block bg-white">
<h5 class="mb-1">
Providers
<!-- <span class="pull-right">(*personal information hidden in demo)</span> -->
</h5>
<i class="fa fa-plus"></i> Add New Provider
<!-- <table class="table table-striped table-bordered dataTable" id="table-2" id="myTable"> -->
<table class="table table-striped table-bordered dataTable" id="myTable">
<!-- <table id="myTable" class="table table-striped table-bordered dataTable" > -->
<h4 style="color:green">${message}</h4>
<thead>
<tr>
<th>ID</th>
<th>Full Name</th>
<!-- <th>Email</th>
<th>Mobile</th>
<th>Total Requests</th>
<th>Accepted Requests</th>
<th>Cancelled Requests</th> -->
<!-- <th>Status</th>
<th>Ratings</th>
<th>Online</th>
<th>Action</th> -->
</tr>
</thead>
<tbody >
<c:forEach var="list" items="${list1}">
<tr>
<td>${list.driver.driverid}</td>
<td>${trans.driver.drivename}</td>
<%-- <td>${driver.location1.driveremail}</td>
<td>${driver.location1.driverphone}</td>
<td>${noRides}</td>
<td></td>
<td>0</td>
<td>${driver.driverStatus}</td> --%>
<td></td>
<%-- <td><span class="tag tag-success">${driver.location1.driverenabledstatus}</span></td>
<td><a class="btn btn-danger btn-block" href="/RajaRathaDashBoardApp/RajarathaDocumentList">Disable</a>
<td>
<center><a class="btn btn-block label-right" href="/RajaRathaDashBoardApp/RajarathaDocumentList?driver=${driver.location1.driverid}&owner=${driverlocation1.ownerid}">View Details</a>
</center>
<center> <span style='font-size:30px;'>✍</span>
</center>
</td> --%>
</tr>
</c:forEach>
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Full Name</th>
<th>Email</th>
<th>Mobile</th>
<th>Total Requests</th>
<th>Accepted Requests</th>
<th>Cancelled Requests</th>
<th>Status</th>
<th>Ratings</th>
<th>Online</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<footer class="footer">
<div class="container-fluid">
<!-- <div class="row text-xs-center" > -->
<div class="col-sm-4 text-sm-left mb-0-5 mb-sm-0">
<p>2017-2018. RajaRatha</p>
</div>
<!-- </div> -->
</div>
</footer>
</div>
</div>
</body>
</html>
output:
113:
114: <c:forEach var="list" items="${list1}">
115: <tr>
116: <td>${list.driver.driverid}</td>
117:
118: <<td>${trans.driver.drivename}</td>
119:
Stacktrace:] with root cause
java.lang.NumberFormatException: For input string: "driver"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at javax.el.ArrayELResolver.coerce(ArrayELResolver.java:144)
at javax.el.ArrayELResolver.getValue(ArrayELResolver.java:61)
at org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:110)
at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:702)
at org.apache.jsp.view.NewFile_jsp._jspx_meth_c_005fforEach_005f0(NewFile_jsp.java:468)
at org.apache.jsp.view.NewFile_jsp._jspService(NewFile_jsp.java:361)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:444)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
I am trying to get individual data from database using group by method in hql but query executed successfully and also it does not display on the respective web page what is the problem in the above code and also how to use group by in Hibernate and Spring Mvc application and also inform what is wrong with the mapping.
1) You query should have the same column ins group by as in the select (excluding the count):
select count(tx.driver.driverid),tx.driver.drivername
from Transaction tx
group by tx.driver.drivername
2) You are trying to perform a projection but you are expecting a List of Transaction. By default the persistence provider will return a List<Object[]> and you will need to extract manually the count column and the drivername column.
3) Alternatively you could use a ResultClass feature -> example

OpenLayers 3 doesn't show KML layer

I'm newbie with OpenLayers and I'm trying to add a KML layer to a map.
Here is my script:
var projection = ol.proj.get('EPSG:3857');
var mapa = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: new ol.View({
center: [-5462834.47, -3058929.70],
projection: projection,
zoom: 10
})
});
map.addLayer(mapa);
var alfalfa_zaragoza = new ol.layer.Vector({
source: new ol.source.Vector({
url: 'kml/ms_alfalfazaragoza_rgba_ndvi.kml',
format: new ol.format.KML()
}),
extractStyles: true,
extractAttributes: true,
maxDepth: 2,
setVisibility: true
});
document.getElementById('addKML').onclick = function () {
map.addLayer(alfalfa_zaragoza);
};
And my html page:
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="http://openlayers.org/en/v3.2.0/css/ol.css" type="text/css">
<script type="javascript" src="<%=request.getContextPath()%>/resources/OpenLayersv3.14.2/build/ol.js"></script>
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false"></script>
<link rel="stylesheet" href="<%=request.getContextPath()%>/resources/OpenLayersv3.14.2/css/ol.css" type="text/css" />
<link rel="stylesheet" href="<%=request.getContextPath()%>/resources/ol3-google-maps-v0.4/ol3gm.css" type="text/css" />
<link rel="stylesheet" href="<%=request.getContextPath()%>/resources/layout.css" type="text/css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="span12">
<div id="map" class="map"></div>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<h4>Concept example</h4>
<div class="row">
<div class="col-md-4 col-sm-4">
<fieldset>
<input id="addKML" type="button" value="Add KML"
title="Add KML layer"/>
</fieldset>
</div>
</div>
</div>
</div>
</div>
<script src="<%=request.getContextPath()%>/resources/ol3-google-maps-v0.4/ol3gm.js"></script>
<script src="<%=request.getContextPath()%>/resources/kml.js"></script>
</body>
</html>
Where is the error? The idea is to press "addKML" button and the layer is added to the map, but when I press it, nothing happens.
You just forget "new" in this line:
var projection = ol.proj.get('EPSG:3857');
Replace with this correct one:
var projection = new ol.proj.get('EPSG:3857');

multiple errors while executing a jsp project

I wrote a jsp project, tried to execute it. I got this error:
listType cannot be resolved to a variable
So I added this lines to my jsp file:
<%#page import="java.util.List"%>
<%#page import="java.util.ArrayList"%>
But it didn't fix the problem. How can I fix it?
There is one more error like this:
The method StudentDetails() is undefined for the type
MangeUser Student.jsp
Here is Student.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="com.junos.users.MangeUser"%>
<%-- <%# page import="com.junos.userdetails.UserEntityDetails"%> --%>
<%#include file="menu.jsp" %>
<%#page language="java" import="java.util.*,java.io.*,java.sql.*"%>
<%!int skillLevel_id=0;%>
<jsp:useBean id="Student" class="com.junos.users.MangeUser" />
<jsp:setProperty name="Student" property="*" />
<!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> Users </title>
<link href="<c:url value="/resources/data-tables/css/jquery.dataTables.css" />"
rel="stylesheet" type="text/css" />
<script src="<c:url value="/resources/data-tables/js/jquery.dataTables.js" />"type="text/javascript"></script>
<link href="<c:url value="/resources/bootstrap-select/css/bootstrap-select.min.css" />"
rel="stylesheet" type="text/css" />
<script src="<c:url value="/resources/bootstrap-select/js/bootstrap-select.min.js" />"></script>
<style type="text/css">
.bootstrap-select:not([class*="col-"]):not([class*="form-control"]):not(.input-group-btn) {
width: 218px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#usrTable').DataTable();
$('#UserDiv').hide();
$('#tblsDiv').hide();
$('#challenegrDescriptionDiv , #Image ').hide();
$('#addUser').click(function(){
$('#UserDiv').show();
$('#usrTbl').hide();
});
$('.cncl').click(function(){
$('#usrTbl').show();
$('#UserDiv').hide();
});
});
var roleValue = function(){
var val = $('#userRole_id option:selected').text();
if(val == "WAITER"){
$('#tblsDiv').show();
}else{
$('#tblsDiv').hide();
}
if(val == "CHALLENGER"){
$('#usrnmDiv , #passDiv , #cnfrmPassDiv').hide();
}else{
$('#usrnmDiv , #passDiv , #cnfrmPassDiv').show();
}
if(val == "CHALLENGER"){
$(' #Image , #description').show();
$('#challenegrDescriptionDiv , #Image ').show();
}else{
$(' #Image , #description').hide();
$('#challenegrDescriptionDiv , #Image ').hide();
}
}
</script>
<script type="text/javascript">
function PreviewImage() {
alert("PreviewImage");
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("profileImage").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("imagePreview").src = oFREvent.target.result;
};
};
</script>
<script type="text/javascript">
//getting value of radio button
$(document).ready(function(){
$("input[type='radio']").click(function(){
var radioValue = $("input[name='name']:checked").val();
if(radioValue){
alert("Your are a - " + radioValue);
}
window.location='EditList.jsp?radioValue='+radioValue;
});
});
</script>
</head>
<body >
<div class="container">
<div class="row-fluid">
<div id="UserDiv" class="col-md-8 col-md-offset-2">
<div class="well well-sm">
</div>
</div>
</div>
</div>
<div id="usrTbl" class="col-md-10 col-md-offset-1">
<div class="btn-group" style= "margin-bottom: 10px;">
<button id="addUser" class="btn btn-success" style="margin-left: 10px;">
<span class="glyphicon glyphicon-plus-sign"></span>
</button>
<button class="btn" style="background-color: #9933CC; color: white;margin-left: 10px;">
<span class="glyphicon glyphicon-edit"></span>
</button>
<button class="btn btn-danger" style="margin-left: 10px;">
<span class="glyphicon glyphicon-trash"></span>
</button>
</div>
<table id="usrTable" class="display text-center table-bordered table-striped" cellspacing="0" width="100%">
<thead>
<tr>
<th class="text-center">First Name</th>
<th class="text-center">Last Name</th>
<th class="text-center">User Name</th>
<th class="text-center">Password</th>
<th class="text-center">Mobile Number</th>
<th class="text-center">Email Id</th>
<th class="text-center">Challenger Description</th>
</tr>
</thead>
<tbody>
<%
List<MangeUser> userList= Student.StudentDetails();
System.out.println("userList size: " + userList.size());
pageContext.setAttribute("Users", userList);
%>
<c:forEach items="${Users}" var="user">
<tr>
<td><c:out value="${user.firstName}"/></td>
<td><c:out value="${user.lastName}"/></td>
<td><c:out value="${user.username}"/></td>
<td><c:out value="${user.password}"/></td>
<td><c:out value="${user.mobileNumber}"/></td>
<td><c:out value="${user.emailID}"/></td>
<td><c:out value="${user.challengerDescription}"/></td>
</tr>
</c:forEach>
</tbody>
</table>
<%#include file="footer.jsp" %>
</div>
</body>
</html>
How can I fix those 2 errors?

how to redirect to success page through servlet using ajax?

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

Categories