method doPost, assignment of if in eclipse and servlets - java

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")){

Related

Sending data(Objects) from Servlet to BootStrap Modal in the same page of JSP

In my application built on Java, JSP with BootStrap, and Servlet, there is the issue to send the data from Servlet to BootStrap Modal.
Based on my project, a user clicks the 'check button' in each table container and that table_id is caught in javascript and send it to Servlet with that value. Then Servlet operates on grabbing the data from the database based on its table_id. The result(orders in the code and results are displayed properly when printing out them) of the operation needed to send to the BootStrap modal section.
TableMonitor.jsp
<%# page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="/docs/4.0/assets/img/favicons/favicon.ico">
<title>Migarock Table Monitoring System</title>
<link rel="canonical"
href="https://getbootstrap.com/docs/4.0/examples/pricing/">
<!-- Bootstrap core CSS -->
<link href="../../dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="pricing.css" rel="stylesheet">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
<link href="./css/tableMonitor.css" rel="stylesheet">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
</head>
<body>
<!--
<div class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom box-shadow">
<h3 class="my-0 mr-md-auto font-weight-normal">Migarock Table Monitoring System</h3>
<a class="btn btn-outline-primary" href="#">Lock</a>
</div> -->
<div class="row">
<div class="col-2">
<div class="container">
<div class="card-deck mb-3 text-center ">
<div class="card mb-4 box-shadow ">
<div class="card-header status1">
<h3 class="my-0 font-weight-normal ">
<strong>Table_01</strong>
</h3>
</div>
<div class="card-body">
<a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
data-toggle="modal" href="#tableModal" data-table-id="1">Check</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-2">
<div class="container">
<div class="card-deck mb-3 text-center">
<div class="card mb-4 box-shadow">
<div class="card-header">
<h3 class="my-0 font-weight-normal">
<strong>Table_02</strong>
</h3>
</div>
<div class="card-body">
<a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
data-toggle="modal" href="#tableModal" data-table-id="2">Check</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-2">
<div class="container">
<div class="card-deck mb-3 text-center">
<div class="card mb-4 box-shadow">
<div class="card-header status2">
<h3 class="my-0 font-weight-normal">
<strong>Table_03</strong>
</h3>
</div>
<div class="card-body">
<a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
data-toggle="modal" href="#tableModal" data-table-id="3">Check</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-2">
<div class="container">
<div class="card-deck mb-3 text-center">
<div class="card mb-4 box-shadow">
<div class="card-header">
<h3 class="my-0 font-weight-normal">
<strong>Table_04</strong>
</h3>
</div>
<div class="card-body">
<a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
data-toggle="modal" href="#tableModal" data-table-id="4">Check</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-2">
<div class="container">
<div class="card-deck mb-3 text-center">
<div class="card mb-4 box-shadow">
<div class="card-header">
<h3 class="my-0 font-weight-normal">
<strong>Table_05</strong>
</h3>
</div>
<div class="card-body">
<a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
data-toggle="modal" href="#tableModal" data-table-id="5">Check</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-2">
<div class="container">
<div class="card-deck mb-3 text-center">
<div class="card mb-4 box-shadow ">
<div class="card-header status3">
<h3 class="my-0 font-weight-normal">
<strong>Table_06</strong>
</h3>
</div>
<div class="card-body">
<a class="btn btn-outline-primary btn-lg btn-block mx-1 mt-1"
data-toggle="modal" href="#tableModal" data-table-id="6">Check</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="tableModal" tabindex="1" role="dialog"
aria-labelledby="modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title" id="modal">Table Status</h2>
<button type="button" class="close" data-dismiss="modal"
aria-label="close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="controlBar">
<div class="row">
<div class="col-8" style="text-align: left;">
<button type="button" class="btn btn-outline-success btn-lg"
data-dismiss="modal">Add item</button>
<button type="button" class="btn btn-outline-secondary btn-lg"
data-dismiss="modal">Change Status</button>
</div>
<div class="col-4" style="text-align: right; padding-right: 10%;">
<button type="button" class="btn btn-outline-warning btn-lg"
data-dismiss="modal">Help</button>
<button type="button" class="btn btn-outline-info btn-lg"
data-dismiss="modal">Bill</button>
</div>
</div>
<div>
<div class="modal-body">
<h3>My name is ${test}</h3>
<!-- <form action="./evaluationRegisterAction.jsp" method="post"> -->
<div class="scrollbar scrollbar-primary">
<!-- <div> -->
<table class="table">
<thead>
<tr style="text-align: center;">
<th scope="col"><input type="checkbox"
class="select-all checkbox" name="select-all" /></th>
<th scope="col">OrderTime</th>
<th scope="col">Item</th>
<th scope="col">QTY</th>
<th scope="col">Price</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
<c:out value="${requestScope.orders}">
<c:forEach items="${orders}" var="order">
<tr style="text-align: center;">
<td style="text-align: center;">
<div class="form-check">
<input type="checkbox" class="select-item checkbox"
name="select-item">
</div>
</td>
<td><span id="orders"></span> ${order.getTimeStamp()}</td>
<td>{order.getOrderItem()}</td>
<td>{order.getOrderQty()}</td>
<td>{order.getOrderPrice()}</td>
<td>{order.getOrderStatus()}</td>
<td><a class="btn btn-light btn-sm mx-1 mt-2"
data-toggle="modal" href="#changeStatus">Ordered</a> <!-- <a class="btn btn-dark btn-sm mx-1 mt-2" data-toggle="modal"
href="#changeStatus">Delivered</a> -->
</td>
</tr>
</c:forEach>
</c:out>
</tbody>
</table>
</div>
</div>
<div>
<table class="table">
<tr style="text-align: center;">
<td colspan="3">
<h4>Total</h4>
</td>
<td colspan="3">
<h4>(total)</h4>
</td>
</tr>
</table>
</div>
<div class="controlBar">
<div class="row">
<div class="col-6" style="text-align: left;">
<button type="button" class="btn btn-danger btn-lg"
data-dismiss="modal">Close Session</button>
</div>
<div class="col-6"
style="text-align: right; padding-right: 10%;">
<button type="button" class="btn btn-outline-danger btn-lg"
data-dismiss="modal">Close Window</button>
</div>
</div>
</div>
</div>
<!-- </form> -->
</div>
</div>
</div>
</div>
<footer class="pt-4 my-md-5 pt-md-5 border-top"> </footer>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script>
window.jQuery
|| document
.write('<script src="../../assets/js/vendor/jquery-slim.min.js"><\/script>')
</script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script>
Holder.addTheme('thumb', {
bg : '#55595c',
fg : '#eceeef',
text : 'Thumbnail'
});
</script>
<script>
$(function() {
//button select all or cancel
$("#select-all").click(function() {
var all = $("input.select-all")[0];
all.checked = !all.checked
var checked = all.checked;
$("input.select-item").each(function(index, item) {
item.checked = checked;
});
});
//button select invert
$("#select-invert").click(function() {
$("input.select-item").each(function(index, item) {
item.checked = !item.checked;
});
checkSelected();
});
//button get selected info
$("#selected").click(
function() {
var items = [];
$("input.select-item:checked:checked").each(
function(index, item) {
items[index] = item.value;
});
if (items.length < 1) {
alert("no selected items!!!");
} else {
var values = items.join(',');
console.log(values);
var html = $("<div></div>");
html.html("selected:" + values);
html.appendTo("body");
}
});
//column checkbox select all or cancel
$("input.select-all").click(function() {
var checked = this.checked;
$("input.select-item").each(function(index, item) {
item.checked = checked;
});
});
//check selected items
$("input.select-item").click(function() {
var checked = this.checked;
console.log(checked);
checkSelected();
});
//check is all selected
function checkSelected() {
var all = $("input.select-all")[0];
var total = $("input.select-item").length;
var len = $("input.select-item:checked:checked").length;
console.log("total:" + total);
console.log("len:" + len);
all.checked = len === total;
}
});
$('#tableModal')
.on(
'show.bs.modal',
function(e) {
var tableID = $(e.relatedTarget).data('table-id');
console.log("test: ", tableID)
$(e.currentTarget).find('input[name="tableID"]')
.val(tableID);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("response").value = xhttp.responseText;
}
};
xhttp.open("POST", "TableMonitor", true);
xhttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xhttp.send("tableId=" + tableID);
var orders = $(this).data('orders');
$('#orders').html(orders);
});
</script>
</body>
</html>
TableMonitor.java(Servlet)
package servlets;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
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 brokers.TableBrokder;
import model.Order;
/**
* Servlet implementation class TableMonitor
*/
#WebServlet("/TableMonitor")
public class TableMonitor extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TableMonitor() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
getServletContext().getRequestDispatcher("/TableMonitor.jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String table_id = request.getParameter("tableId");
String action = request.getParameter("action");
System.out.println("servlet: " + table_id);
List<Order> orders = null;
TableBrokder tb = new TableBrokder();
try {
orders = tb.getOrderAll(Integer.parseInt(table_id));
} catch (NumberFormatException | SQLException e) {
e.printStackTrace();
}
for (int i = 0; i < orders.size(); i++) {
orders.get(i).toString();
}
// response.sendRedirect("TableMonitor");
RequestDispatcher dispatcher = request.getRequestDispatcher("/TableMonitor.jsp");
request.setAttribute("orders", orders);
request.setAttribute("test", "test");
dispatcher.forward(request, response);
}
}
Even though I google it but didn't get clear answers. Could you help me with this issue?
Looks like you are making an ajax call in your js but in your servlet you are not returning the response. I highly recommend checking out this answer on how to make ajax calls with servlets.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String table_id = request.getParameter("tableId");
String action = request.getParameter("action");
System.out.println("servlet: " + table_id);
List<Order> orders = null;
TableBrokder tb = new TableBrokder();
try {
orders = tb.getOrderAll(Integer.parseInt(table_id));
} catch (NumberFormatException | SQLException e) {
e.printStackTrace();
}
for (int i = 0; i < orders.size(); i++) {
orders.get(i).toString();
}
//convert your list of orders to json
String json = new Gson().toJson(orders);
//add json to response
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
When you make ajax calls you won't be able to do things like this:
request.setAttribute("orders", orders);
request.setAttribute("test", "test");
Because when you call this servlet url through ajax, you are not loading the jsp page again so the HttpServletRequest won't be passed to the jsp page. Hope this helps understand it some more.

