Here is my code:
#WebServlet({ "/Response1", "/resp" })
public class Response1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int count=0;
int Number =1;
System.out.println("s val is ==> "+request.getParameter("empidVal"));
String s1 = request.getParameter("empidVal");
System.out.println(s1);
services3 empjiras = new services3();
try {
Map<Object, Object> map1 = empjiras.getJiras(s1);
Object obj3 = map1.get("obj3");
map1.remove("obj3");
System.out.println(obj3);
Collection c=map1.values();
String myvalue="";
for (Iterator iterator = c.iterator(); iterator.hasNext();)
{
myvalue = (String) iterator.next();
count++;
}
System.out.println(count);
int count1 = count;
if(count!=0)
{
Set<Map.Entry<Object,Object>> s2=map1.entrySet();
PrintWriter out1=response.getWriter();
out1.println("<html>"+
"<center><font size=\"20\"><body><h2>JIRA Details</h2></font>"+
//"<table border='1'>"+
"<table width=\"800\" border ='10'>\r\n" +
"<tr>\r\n" +
"<th><font size ='+2'>Number</font></th>"+
"<th><font size ='+2'>JiraNumber</font></th>"+
"<th><font size ='+2'>Jira Status</font></th>" +
"<th><font size = '+2'>EmailId</font></th>\r\n</center>"+
"<button type='ok' value='ok'>OK</button>" +
"<button type='cancel' value='cancel'>cancel</button>");
for (Iterator<Map.Entry<Object,Object>> iterator = s2.iterator(); iterator.hasNext();) {
Map.Entry<Object,Object> entry = iterator.next();
Object name2 = entry.getKey();
Object value2 = entry.getValue();
Object email = obj3;
int num = Number++;
PrintWriter out=response.getWriter();
out.println(
"</tr>\r\n" +
"<tr>\r\n" +
"<tr>\r\n" +
"<td height=\"100\">"+num+"</td>"+
"<td height=\"100\">"+name2+"</td>\r\n" +
"<td height=\"100\">"+value2+"</td>\r\n"+
"<td height=\"100\">"+email+"</td>\r\n"+
"</tr>\r\n");
}
out1.println("</table></body></html>");
}
else
{
PrintWriter out=response.getWriter();
// out.println("count is :"+count1);
out.println("<html><body><h2>no jira issues in validating release</h2></body></html>");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here i am embedding the html code in an servlet which I think is not a good practice,actually I am reading the objects from another servlet and then processing it and displaying it in the browser.But is there any way how to separate this html code from the servlet.
Thanks in advance..
asp.net client
.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Image_Identify.aspx.cs"
Inherits="WebApplication.iva.Image_Identify" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data" method="post">
<div>
<asp:Button ID="Button_Post" runat="server" Text="submit" OnClick="Button_PostWebRequest" />
</div>
</form>
</body>
</html>
.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
namespace WebApplication.iva
{
public partial class Image_Identify : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string postUrl = "http://xxx/WebUploadHandleServlet";
string paramData = "E:\\1111.jpg";
string ret = string.Empty;
Encoding dataEncode = Encoding.UTF8;
try
{
byte[] byteArray = dataEncode.GetBytes(paramData);
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "multipart/mixed";
webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
ret = sr.ReadToEnd();
sr.Close();
response.Close();
newStream.Close();
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
}
}
protected void Button_PostWebRequest(object sender, EventArgs e)
{
}
}
}
java server
#WebServlet(asyncSupported = true, urlPatterns = { "/WebUploadHandleServlet" })
public class WebUploadHandleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final long MAXSize = 1024 * 1024 * 4 * 2L;// 4*2MB
private String filedir = null;// before
private String resdir = null;// after
/**
* #see HttpServlet#HttpServlet()
*/
public WebUploadHandleServlet() {
super();
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
System.out.println("init...");
JNIDispatcher.getInstance();
filedir = config.getServletContext().getRealPath("WEB-INF/original_images");
resdir = config.getServletContext().getRealPath("WEB-INF/result_images");
File file1 = new File(filedir);
File file2 = new File(resdir);
if (!file1.exists() && !file2.exists()) {
System.out.println("create dir");
file1.mkdir();
file2.mkdir();
System.out.println("create success");
}
System.out.println("filedir=" + filedir);
System.out.println("resdir=" + resdir);
super.init(config);
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("receive request");
double begin_time = System.currentTimeMillis();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//FileUpload upload = new FileUpload(factory);20161005
upload.setSizeMax(-1);
upload.setHeaderEncoding("utf-8");
ImageDispose disposer = new ImageDispose(filedir, resdir);
// response.setContentType("text/html");
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String respondResult = null;
String filename = null;
try {
List<FileItem> items = upload.parseRequest(request);
if (items != null && !items.isEmpty()) {
System.out.println("items size:" + items.size());
double start_time = System.currentTimeMillis();
for (FileItem fileItem : items) {
filename = fileItem.getName();
String filepath = filedir + File.separator + filename;
System.out.println("file save path:" + filepath);
InputStream inputStream = fileItem.getInputStream();
respondResult = disposer.process(inputStream, filename);
inputStream.close();
fileItem.delete();
}
double end_time = System.currentTimeMillis();
System.out.println("JNI handle" + filename + "time:" + (end_time - start_time) + "ms");
System.out.println("total time:" + (end_time - begin_time));
}
out.write(respondResult);
} catch (Exception e) {
e.printStackTrace();
out.write("文件" + filename + "upload fail:" + e.getMessage());
}
System.out.println("finish!");
}
#Override
public void destroy() {
System.out.println("release JNI...");
JNIDispatcher.getInstance().releaseJNI();
super.destroy();
}
}
I have printed the result as below.
It seems that java server has received the http request but cannot resolve.
Hope for help!
I have a problem when retrieving data (an Integer value) between servlets, when I want to multiply the value retrieved. I have this function in my first servlet,
private int totalNumberOf(Map<String,Integer> cart) {
int counter = 0;
for (String key : cart.keySet())
counter += cart.get(key);
return counter;
}
And I also have the attribute for it (placed at the end of the doGet() method)...
req.setAttribute("quantity", new Integer(totalNumberOf(cart)));
, a function that gives me the total number of products that are in the cart, which updates the value every time I add something to the cart so when I finish buying I can get an updated value of the number of products that are currently in the cart.
The problem comes now, when I try to do the fictional checkout (because I just have a generic price for every type of product) and I have to multiply the number of items by the generic price (here's where the NullPointer shows up).
Here's the code of my second servlet,
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer quantity;
int toPay;
int genericValue = 20;
quantity = (Integer) req.getAttribute("quantity");
toPay = quantity.intValue() * genericValue; // NullPointer
}
I've tried everything in every way but I can't get rid of that ugly NullPointer. Hope you can help me a bit with this...
UPDATE Servlet1
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
String mensajeBienvenida = "";
Map<String,Integer> carrito = null;
String articuloElegido = req.getParameter("producto");
HttpSession session = req.getSession();
if (session.isNew()) {
session.invalidate();
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.html");
dispatcher.forward(req, res);
}
else {
String nombreUsuario = ((Usuario)session.getAttribute("user")).getNombre();
if (session.getAttribute("carrito") == null) {
carrito = new HashMap<String,Integer>();
session.setAttribute("carrito",carrito);
mensajeBienvenida="Bienvenido a la tienda, " + nombreUsuario + "!";
}
else {
carrito = (Map<String,Integer>) session.getAttribute("carrito");
mensajeBienvenida = "Qué bien que sigas comprando, " + nombreUsuario + "!";
}
insertarEnCarrito(carrito, articuloElegido);
}
req.setAttribute("mensaje", mensajeBienvenida);
req.setAttribute("cesta", cestaDeLaCompraEnHTML(carrito));
req.setAttribute("cantidad", numeroTotalLibros(carrito));
RequestDispatcher dispatcher = getServletContext().getNamedDispatcher("VistaTienda");
dispatcher.forward(req, res);
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}
private void insertarEnCarrito(Map<String,Integer> carrito, String articulo) {
if (carrito.get(articulo) == null){
carrito.put(articulo, new Integer(1));
}
else {
int numeroArticulos = (Integer)carrito.get(articulo).intValue();
carrito.put(articulo, new Integer(numeroArticulos+1));
}
}
private String cestaDeLaCompraEnHTML(Map<String,Integer> carrito) {
String cestaEnHTML = "";
for (String key : carrito.keySet())
cestaEnHTML += "<p>["+key+"], "+carrito.get(key)+" unidades</p>";
return cestaEnHTML;
}
private int numeroTotalLibros(Map<String,Integer> carrito) {
int counterLibro = 0;
for (String key : carrito.keySet())
counterLibro += carrito.get(key);
return counterLibro;
}
}
Servlet2
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
String mensajeBienvenida;
String cestaDeLaCompraEnHTML;
mensajeBienvenida = (String) req.getAttribute("mensaje");
cestaDeLaCompraEnHTML = (String) req.getAttribute("cesta");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Tienda con login!</TITLE></HEAD>");
out.println("<BODY>" + mensajeBienvenida + "<br>");
out.println(cestaDeLaCompraEnHTML + "<br>");
out.println("PRUEBA CANTIDAD LIBROS EN TOTAL - " + req.getAttribute("cantidad") + "<br>");
out.println("Seguir comprando!</BODY></HTML>");
out.println("Anular Compra</BODY></HTML>");
out.println("Pagar Compra</BODY></HTML>");
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}
Servlet3
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer cantidadLibro;
int pagar;
int valorLibro = 20;
Map<String,Integer> carrito = (Map<String,Integer>) session.getAttribute("carrito");
Usuario usuario = (Usuario) session.getAttribute("user");
cantidadLibro = (Integer) req.getAttribute("cantidad");
if (cantidadLibro == null){
cantidadLibro = 0;
} else {
cantidadLibro = (Integer) req.getAttribute("cantidad");
}
// pagar = cantidadLibro.intValue() * valorLibro;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Tienda con login!</TITLE></HEAD>");
out.println("<BODY><p><b>COMPRA REALIZADA!</b><br>");
out.println("<br><p>Total a pagar por su compra - " + "<br>");
out.println("<br><p>PRUEBA getAttribute - " + req.getAttribute("cantidad") + "<br>");
out.println("<br><p>Gracias por su compra " + usuario.getNombre() + " " + usuario.getApellidos() + "<br>");
out.println("<br><p>e-mail del usuario - " + usuario.getEmail() + "<br>");
out.println("<br><p>User ID - " + usuario.getId() + "<br>");
session.invalidate();
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}
Besides the refactoring and optimisation that your code might need, the problem you are refering to is that your are setting the attribute "cantidad" to the request instead of the session.
In Servlet1, replace this
req.setAttribute("cantidad", numeroTotalLibros(carrito));
with this
session.setAttribute("cantidad", numeroTotalLibros(carrito));
And in Servlet3, replace this
cantidadLibro = (Integer) req.getAttribute("cantidad");
with this
cantidadLibro = (Integer) session.getAttribute("cantidad");
The reason is that you are forwarding your request from Servlet1 to Servlet2, and so in Servlet2 you can access the "forwarded" request and all its attributes, BUT Serlvet3 is called independently at a later stage. I guess that is when you press "Pagar" in the rendered HTML page. Therefore, you can no longer access those attributes via the request because it is a different request. You can instead access them via the session if you stored them there previously.
Hope this helps.
Have you ever heard about debugging tools?
Your quantity variable has null value, it could be because of abscense attribute quantity in request. That is why you got NPE: null * (primitive numeric constant) -> NullPointerException.
From your code it it looks like "quantity.intValue()" throws your null pointer because quantity is null. Try this:
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer quantity = 0;
int toPay;
int genericValue = 20;
if (req.getAttribute("quantity") != null) {
quantity = (Integer) req.getAttribute("quantity");
}
toPay = quantity.intValue() * genericValue;
}
Notice not only do I initialize quantity with a value of 0 (so that it is not null) I also add a null check to "req.getAttribute("quantity")" so that you do not assign null to quantity in the case where .getAttribute returns null.
It's likely that your getAttribute function returned null. Remember to do null checking in code. I suggest a if (quantity != null) check before you call .intValue()
Another possible solution would be to check what .getAttribute() returned instead of checking what quantity was set to. You could also give quantity a default value.
if (req.getAttribute("quantity") == null) {
quantity = 0;
} else {
quantity = (Integer) req.getAttribute("quantity");
}
I am dispatching a request to html resource in Webcontent folder in servlet. But its not dispatching it. Even its not giving any exception. AboutUs is an html page placed in WebContent folder of project. The IDE i am using is eclipse. I am very new to web development. any help will be appreciated.
Thanks in advance.
Servlet Code:
#WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name="";
String pass="";
name=request.getParameter("param1");
pass=request.getParameter("param2");
System.out.println("Name :" +name+"PAss :"+pass);
if (name!=null && pass!=null){
List<User> please = DataAccessUtil.getByEmail(name, pass);
if (please!=null)
{
int count = please.size();
System.out.println("Record Found : " + count);
if(!(count==0))
{
Iterator<User> iterator = please.iterator();
while(iterator.hasNext())
{
User object = (User) iterator.next();
String email = object.getEmail();
HttpSession session = request.getSession();
session.setMaxInactiveInterval(60);
session.setAttribute("email", email);
}
RequestDispatcher r= request.getRequestDispatcher("/AboutUs.html");
r.forward(request, response);
log("please");
}
else{
RequestDispatcher rd= request.getRequestDispatcher("/DR.html");
rd.forward(request, response);
log("please2");
}
}
}
else{
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
We have tasks in java web-app that take a long time in completing and before the time the task completes the request times out and page cannot be displayed happens. We are think of setting a async redirection servlet that acts as a front-controller redirecting the request to the appropriate action classes and while the request is being served the servlet keeps sending a heartbeat every minute or so, until the request is completed by the corresponding action classes. Has anybody implemented something similar using asynchronous servlet 3.0? Also is this possible? I understand that this is similar to server push. Thanks for guidance.
yes this kind of functionality you can achive by use of
asynchronous servlet 3.0.it basically works like push
notification and also give you respose continously with
out making request here i have one code that i share with
this code may help for you to make async request.
this example check live users
#WebServlet(urlPatterns = { "/checkliveuser" }, asyncSupported = true)
public class CheckLiveUser extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Queue<AsyncContext> queue = new ConcurrentLinkedQueue();
private static final BlockingQueue<String> messageQueue = new LinkedBlockingQueue();
private static final String BEGIN_SCRIPT_TAG = "<script type='text/javascript'>\n";
private static final String END_SCRIPT_TAG = "</script>\n";
private Thread notifierThread = null;
#Override
public void init(ServletConfig config) throws ServletException {
ServletContext context = config.getServletContext();
Set<String> users = new HashSet<String>();
Map<String, String> page = new HashMap<String, String>();
context.setAttribute("page", page);
context.setAttribute("messageQueue", messageQueue);
Runnable notifierRunnable = new Runnable() {
public void run() {
boolean done = false;
while (!done) {
System.out.println("in thread");
String cMessage = null;
try {
cMessage = BEGIN_SCRIPT_TAG + toJsonp("<b>Live User:", messageQueue.take())
+ END_SCRIPT_TAG;
for (AsyncContext ac : queue) {
try {
PrintWriter acWriter = ac.getResponse()
.getWriter();
acWriter.println(cMessage);
acWriter.flush();
} catch (IOException ex) {
System.out.println(ex);
queue.remove(ac);
}
}
} catch (InterruptedException iex) {
done = true;
System.out.println(iex);
}
}
}
};
notifierThread = new Thread(notifierRunnable);
notifierThread.start();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
final AsyncContext ac = request.startAsync();
ac.setTimeout(10 * 60 * 1000 * 1000);
ac.addListener(new AsyncListener() {
public void onComplete(AsyncEvent event) throws IOException {
queue.remove(ac);
System.out.println("on complete");
}
public void onTimeout(AsyncEvent event) throws IOException {
queue.remove(ac);
System.out.println("on timeout");
}
public void onError(AsyncEvent event) throws IOException {
queue.remove(ac);
System.out.println("on error");
}
public void onStartAsync(AsyncEvent event) throws IOException {
System.out.println("on startup");
}
});
queue.add(ac);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
ServletContext context = request.getServletContext();
HttpSession session = request.getSession();
Map<String, String> logins = (Map<String, String>) context
.getAttribute("page");
if (request.getParameter("action") != null
&& !request.getParameter("action").isEmpty()) {
if (request.getParameter("action").equalsIgnoreCase("logout")) {
logins.remove(request.getSession().getId());
request.getSession().invalidate();
}
}
String name = request.getParameter("loginID");
if (name != null) {
session.setAttribute("user", name);
session.setAttribute("jsessionId", session.getId());
logins.put(session.getId(), name);
}
String html = "";
for (Map.Entry<String, String> entry : logins.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
html += entry.getValue() + "<br>";
}
String cMessage = BEGIN_SCRIPT_TAG + toJsonp("<b>Live User:", html)
+ END_SCRIPT_TAG;
notify(cMessage);
response.getWriter().println("success");
if (request.getParameter("action") != null
&& !request.getParameter("action").isEmpty()) {
if (request.getParameter("action").equalsIgnoreCase("logout"))
response.sendRedirect("login.jsp");
} else {
response.sendRedirect("welcome.jsp");
}
}
#Override
public void destroy() {
queue.clear();
notifierThread.interrupt();
}
private void notify(String cMessage) throws IOException {
try {
messageQueue.put(cMessage);
} catch (Exception ex) {
IOException t = new IOException();
t.initCause(ex);
throw t;
}
}
private String escape(String orig) {
StringBuffer buffer = new StringBuffer(orig.length());
for (int i = 0; i < orig.length(); i++) {
char c = orig.charAt(i);
switch (c) {
case '\b':
buffer.append("\\b");
break;
case '\f':
buffer.append("\\f");
break;
case '\n':
buffer.append("<br />");
break;
case '\r':
// ignore
break;
case '\t':
buffer.append("\\t");
break;
case '\'':
buffer.append("\\'");
break;
case '\"':
buffer.append("\\\"");
break;
case '\\':
buffer.append("\\\\");
break;
case '<':
buffer.append("<");
break;
case '>':
buffer.append(">");
break;
case '&':
buffer.append("&");
break;
default:
buffer.append(c);
}
}
return buffer.toString();
}
private String toJsonp(String name, String message) {
return "window.parent.app.update({ name: \"" + escape(name)
+ "\", message: \"" + escape(message) + "\" });\n";
}