I would like to do the servlet program for the below,"create a servlet named com.SessServlet.If you are accessing the servlet in a new browser then
for the first time it should display ‘Welcome, Newcomer’. When you refresh the same page it should display‘Welcome Back. You are visiting the page for <no of times you have refreshed the page>’."
`package com.SessServlet122;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessServlet extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
res.setContentType("text/html");
int i;
PrintWriter pw=res.getWriter();
HttpSession hs=req.getSession();
i=0;
if(hs.isNew())
{
pw.println("Hello:::"+i);
}
else
{ i++;
pw.println("Welcome Back:Ur entry count is::::"+i);
}
pw.close();
}
}`
But this code is not working properly. How to solve this? Thanks in advance.
You should store that counter as a sessionVariable, that way you will get it work.
You need this line after your pw.close(); call:
hs.setAttribute("counter", i);
Also, the initialization of your counter i should look like this:
Integer i = (Integer)hs.getAttribute("counter");
if (i == null)
i = 0;
Hint:
Create a Servlet
From service() method retrieve session and set an attribute in session if its there else set ans display appropriate message
On jsp use JSTL to display the counter, for example : if the attribute set was hitCount then on jsp use ${hitCount}
Related
I'd like to make one text for multiple html files, something like greating. Let's say greating is:
"Hello, if you have any questions please conatact me."
What I want is to recall that text on every html page. And later if I change it, the change would appear on all the html pages.
I am weak on java, but I think I need to create some javascript and recall the text with div class function, like the facebook button is made.
P.S. Facebook button recall:
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data- layout="standard" data-action="like" data-show-faces="true" data-share="true">
with javascript you can change the content of a tag with html() function, or you could include the resource, i guess it depends on the technology being used
In the simplest form, you can create a function in your javascript master copy and make a document.write call. You would need to call that script file on every page.
function greetingMessage() {
document.write('your message);
};
Then
call greetingMessage();
you can also put the javascript in a master file and then have the div in each HTML page:
function greetingMessage(){
document.getElementById('Message').innerHTML = 'Your Message';
};
HTML:
<body onload="greetingMessage();">
<div id="Message" style="color:red;"></div>
If you are using JSP's or Servlets you can have a resource/properties file that contains many Strings being used throughout your application. The properties file would contain key=value pairs. You could then simply reference a particular key in the properties file, for instance:
greeting=Hello, if you have any questions please contact me
The key is "greeting", the value is "Hello, if you have any questions please contact me"
To read in the properties file you would use the Properties class like so:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class MyWebPage extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
{
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.print("<html><head></head><body><div class=\"someclass\">" +
getGreeting() + "</div>"
"</body></html>"
);
}
public String getGreeting()
{
String greeting = "";
try{
Properties prop = new Properties();
InputStream input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
greeting = prop.getProperty("greeting");
input.close();
}
catch(IOException ioe){ioe.printStackTrace();}
finally{
if (input != null)
{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return greeting;
}
}
The same sort of thing can be effectively used in Java Server Pages. Hope this helps.
i created a jsp page that calls another jsp page that show an image took from a blob field in my mysql db:
<img src="blob.jsp">
it works. But, somewhere in this forum i read that this is not the right way to do it. I should, instead, using a servlet this way:
<img src="servlet_name">
I created a servlet, but it doesent show me the image it shows me this
ÿØÿàJFIFHHÿí$Photoshop 3.08BIMí ResolutionHH8BIM FX Global Lighting Anglex8BIMFX Global Altitude8BIMó Print Flags 8BIM Copyright Flag8BIM'Japanese Print Flags 8BIMõColor Halftone SettingsH/fflff/ff¡™š2Z5-8BIMøColor Transfer Settingspÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿè8BIM Layer State8BIM Layer Groups8BIMGuides##8BIM URL overrides8BIMSlicesuƒD Untitled-1Dƒ8BIMICC Untagged Flag
This is my simple servlet
package Jeans;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/BlobDisplay")
public class BlobDisplay extends HttpServlet {
private static final long serialVersionUID = 1L;
GestioneDB gestioneDB ;
public BlobDisplay() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Blob image = null;
byte[ ] imgData = null ;
String query = null;
query = request.getParameter(query);
gestioneDB = new GestioneDB();
ResultSet rs = gestioneDB.rs("select immagine_principale from news where id ='217'");
try{
if (rs.next()) {
image = rs.getBlob("immagine_principale");
imgData = image.getBytes(1,(int)image.length());
response.setContentType("image/jpg");
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();
}
}
catch(Exception e){}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
Here is a debugging hint for now.
JSPs are just "inside out" servlets and they are translated to servlets by the container. Since your JSP works and your servlet doesn't, why don't you check out (and post) the generated servlet. If you are using tomcat, it would be in a file called blob__jsp.java deep in the work directory. Then compare the calls and set up of your servlet and the generated servlet.
(My first guess is the content type, but you seem to be setting that)
I am trying a slideshow using a servlet . Though the photos are loaded but is not a slideshow. What i get is a series of images.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class PhotoCollection extends HttpServlet{
private String array[] = {"first.jpg","second.jpg","third.jpg","fourth.jpg"};
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html>");
writer.println("<head>");
writer.println("<title>");
writer.println("SlideShow");
writer.println("</title>");
writer.println("</head>");
writer.println("<body>");
writer.println("<table>");
writer.println("<tr>");
try {
for(int i=0;i<=3;i++) {
writer.println("<td>");
writer.println("<img src=" + array[i] + " height=100 width=110>");
writer.println("</td>");
Thread.sleep(1000);
}
}catch(Exception exc) {
writer.println("<br />" + exc + "<br />");
}
writer.println("</tr>");
writer.println("</table>");
writer.println("</body>");
writer.println("</html>");
}
}
I have made the thread sleep 1 second but that doesn't affect the loading. How can i do a slideshow using it ? What changes do i have to make in the above servlet ?
You should use jQuery plugins for displaying it on browser pretty, use servlet just to serve image
Note : adding sleep in doGet doesn't make sense here, out put is sent once the method is executed so it would pause the execution
In my code..i have retrieved the value of input(text type) from a jsp page in a servlet using request.getParameter().
Now using these values,i have performed some calculation.
now i want to forward the calculated value (i.e. the result) as well as the operands.. i e. the retrieved value to a new jsp page. I am doing this by setting the values using request.setAttribute() and forwarding to the destined jsp page using getRequestDispatcher().forward(request,response).
But my page is not being forwarded.
package imsf;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import Service;
public class CalcPurRate extends HttpServlet {
String iname;
String cname;
String mrate;
String irate;
String disR;
String disP;
String newAdd;
String q;
int imr;
int iir;
int idR;
int idP;
String dP;
String dR;
int ina;
int iprate;
int total;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String in=request.getParameter("iname");
out.print("my name"+in);
String cn=request.getParameter("cname");
out.print("my cate"+cn);
if(request.getParameter("mrate")!=null)
{
String mr=request.getParameter("mrate");
if(!(mr.equals(null)))
{
imr=Integer.parseInt(mr);
out.print(" mrp= "+imr);
}
}
if(request.getParameter("irate")!=null)
{
String ir=request.getParameter("irate");
if(!(ir.equals(null)))
{
iir=Integer.parseInt(ir);
out.print("invoice= "+iir);
}
}
if(request.getParameter("disR")!=null)
{
out.print("disR not null");
dR=request.getParameter("disR");
if(!(dR.equals(null)))
{
out.print("disR not zero");
idR=Integer.parseInt(dR);
/*if(request.getParameter("disP")==null)
{
out.print("disP not zero");
dP=request.getParameter("disP");
if(dP.equals(null))
{
out.print("disP not zero");
iprate=((iir)-(idR));
out.print("iprate="+iprate);
}
}*/
out.print("integer dis R="+idR);
iprate=((iir)-(idR));
out.print("iprate="+iprate);
}
}
/*if(request.getParameter("disP")!=null)
{
out.print("disP not null");
dP=request.getParameter("disP");
if(!(dP.equals(null)))
{
out.print("disP value="+dP);
out.print("disP not zero");
/*if(request.getParameter("disR")==null)
{
dR=request.getParameter("disR");
if(dR.equals(null))
{
idP=Integer.parseInt(dP);
out.print("integer dis P="+idP);
iprate=((iir)-(((idP)*(iir))/100));
out.print("pur rate"+iprate);
}
}*/
//}
//}
/*if(idR!=0)
{
out.print("innn");
iprate=((iir)-(idR));
out.print("pur rate"+iprate);
}
out.print("heheh");
if(idP!=0)
{
iprate=iir-((idP*iir)/100);
out.print("vgfhg"+iprate);
}*/
if(request.getParameter("newAdd")!=null)
{
String na=request.getParameter("newAdd");
if(!(na.equals(null)))
{
ina=Integer.parseInt(na);
total=((ina)*(iprate));
out.print("total="+total);
}
}
request.setAttribute("purRate",iprate);
request.setAttribute("total",total);
//response.sendRedirect("ItemDetail.jsp");
RequestDispatcher rd=request.getRequestDispatcher("/ItemDetail.jsp");
rd.forward(request, response);
}
catch(Exception e)
{
e.getMessage();
}
}
}
processRequest() is not a method that has any meaning to an HttpServlet. Your servlet is actually doing nothing whatsoever - processRequest() will not be invoked by anything.
You should be implementing either doGet() or doPost(), and put your logic in there.
Incidentally, storing data in fields of a servlet like this is an extremely bad idea. It's not thread-safe - multiple concurrent requests will corrupt your servlet's state.
if you want to land in a new page, just use the sendRedirect() method.
by the way the details that you have provided looks correct.
try to get the parameters at the destination jsp and let us know.. it should work..
HTH
out.println("<tr><td><FORM ENCTYPE='multipart/form-data'"+
"method='POST' action='ProcessUpload' ></td>"+
"<td><INPUT TYPE='file' NAME='mptest'></td>"+
"<td><INPUT TYPE='submit' VALUE='upload'></td>"+
"</FORM></tr>");
This codes can help me upload file but the problem is after I click upload, I cant save the uploaded file in particular directory.Anyone can give some suggestion?
The code above simply outputs the HTML for an upload button. It does not do anything with any upload requests that form might start.
May I ask why you don't want to use Apache Commons FileUpload? To not use it will mean that you will need to implement RFC 1867. A lot of time and effort wasted when an implementation already exists.
You have to write another servlet (or some CGI, jsp ...etc.) to retrieve the file from the request and save it to wherever you like:
http://www.frontiernet.net/~Imaging/FileUploadServlet.html
Apache Commons FileUpload is the way to go as others suggested. If you don't want use that for any reason, you can also look at this class,
http://metatemplate.googlecode.com/svn/trunk/metatemplate/java-app-framework/tomcat-adapter/src/com/oreilly/servlet/MultipartRequest.java
This is not as robust as FileUpload but it works fine for simple file upload.
If you want to use Multipart request you need to write your processUpload servlet to handle this eg:
private String fileSavePath;
public void init(){
fileSavePath = getServletContext().getRealPath("/") + "data";
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
MultipartRequest mpr = new MultipartRequest(request, fileSavePath);
}
And I really wouldn't output pure html from a servlet as in your question - try dispatching to a jsp - even better if nothing else is required just use plain html.
The COS libary http://servlets.com/cos/ (not apache)
I second mlk's suggestion and think reading the Users Guide to Commons FileUpload will help you get started. It will handle receiving the file, but you still have to tell it "where" to store it. From your description, sounds like you want the user to choose "where" to store the file. You will have to write this portion yourself.
I hacked together a quick lister in a servlet. All the other comments are correct. Not a good idea to write html in a servlet, but this sounds like a good learning experience.
package somepackage;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DirectoryChooserServlet extends HttpServlet {
public DirectoryChooserServlet() {
super();
}
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Writer w = response.getWriter();
w.write("<html><body>");
String action = request.getParameter("action");
String directory = request.getParameter("directory");
String startDirectory = "/private";
if ("list".equals(action)) {
startDirectory = directory;
}
File dir = new File(startDirectory);
if (dir != null) {
w.write("..<br/>");
for(File f: dir.listFiles()) {
if(f.isDirectory()) {
w.write("" + f.getName() + "<br/>");
}
}
}
w.write("</body></html>");
}
}