JSP and Servlet NullPointer - display class attribute in text field

I am creating a project with JSP & Servlet (and entity beans) and I am trying to create a form where a user registers as a customer and is then redirected to a reservation page.
I want to keep the Id for the Customer that just registered and fill it into a disabled text field and then create a reservation on the next page. But whenever I try to load the customer class through jsp the whole application crashes with a NullPointerException.
It seems like the program crashes when it reaches the jsp-tags to fetch my customer, since it does print out the c.cPnr to the console as well as the test in the JSP-file.
<%# page import = "g24.isp.ejb.Customer" %>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to Ski Village!</title>
<link rel="stylesheet" href="new/css/normalize.css">
<link rel="stylesheet" href="new/css/stylesheet.css">
<link href='https://fonts.googleapis.com/css?family=Fjalla+One|Poppins:400,500,600' rel='stylesheet' type='text/css'>
<script src="javascript/script.js" type="text/javascript"></script>
</head>
<body>
<% System.out.println("test"); %>
<% Customer c = (Customer) session.getAttribute("customer"); %>
<div id="container">
<!-- HEADER + MENU -->
<header>
<div class="logo"><!-- Ski Village Logo --></div>
<div class="menu">
<ul>
<li> Home </li>
<li class="left-menu"> About </li>
<li class="right-menu"> Book </li>
<li> <a href="index.html" > Test</a></li>
</ul>
</div>
</header>
<!-- PAGE CONTENT -->
<div id="wrapper">
<div class="center-form">
<form action="/HotelClient/HotelServlet" name="resForm" method="post">
<input type="text" name="cPnr" value="<%= c.getcPnr() %>" >
<input type="number" name="week" min="1" max="52" placeholder="Select week" >
<select name="cno">
<option value="1">Adventure Cabin
</option>
<option value="2">Cozy Cabin
</option>
<option value="3">Snowy Cabin
</option>
<option value="4">Hacker Cabin
</option>
</select>
<input type="submit" name="checkres" value="Check availability">
<input type="submit" name="submitresform" value="Create reservation" type="hidden">
<input name="operation" value="bajskorv" type="hidden">
</form>
</div>
<!-- FOOTER + SOCIAL ICONS -->
<footer>
<img src="img/facebook-logo.png" class="social-icon" alt="facebook logo">
<img src="img/instagram-logo.png" class="social-icon" alt="instagram logo">
<img src="img/twitter-logo.png" class="social-icon" alt="twitter logo">
<p>© 2016 | Ski Village</p>
</footer>
</div>
</div>
</body>
</html>
Servlet code:
package g24.isp.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
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;
import g24.isp.ejb.Cabin;
import g24.isp.ejb.Customer;
import g24.isp.ejb.Hotel;
import g24.isp.ejb.Reservation;
import g24.isp.facade.Facade;
import g24.isp.facade.FacadeLocal;
import g24.isp.ejb.MethodClass;
/**
* Servlet implementation class HotelServlet
*/
#WebServlet("/HotelServlet")
public class HotelServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB
private FacadeLocal facade;
/**
* #see HttpServlet#HttpServlet()
*/
public HotelServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
out.println("MainServlet-doGet");
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String url = "did not get an url";
// Get hidden field
String operation = request.getParameter("operation");
MethodClass mc = new MethodClass();
if (operation.equals("createcustomer")) {
String cPnr = request.getParameter("txtcPnr");
String cAddress = request.getParameter("txtcAddress");
String cPhone = request.getParameter("txtcPhone");
String cName = request.getParameter("txtcName");
if (facade.findByCpnr(cPnr) == null) {
Customer customer = new Customer();
customer.setcPnr(cPnr);
customer.setcAddress(cAddress);
customer.setcPhone(cPhone);
customer.setcName(cName);
facade.createCustomer(customer);
url = "/new/reservation.jsp";
} else {
url = "new/newcust.jsp";
}
}
else if (operation.equals("createreservation")) {
String cpnr = request.getParameter("txtcPnr");
int week = mc.ParseStringToInt(request.getParameter("week"));
int cno = mc.ParseStringToInt(request.getParameter("cno"));
Customer cs = facade.findByCpnr(cpnr);
Cabin cb = facade.findByCabinNo(cno);
if (cb != null && cs != null) {
Reservation res = new Reservation();
res.setCabin(cb);
res.setCustomer(cs);
res.setrDate(week);
facade.createReservation(res);
url = "/Index.jsp";
} else {
System.out.println("Did not enter if statement");
url = "/Index.jsp";
}
}
else if (operation.equals("newcustomer")) {
url = "/new/newcust.jsp";
}
else if (operation.equals("setcustomer")) {
System.out.println("Servlet - Create reservation");
String cpnr = request.getParameter("txtcPnr");
System.out.println(cpnr);
url = "/new/reservation.jsp";
Customer customer = facade.findByCpnr(cpnr);
if (customer != null) {
System.out.println(customer.getcName());
session.setAttribute("customer", customer);
url = "/reservation.jsp";
}
else {
System.out.println("Customer value is null");
}
}
System.out.println(url);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
May be it's not setting the session attribute and when c.getcPnr() gets executed, it throws NullPointerException. Can you check whether the attribute is set in the session? You can try printing out 'c' in the jsp.
I solved the problem - i was trying to find the customer by accessing the facade.findBycPnr() method.
The solution was to session.setAttribute(customer, cust) when creating the customer.

