I have a html jsp form where users can copy their text press submit and pdf is created using Itext . On the other side the servlet gets the data . What happens is when I use some non standard letters it gives me back #^& for these letters . I did use in my servler and both jsp charset=UTF-8 , I am using post method to send data . I am using netbeans and tomcat .
It is not about Itext since when I do System.out.println(variable) it also does not print correctly .
package servlets;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfAnnotation;
import com.lowagie.text.pdf.PdfAppearance;
import com.lowagie.text.pdf.PdfFormField;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.draw.LineSeparator;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* #author Jovo
*/
#WebServlet(name = "GenerateBrokersPdf", urlPatterns = {"/GenerateBrokersPdf"})
public class GenerateBrokersPdf extends HttpServlet {
/*
public static final String FONT = "C:/Windows/Fonts/segoeui.ttf";
bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
document.add(new Paragraph(title,new Font(bf, 12)));
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException, DocumentException {
response.setContentType("application/pdf;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UFT-8");
BaseFont bf;
try {
HttpSession session = request.getSession(true);
if (session.getAttribute("taxnumber") == null || session.getAttribute("email") == null || session.getAttribute("password") == null) {
request.setAttribute("message", "The user does not exist in our database");
request.getRequestDispatcher("/Login.jsp").forward(request, response);
}
String title = request.getParameter("doctitle");
String date = request.getParameter("docdate");
String text = request.getParameter("brokerstext");
//String text = URLDecoder.decode(new String(request.getParameter("brokerstext").getBytes("iso-8859-1")), "UTF-8");
// System.out.println(text);
String[] newdate = date.split("/");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
document.open();
document.add(new Paragraph(newdate[1] + "/" + newdate[0] + "/" + newdate[2]));
document.add(new Paragraph(title));
document.add(new Paragraph(text));
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
document.add(new LineSeparator());
document.add(Chunk.NEWLINE);
document.add(new LineSeparator());
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
document.add(new Paragraph(" Brokers's digital signature Clients's digital signature"));
//potpis 1
PdfFormField field1 = PdfFormField.createSignature(writer);
field1.setWidget(new Rectangle(72, 100, 172, 200), PdfAnnotation.HIGHLIGHT_INVERT);
field1.setFieldName("mySig1");
field1.setTitle("Klijent1");
field1.setFlags(PdfAnnotation.FLAGS_PRINT);
field1.setPage();
PdfAppearance tp1 = PdfAppearance.createAppearance(writer, 72, 48);
tp1.rectangle(0.5f, 0.5f, 71.5f, 47.5f);
tp1.stroke();
field1.setAppearance(
PdfAnnotation.APPEARANCE_NORMAL, tp1);
writer.addAnnotation(field1);
//potpis
//potpis 2
PdfFormField field2 = PdfFormField.createSignature(writer);
field2.setWidget(new Rectangle(372, 100, 472, 200), PdfAnnotation.HIGHLIGHT_INVERT);
field2.setFieldName("mySig2");
field2.setTitle("Klijent2");
field2.setFlags(PdfAnnotation.FLAGS_PRINT);
field2.setPage();
PdfAppearance tp2 = PdfAppearance.createAppearance(writer, 72, 48);
tp2.rectangle(0.5f, 0.5f, 71.5f, 47.5f);
tp2.stroke();
field2.setAppearance(
PdfAnnotation.APPEARANCE_NORMAL, tp2);
writer.addAnnotation(field2);
//potpis
document.close();
/* TODO output your page here. You may use following sample code. */
} finally {
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
try {
processRequest(request, response);
} catch (DocumentException ex) {
Logger.getLogger(GenerateBrokersPdf.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (SQLException ex) {
Logger.getLogger(GenerateBrokersPdf.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
try {
processRequest(request, response);
} catch (DocumentException ex) {
Logger.getLogger(GenerateBrokersPdf.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (SQLException ex) {
Logger.getLogger(GenerateBrokersPdf.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
This is the jsp start code
<%#page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<% request.setCharacterEncoding("UTF-8");%>
<%
if(session.getAttribute("taxnumber")==null || session.getAttribute("email")==null || session.getAttribute("password")==null )
{
request.setAttribute("message", "The user does not exist in our database");
request.getRequestDispatcher("/Login.jsp").forward(request, response);
}
%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<meta content="width=device-width" name="viewport"> ...
This is the html with form(created by jsp) source code
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<meta content="width=device-width" name="viewport">
<link type="text/css" href="NodeGraph/css/base.css" rel="stylesheet" />
<link type="text/css" href="NodeGraph/css/Spacetree.css" rel="stylesheet" />
<script language="javascript" type="text/javascript" src="jit.js"></script>
<link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700">
<link href="content/css/bootstrap.css" type="text/css" rel="stylesheet">
<link href="content/css/bootstrap-responsive.css" type="text/css" rel="stylesheet">
<link href="content/css/bootmetro.css" type="text/css" rel="stylesheet">
<link href="content/css/bootmetro-tiles.css" type="text/css" rel="stylesheet">
<link href="content/css/bootmetro-charms.css" type="text/css" rel="stylesheet">
<link href="content/css/metro-ui-light.css" type="text/css" rel="stylesheet">
<link href="content/css/icomoon.css" type="text/css" rel="stylesheet">
<link href="content/css/datepicker.css" type="text/css" rel="stylesheet">
<link href="content/css/daterangepicker.css" type="text/css" rel="stylesheet">
<link href="content/css/demo.css" type="text/css" rel="stylesheet">
<link href="scripts/google-code-prettify/prettify.css" type="text/css" rel="stylesheet">
<link href="content/ico/favicon.ico" rel="shortcut icon">
<link href="content/ico/apple-touch-icon-144-precomposed.png" sizes="144x144" rel="apple-touch-icon-precomposed">
<link href="content/ico/apple-touch-icon-114-precomposed.png" sizes="114x114" rel="apple-touch-icon-precomposed">
<link href="content/ico/apple-touch-icon-72-precomposed.png" sizes="72x72" rel="apple-touch-icon-precomposed">
<link href="content/ico/apple-touch-icon-57-precomposed.png" rel="apple-touch-icon-precomposed">
<script>
function showchat()
{
if (document.getElementById("charms").style.display=="block")
{
document.getElementById("charms").style.display="none";
}
else
{
document.getElementById("charms").style.display="block";
}
}
</script>
</head>
<body >
<div class="container-fluid">
<div class="row-fluid">
<div class="span2" >
<a id="backbutton" class="win-backbutton" href="#" onclick="history.go(-1)"></a>
<a style="margin-top: 45px;position: absolute;width: 170px;" class="thumbnail" href="DebtSolutions.jsp">
<img alt="" src="DeptSolutionIc.jpg">
<label>Debt Solutions</label>
</a>
<a style="margin-top: 215px;position: absolute;width: 170px;" class="thumbnail" href="Synergy.jsp">
<img alt="" src="SynergyIc.jpg">
<label>Company Synergy</label>
</a>
<a style="margin-top: 385px;position: absolute;width: 170px;" class="thumbnail" href="PublicBid.jsp">
<img alt="" src="PublicInc.jpg">
<label>Public Procurements</label>
</a>
<a style="margin-top: 555px;position: absolute;width: 170px;" class="thumbnail" href="CompanySearch.jsp">
<img alt="" src="SearchIc.jpg">
<label>Company Search</label>
</a>
<a style="margin-top: 725px;position: absolute; width: 170px;"class="thumbnail" href="CompanyNetworking.jsp">
<img alt="" src="NetworkingIc.jpg">
<label>Company Networking</label>
</a>
<a style="margin-top: 895px;position: absolute; width: 170px;padding-bottom: 30px;"class="thumbnail" href="Brokers.jsp">
<img alt="" src="brokers.jpg">
<label>Brokers Accounts</label>
</a>
</div>
<div class="span10" style="text-align:justify;margin-right:200px;margin-left:200px;">
<hr class="win-command">
<button class="win-command" onclick="parent.location='Start.jsp'">
<span class="win-commandimage win-commandring"></span>
<span class="win-label">Start</span>
</button>
<hr class="win-command">
<button class="win-command" onclick="parent.location='Statistics.jsp'">
<span class="win-commandimage win-commandring"></span>
<span class="win-label">Statistics</span>
</button>
<hr class="win-command">
<button class="win-command" onclick="showchat();">
<span class="win-commandimage win-commandring">]</span>
<span class="win-label">Chat</span>
</button>
<hr class="win-command">
<button class="win-command" onclick="parent.location='Setup.jsp'">
<span class="win-commandimage win-commandring"></span>
<span class="win-label">Setup</span>
</button>
<hr class="win-command">
<button class="win-command" onclick="parent.location='Home.jsp'">
<span class="win-commandimage win-commandring"></span>
<span class="win-label">Logout</span>
</button>
<hr class="win-command">
<div id="top-info" class="pull-right">
<a class="pull-left" href="#">
<div class="top-info-block">
<h3>Coca Cola Hellenic Company Serbia doo
</h3>
</div>
<div class="top-info-block">
<b class="icon-user"></b>
</div>
</a>
</div>
<span class="label label-success" style="display: block;background-color: #AA40FF;"> <h1>BROKERS ACCOUNTS</h1></span>
<p> <h2>Create a purchase documents for your clients </h2></p>
<p><h4>Your clients need not come to your office to sign a document for a purchase of stocks to be made. You can generate these documents online and send them to your clients for signing via smart card .
Generate a pdf document and send it to your clients by email for signing .
</h4></p>
<form onsubmit="return sendformdata();" style="margin: 30px;" target="_blank" action="GenerateBrokersPdf" method="post">
<label>Document title</label>
<input type="text" name="doctitle" id="doctitles" class="input-xxlarge" placeholder="Enter the document title"/>
<label>Document creation date</label>
<input type="text" id="datepicker" name="docdate" class="input-xxlarge" placeholder="Click to enter document creation date"/>
<label>Set the document text</label>
<textarea name="brokerstext" id="brokerstext" maxlength="999999" placeholder="The document text content" rows="20" cols="50" class="input-xxlarge" ></textarea>
<p><button type="submit" class="btn" style="margin-left: 25px;" >GENERATE A PDF DOCUMENT </button></p>
</form>
<script type="text/javascript">
function sendformdata()
{
if (document.getElementById("doctitles").value=="")
{
document.getElementById("mymessagesbody").innerHTML="<p><h2>You must input the document title</h2><p>" ;
$('#myModal2').modal("toggle");
return false;
}
if (document.getElementById("datepicker").value=="")
{
document.getElementById("mymessagesbody").innerHTML="<p><h2>You must input the document date</h2><p>" ;
$('#myModal2').modal("toggle");
return false;
}
if (document.getElementById("brokerstext").value=="")
{
document.getElementById("mymessagesbody").innerHTML="<p><h2>You must input the document content text</h2><p>" ;
$('#myModal2').modal("toggle");
return false;
}
}
</script>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
window.jQuery || document.write("<script src='scripts/jquery-1.8.2.min.js'>\x3C/script>")
</script>
<script src="scripts/google-code-prettify/prettify.js" type="text/javascript"></script>
<script src="scripts/jquery.mousewheel.js" type="text/javascript"></script>
<script src="scripts/jquery.scrollTo.js" type="text/javascript"></script>
<script src="scripts/jquery.blockUI.js" type="text/javascript"></script>
<script src="scripts/jquery.form.js" type="text/javascript"></script>
<script src="scripts/jquery.validate.js" type="text/javascript"></script>
<script src="scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
<script src="scripts/modernizr-2.6.1.min.js" type="text/javascript"></script>
<script src="scripts/mustache.js" type="text/javascript"></script>
<script src="scripts/bootstrap.min.js" type="text/javascript"></script>
<script src="scripts/bootstrap.js" type="text/javascript"></script>
<script src="scripts/bootmetro.js" type="text/javascript"></script>
<script src="scripts/bootmetro-charms.js" type="text/javascript"></script>
<script src="scripts/demo.js" type="text/javascript"></script>
<script src="scripts/holder.js" type="text/javascript"></script>
<script src="scripts/bootstrap-datepicker.js" type="text/javascript"></script>
<script src="scripts/daterangepicker.js" type="text/javascript"></script>
<script src="scripts/holder.js" type="text/javascript"></script>
<script type="text/javascript">
$(".metro").metro();
</script>
<div id="charms" class="win-ui-dark in" style="display: none;">
<div id="theme-charms-section" class="charms-section">
<div class="charms-header">
<a class="close-charms win-command" href="#" onclick="showchat();">
<span class="win-commandimage win-commandring"></span>
</a>
<h2>Chat</h2>
</div>
<div class="row-fluid">
<div class="span12">
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<div id="myModal2" class="modal message hide fade in" aria-hidden="false" aria-labelledby="myModalLabel" role="dialog" tabindex="-1" style="display: none;">
<div class="modal-header">
<button class="close" aria-hidden="true" data-dismiss="modal" type="button"></button>
<h3>Message</h3>
</div>
<div class="modal-body" id="mymessagesbody">
<p></p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Close</button>
</div>
</div>
<footer ><p style="margin-left:25px;"> © 2013 compensatemeonline.com </p></footer>
</body>
</html>
1) You need to set the data content type to utf-8 before submitting the data. Because receiver(in this case, servlet) needs to know what encoding was set(in JSP) for the data before servlet actually decodes the bytes.
ie: request.setCharacterEncoding("UTF-8");
2) <%#page pageEncoding="UTF-8"%> is not used for the java data. This line is used to tell what language the JSP file was written in. ie: English, Chinese. I think you totally misunderstood this line.
Answer Updated:
3) Remove this line >> String(request.getParameter("brokerstext").getBytes("iso-8859-1")), "UTF-8"); You don't need to convert received UTF-8 bytes to iso.
Note: Please post your JSP code
The problem is that when parsing the form fields tomcat doesn't know the charset used.
This is normally resolved using a filter that changes charset in request.
Create the following class:
public class EncodingSetterFilter implements Filter
{
/** Creates a new instance of EncodingSetterFilter */
public EncodingSetterFilter()
{
}
public void init(FilterConfig filterConfig) throws ServletException
{
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
servletRequest.setCharacterEncoding("UTF-8");
filterChain.doFilter(servletRequest, servletResponse);
}
public void destroy()
{
}
}
And then configure its usage in web.xml (be sure to specify correct filter class):
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>
com.yourpackage.EncodingFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Related
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?
That this wrong in the code? I want to make an answer HttpServlet with an if but "I appear "the left-hand an assignment must be a variable" in the last else, I cannot correctly declare the method, How can I fix it?
package controladores;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class AjaxController
*/
#WebServlet("/AjaxController")
public class AjaxController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public AjaxController() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain ");
PrintWriter out = response.getWriter();
String action = request.getParameter("action");
if(action.equals("demo1")){
String nombreCompleto = request.getParameter("nombreCompleto");
out.println("Hola " + nombreCompleto);
}
else if (action.equals("demo2")){
int a = Integer.parseInt(request.getParameter("numero1"));
int b = Integer.parseInt(request.getParameter("numero2"));
out.println(a + b);
} else(action.equals("demo3")){
int d = Integer.parseInt(request.getParameter("numa"));
int c = Integer.parseInt(request.getParameter("numb"));
out.println(c * d);
}
}
}
and index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Demo Ajax</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet"/>
<link href="" rel="stylesheet"/>
<link type="text/css" rel="stylesheet" href="resources/css/miPrimerCSS.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#unHola').click(function(){
var nombreCompleto = $('#nombreCompleto').val();
$.ajax({
type:'POST',
data: {
nombreCompleto : nombreCompleto,
action: 'demo1'
},
url: 'AjaxController',
success: function(result){
$('#resultadoNombre').html(result);
}
});
});
$('#unaSuma').click(function(){
var numero1 = $('#numero1').val();
var numero2 = $('#numero2').val();
$.ajax({
type:'POST',
data: {
numero1 : numero1,
numero2 : numero2,
action: 'demo2'
},
url:'AjaxController',
success : function(result){
$('#resultadoSuma').html(result);
}
});
});
$('#unProducto').click(function(){
var numero1 = $('#numa').val();
var numero2 = $('#numb').val();
$.ajax({
type:'POST',
data: {
numa : numa,
numb : numb,
action: 'demo3'
},
url:'AjaxController',
success : function(result){
$('#resultadoProd').html(result);
}
});
});
});
</script>
</head>
<body>
<nav>
<div class="nav-wrapper">
Logo
<ul class="right hide-on-med-and-down">
<li>Home</li>
<li>Pages</li>
<li>About us</li>
<li>Lab</li>
<!-- Dropdown Trigger -->
<!-- <li><a class="dropdown-button" href="#!" data-activates="dropdown1">Dropdown<i class="material-icons right">arrow_drop_down</i></a></li> -->
</ul>
</div>
</nav>
<div class="container">
<p class="z-depth-5">
<fieldset>
<h3>Un Hola</h3>
<form>
Introduce tu nombre <input type="text" id="nombreCompleto"><br>
<input type="button" value="Hola" id="unHola"><br>
<span id="resultadoNombre"></span>
</form>
</fieldset>
</div>
<br><br>
<div class="container">
<fieldset>
<h3>Una Suma</h3>
<form>
Numero 1 <input type="text" id="numero1"><br>
Numero 2 <input type="text" id="numero2"><br>
Resultado <span
id=resultadoSuma></span><br> <input type="button" value="Suma"
id="unaSuma">
</form>
</fieldset>
</div>
<div class="container">
<fieldset>
<h3>Un Producto</h3>
<form>
Numero 1 <input type="text" id="numero1"><br>
Numero 2 <input type="text" id="numero2"><br>
Resultado <span id=resultadoProd></span><br> <input type="button" value="Producto"
id="unProducto">
</form>
</fieldset>
</div>
<footer class="page-footer">
<div class="container">
<h5 class="white-text">Footer Content</h5>
</div>
<div class="footer-copyright">
<div class="container">
© 2014 Copyright Text
<a class="grey-text text-lighten-4 right" href="#!">More Links</a>
</div>
</div>
</footer>
</body>
</html>
} else(action.equals("demo3")){
I assume you meant:
} else if(action.equals("demo3")){
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';
});
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