How to combine an javabean with jquery validation plugin?

I am building a web app where users can sign up. I have a jquery validation method for the signup form.
What I need is to also validate the username for availability according to my database.
I am not allowed to use php to do this, so i need to use java, a javabean for that cause.
How can i combine jquery and java like this ? Should i use the "remote" command from jquery or combine validation with another function ?
If name already exists n database i don't want my form to submit.
Signup.xhtml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>TODO supply a title</title>
<link rel="stylesheet" type="text/css" href="newcss.css" />
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet"></link>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="jquery.js" type="text/javascript"></script>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/additional-methods.min.js" type="text/javascript"></script>
<script src="validate.js" type="text/javascript"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div id="container" align="center">
<h2>User Registration</h2>
<form action="welcome.xhtml" method="post" id="contact_form">
<div>
<label for="name">Name</label>
<input id="name" type="text" name="name"/>
<span id="nameInfo"></span>
</div>
<div >
<label for="email" >Email</label>
<input id="email" type="text" name="email"/>
<span id="emailInfo"></span>
</div>
<div>
<label for="password">password</label>
<input id="password" type="password" name="pass1"/>
<span id="pass1Info"></span>
</div>
<div>
<label for="confirm">confirm password</label>
<input id="confirm" type="password" name="pass2"/>
<span id="pass2Info"></span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message"/>
<span id="messageInfo"></span>
</div>
<div>
<input id="send" name="send" type="submit" value="Send"/>
</div>
<br/>
<!-- <p>Already registered? Sign in.</p> -->
</form>
</div>
</body>
</html>
validate.js
$(document).ready(function () {
//Validation rules for form
$("#contact_form").validate({
// Specify the validation rules
rules: {
name: {
required: true
// remote: ???
},
password: {
required: true,
minlength: 5
},
confirm: {
required: true,
equalto: "#password"
},
email: {
required: true,
email: true
}
},
// Specify the validation error messages
messages: {
name: "Please enter your name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm:{
equalto: "Passwords are not matching"
},
email: "Please enter a valid email address"
},
submitHandler: function (form) {
form.submit();
}
});
});
CheckAvailability.java (I inserted as js, cause it would not retain its format)
package Beans;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class CheckAvailability extends HttpServlet {
private static final long serialVersionUID = -734503860925086969L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String connectionURL = "jdbc:mysql://localhost:3306/teddb"; // teddb is my database name
Connection connection;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "Sk1994!!");
String uname = request.getParameter("name");
PreparedStatement ps = connection.prepareStatement("select username from users where username=?");
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
out.println("");
}
else{
out.println("Username already in use");
}
out.println();
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
out.println("Error ->" + ex.getMessage());
} finally {
out.close();
}
}
}

Application using SOAP webservices, signup functionality not working on client side

Am creating a web application using SOAP web services in java. Sign up functionality works fine when I test through the test client at the server side however, at the client side when I fill in the details and click on signUp button the same page is getting refreshed but no action is being performed (data is not getting inserted into the database). When debugged, I saw that the code is failing at
if(qdone.equalsIgnoreCase("true")){
Could anyone please help me with this. I'm not knowing where am I going wrong.
Here is my code
signUp.jsp
<%# page contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link href="Flat-UI-master/css/flat-ui.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link rel="shortcut icon" href="Flat-UI-master/images/favicon.ico">
<link rel="stylesheet" href="Flat-UI-master/bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="css/icon-font.css">
</head>
<body>
<div id="page-wrapper">
<header class="header-11">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="row">
<div class="navbar-collapse collapse in" style="height: auto;">
<ul class="nav navbar-nav">
<li class="active"><span class="glyphicon glyphicon-home"></span>Home</li>
<li>College Explorer
<li>Fund Raisers</li>
<li>FAFSA</li>
<li>Student Loans</li>
</ul>
<ul class="nav pull-right">
<li><a class="btn btn-primary" href="signIn.jsp">SIGN IN</a> </li>
</ul>
</div>
</div>
</div>
</div>
</header>
<br>
<br>
<br>
<section class="header-11-sub bg-midnight-blue">
<div class="background"> </div>
<div class="container">
<div class="row">
<div class="col-sm-4">
<h3>Task Tracker</h3>
<p>Make your life easy having a task tracker</p>
<div class="signup-form">
<form id="form" method="post" action="signUp">
<div class="form-group">
<input class="form-control" type="text" placeholder="username"
id="username">
</div>
<div class="form-group">
<input class="form-control" type="password"
placeholder="password" id="password">
</div>
<div class="form-group">
<input class="form-control" type="text" placeholder="fname"
id="fname">
</div>
<div class="form-group">
<input class="form-control" type="text" placeholder="lname"
id="lname">
</div>
<div class="form-group">
<input class="form-control" type="text"
placeholder="email#example.com" id="email">
</div>
<div class="form-group">
<button type="submit" class="btn btn-large btn-primary">Sign
Up</button>
<a href='http://localhost:8080/FinalClient/View/signUp.jsp'
class="btn btn-large btn-primary">Cancel</a>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
</div>
<script class="cssdeck"
src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script class="cssdeck"
src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/js/bootstrap.min.js">
</script>
</body>
</html>
signUp Servlet (signUp.java)
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.jws.WebService;
import javax.servlet.RequestDispatcher;
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;
import DefaultNamespace.ServiceProxy;
/**
* Servlet implementation class signUp
*/
#WebServlet("/signUp")
public class signUp extends HttpServlet {
private static final long serialVersionUID = 1L;
ServiceProxy proxy =new ServiceProxy();
/**
* #see HttpServlet#HttpServlet()
*/
public signUp() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out =response.getWriter();
response.setContentType("text/html");
String qdone;
try{
String username = request.getParameter("username");
String password = request.getParameter("password");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
if (!checkMandatorySignUpFields(username, password, fname, lname, email)) {
request.setAttribute("message", "Required Field Missing!");
String nextJSP = "/View/signUp.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request, response);
}else {
proxy.setEndpoint("http://localhost:8080/Final/services/Service");
System.out.println("crossed the endpoint");
qdone=proxy.signUp(username,password,fname,lname,email);
System.out.println(qdone);
System.out.println("signup qdone");
HttpSession session =request.getSession();
System.out.println("Session started");
if(qdone.equalsIgnoreCase("true")){
System.out.println("qdone value obtained....signup successful");
session.setAttribute("userSession", session);
out.println("Welcome to CollegeTime Task planner" +username);
request.setAttribute("message", "Signup successful, Please login.");
String nextJSP= "/View/signIn.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request, response);
}else{
out.println(qdone.equalsIgnoreCase("false"));
out.println("\n <a href='http://localhost:8080/FinalClient/View/signUp.jsp'><br>Go back to Signup and try again</a>");
request.setAttribute("message", "Unable to Signup!" + qdone);
String nextJSP = "/View/signUp.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request, response);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
private boolean checkMandatorySignUpFields(String username, String password, String fname, String lname, String email){
// TODO Auto-generated method stub
return true;
}
}
Service.java (signup functionality) code at the Server side
#WebService
public class Service {
DatabaseConnection db = new DatabaseConnection();
String result="";
public String signUp(String username, String password, String fname, String lname, String email){
System.out.println("Inside SignUp");
result=db.signUp(username, password, fname, lname, email);
System.out.println("SignUp Successful");
System.out.println(result);
return result;
}
Database query implementation for signUp at server side
public String signUp(String username, String password, String fname, String lname, String email){
int rowcount=0;
String result = "";
Calendar cal= Calendar.getInstance();
String time = sdf.format(cal.getTime());
try{
String query="select * from user where username = '"+username+"'";
ResultSet res;
stm.executeQuery(query);
res=stm.getResultSet();
if(!res.next()){
String insertQuery = "insert into user(username, fname, lname, password, email, lastlogin) values ('"+username+"', '"+password+"','"+fname+"','"+lname+"','"+email+"','"+time+"')";
rowcount=stm.executeUpdate(insertQuery);
if(rowcount>0){
result ="true";
}
else{
result="false";
}
}
}catch(SQLException e){
e.printStackTrace();
}
System.out.println(result);
return result;
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>FinalClient</display-name>
<welcome-file-list>
<welcome-file>signUp.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>signUp</display-name>
<servlet-name>signUp</servlet-name>
<servlet-class>servlets.signUp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>signUp</servlet-name>
<url-pattern>/View/signUp</url-pattern>
</servlet-mapping>
</web-app>
My issue was solved. Just posting, in case if anyone in future come across the same issue.
I dint give name attribute in the signUp.jsp form
Previously in signUp.jsp:
<form id="form" method="post" action="signUp">
<div class="form-group">
<input class="form-control" type="text" placeholder="username"
id="username">
</div>
Later(Solution) in signUp.jsp (adding a name attribute):
<form id="form" method="post" action="signUp">
<div class="form-group">
<input class="form-control" type="text" placeholder="username"
id="username" name="username">
</div>

Get letters to servlet the right way

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>

Categories