Call doGet in the Init of a servlet?
Hello
Please could you show through the code. I think there is something wrong with the init. If I run the servlet, it don't show a thing. It only displays: Site can't not be shown.
The doGet and also the dopost is not executed. Must I call in the doPost in the init(). And when yes how?
Thanks a lot!
Sandra Frei
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Properties;
public class update42 extends HttpServlet {
Connection con = null;
public void init() {//throws ServletException {
String url = "jdbc:DBF:/sys:copal/copal_data/data/gesch/data/stamm";
try {
//Register the JDBC driver
Class.forName("zyh.sql.dbf.DBFDriver");//.newInstance();
con = DriverManager.getConnection(url, "fre","sandy66");
catch( Exception e ) {
e.printStackTrace();
}//end catch
}//end init()
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("in do get");
//connecting to the Database
Statement stmt = null;
ResultSet rs = null;
PreparedStatement ps = null;
try
stmt = con.createStatement();
catch (SQLException e) {e.getNextException();}
// displaying records
try
rs = stmt.executeQuery("SELECT Random, Nsa, Bzng, Bzn2, Tart, Meeh, Fstat, Nzn FROM part");
catch (SQLException e) {e.getNextException();}
try
while(rs.next()) {
out.print("<form action=\"");
out.print( req.getRequestURI() );
out.print("\" method=\"post\">");
out.print("<input type=\"text\""); //hidden
out.print(" name=\"Random\" size=\"15\" value=\"");//without 15
out.print( rs.getObject(1).toString() );
out.print("\">");
out.print("<input type=\"text\"");
out.print(" name=\"Nsa\" size=\"15\" value=\"");
out.print( rs.getObject(2).toString() );
out.print("\">");
out.print("<input type=\"text\"");
out.print(" name=\"Bzng\" size=\"25\" value=\"");
out.print( rs.getObject(3).toString() );
out.print("\">");
out.print("<input type=\"text\"");
out.print(" name=\"Bzn2\" size=\"25\" value=\"");
out.print( rs.getObject(4).toString() );
out.print("\">");
out.print("<input type=\"text\"");
out.print(" name=\"Tart\" size=\"6\" value=\"");
out.print( rs.getObject(5).toString() );
out.print("\">");
out.print("<input type=\"text\"");
out.print(" name=\"Meeh\" size=\"6\" value=\"");
out.print( rs.getObject(6).toString() );
out.print("\">");
out.print("<input type=\"text\"");
out.print(" name=\"Fstat\" size=\"6\" value=\"");
out.print( rs.getObject(7).toString() );
out.print("\">");
out.print("<input type=\"text\"");
out.print(" name=\"Nzn\" size=\"15\" value=\"");
out.print( rs.getObject(8).toString() );
out.print("\">");
out.print(" <input type=\"submit\"");
out.print(" value=\" \">");
out.print(" Update<br>");
out.print("</form>");
catch (SQLException e) {e.getNextException();}
try
if(rs != null)
rs.close();
if(stmt != null)
stmt.close();
catch (SQLException e) {
e.printStackTrace();
out.print("</pre></code>");
out.print("<p\"><a href=\"");
out.print( req.getRequestURI() );
out.print("\">Back</a></p>");
out.print("</body></html>");
out.close();
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("<html><body>");
out.print("<code><pre>");
out.print("<table border=1>");
out.print("<tr>");
out.print("<td><font color=green>Artikelnr</font></td>");
out.print("<td><font color=green>Bezeichnung</font></td>");
out.print("<td><font color=green>Zusatzbezeichnung</font></td>");
out.print("<td><font color=green>Art</font></td>");
out.print("<td><font color=green>ME</font></td>");
out.print("<td><font color=green>Stat</font></td>");
out.print("<td><font color=green>Spezifikation</font></td>");
out.print("</tr>");
// receiving parameters
String Bzn2 = req.getParameter("Bzn2").trim();
String Meeh= req.getParameter("Meeh").trim();
String Pk = req.getParameter("Random").trim();
boolean proceed = false;
Statement stmt = null;
Statement stmt1 = null;
ResultSet rs = null;
try {
String sql;
sql = "UPDATE part SET Bzn2 = " + "'" + Bzn2 + "'" + " WHERE Random LIKE " + "'" + Pk + "'";
stmt1 = con.createStatement();
out.print(sql);
out.print(Bzn2 + Meeh + Pk);
stmt1.executeUpdate(sql);
// displaying records
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM part");
while(rs.next())
out.print("<tr>");
out.print("<td>"+ rs.getObject(1).toString()+ "</td>");
out.print("<td>"+ rs.getObject(2).toString()+ "</td>");
out.print("<td>"+ rs.getObject(3).toString()+ "</td>");
out.print("<td>"+ rs.getObject(4).toString()+ "</td>");
out.print("<td>"+ rs.getObject(5).toString()+ "</td>");
out.print("<td>"+ rs.getObject(6).toString()+ "</td>");
out.print("<td>"+ rs.getObject(7).toString()+ "</td>");
out.print("</tr>");
out.print("</table>");
catch (Exception e)
out.print(e.getMessage());
e.printStackTrace();
try
if(rs != null)
rs.close();
if(stmt != null)
stmt.close();
if(stmt1 != null)
stmt1.close();
catch (SQLException e) {e.getNextException();}
out.print("</pre></code>");
out.print("<p\"><a href=\"");
out.print( req.getRequestURI() );
out.print("\">Back</a></p>");
out.print("</body></html>");
out.close();
public void destroy() {
try {
//Close the connection to the database
con.close();
} catch( Exception e ) {
e.printStackTrace();
}
It won't get shown unless you make a call to the servlet from (e.g.) a web browser referencing it. And no - don't call doPost() or doGet() from the init() method. You might be lucky, and it might work, but it's inherently unsafe. Servlet engines will not normally call these methods until the servlet is properly initialised.
And BTW, there is no guarantee that init() will be called until the first call to the servlet, unless you specify load on startup to the servlet engine.
Your best bet is simply to type the URL of your servlet into your web browser. That will call doGet(). To call doPost(), you'll have to write a little HTML page with a form with method="post" and action=the name of your servlet.
Robin
Similar Messages
-
Hi, everyone..
I wonder why we call super.init(config) in init method of servlet... If i dont call it ; when i try to get servletcontext in service method it throws java.lang.NullPointerException...when we call super.init() , what is happening behind the scene? If anybody has a technical explanation for my question , i will be very pleased...
THX FOR YOUR FUTURE REPLIES IN ADVANCE....I am sorry about the uppercases and i dont want to seem smart on java forums... Anyway, m8 this is the thing that i know... i meant; for instance when we override doGet or doPost method ; we dont need to override init method; but the server loads the servlet and we can get the context of the servlet in these methods easily by calling getServletContext() method; however when we want to call service method implicitly by jndi, servlet needs to be loaded and init method must call its parent...(i also write down in web.xml <load-on-startup>.... for that servlet).
thx for your replies in advance.... -
Hello
Please could you show through the code. I think there is something wrong with the init. If I run the servlet, it don't show a thing. It only displays: Site can't not be shown.
The doGet and also the dopost is not executed. Must I call in the doPost in the init(). And when yes how?
Thanks a lot!
Sandra Frei
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Properties;
public class update42 extends HttpServlet {
Connection con = null;
public void init() {//throws ServletException {
String url = "jdbc:DBF:/sys:copal/copal_data/data/gesch/data/stamm";
try {
//Register the JDBC driver
Class.forName("zyh.sql.dbf.DBFDriver");//.newInstance();
con = DriverManager.getConnection(url, "fre","sandy66");
catch( Exception e ) {
e.printStackTrace();
}//end catch
}//end init()
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("in do get");
//connecting to the Database
Statement stmt = null;
ResultSet rs = null;
PreparedStatement ps = null;
try
stmt = con.createStatement();
catch (SQLException e) {e.getNextException();}
// displaying records
try
rs = stmt.executeQuery("SELECT Random, Nsa, Bzng, Bzn2, Tart, Meeh, Fstat, Nzn FROM part");
catch (SQLException e) {e.getNextException();}
try
while(rs.next()) {
out.print("<form action=\"");
out.print( req.getRequestURI() );
out.print("\" method=\"post\">");
out.print("<input type=\"text\""); //hidden
out.print(" name=\"Random\" size=\"15\" value=\"");//without 15
out.print( rs.getObject(1).toString() );
out.print("\">");
out.print("<input type=\"text\"");
out.print(" name=\"Nsa\" size=\"15\" value=\"");
out.print( rs.getObject(2).toString() );
out.print("\">");
out.print("<input type=\"text\"");
out.print(" name=\"Bzng\" size=\"25\" value=\"");
out.print( rs.getObject(3).toString() );
out.print("\">");
out.print("<input type=\"text\"");
out.print(" name=\"Bzn2\" size=\"25\" value=\"");
out.print( rs.getObject(4).toString() );
out.print("\">");
out.print("<input type=\"text\"");
out.print(" name=\"Tart\" size=\"6\" value=\"");
out.print( rs.getObject(5).toString() );
out.print("\">");
out.print("<input type=\"text\"");
out.print(" name=\"Meeh\" size=\"6\" value=\"");
out.print( rs.getObject(6).toString() );
out.print("\">");
out.print("<input type=\"text\"");
out.print(" name=\"Fstat\" size=\"6\" value=\"");
out.print( rs.getObject(7).toString() );
out.print("\">");
out.print("<input type=\"text\"");
out.print(" name=\"Nzn\" size=\"15\" value=\"");
out.print( rs.getObject(8).toString() );
out.print("\">");
out.print(" <input type=\"submit\"");
out.print(" value=\" \">");
out.print(" Update<br>");
out.print("</form>");
catch (SQLException e) {e.getNextException();}
try
if(rs != null)
rs.close();
if(stmt != null)
stmt.close();
catch (SQLException e) {
e.printStackTrace();
out.print("</pre></code>");
out.print("<p\"><a href=\"");
out.print( req.getRequestURI() );
out.print("\">Back</a></p>");
out.print("</body></html>");
out.close();
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("<html><body>");
out.print("<code><pre>");
out.print("<table border=1>");
out.print("<tr>");
out.print("<td><font color=green>Artikelnr</font></td>");
out.print("<td><font color=green>Bezeichnung</font></td>");
out.print("<td><font color=green>Zusatzbezeichnung</font></td>");
out.print("<td><font color=green>Art</font></td>");
out.print("<td><font color=green>ME</font></td>");
out.print("<td><font color=green>Stat</font></td>");
out.print("<td><font color=green>Spezifikation</font></td>");
out.print("</tr>");
// receiving parameters
String Bzn2 = req.getParameter("Bzn2").trim();
String Meeh= req.getParameter("Meeh").trim();
String Pk = req.getParameter("Random").trim();
boolean proceed = false;
Statement stmt = null;
Statement stmt1 = null;
ResultSet rs = null;
try {
String sql;
sql = "UPDATE part SET Bzn2 = " + "'" + Bzn2 + "'" + " WHERE Random LIKE " + "'" + Pk + "'";
stmt1 = con.createStatement();
out.print(sql);
out.print(Bzn2 + Meeh + Pk);
stmt1.executeUpdate(sql);
// displaying records
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM part");
while(rs.next())
out.print("<tr>");
out.print("<td>"+ rs.getObject(1).toString()+ "</td>");
out.print("<td>"+ rs.getObject(2).toString()+ "</td>");
out.print("<td>"+ rs.getObject(3).toString()+ "</td>");
out.print("<td>"+ rs.getObject(4).toString()+ "</td>");
out.print("<td>"+ rs.getObject(5).toString()+ "</td>");
out.print("<td>"+ rs.getObject(6).toString()+ "</td>");
out.print("<td>"+ rs.getObject(7).toString()+ "</td>");
out.print("</tr>");
out.print("</table>");
catch (Exception e)
out.print(e.getMessage());
e.printStackTrace();
try
if(rs != null)
rs.close();
if(stmt != null)
stmt.close();
if(stmt1 != null)
stmt1.close();
catch (SQLException e) {e.getNextException();}
out.print("</pre></code>");
out.print("<p\"><a href=\"");
out.print( req.getRequestURI() );
out.print("\">Back</a></p>");
out.print("</body></html>");
out.close();
public void destroy() {
try {
//Close the connection to the database
con.close();
} catch( Exception e ) {
e.printStackTrace();
}No, do NOT call doGet() or doPost() from the init() method. Your problem is something else, but you have not provided enough information to figure out what, and there are several possibilites. "Site can't not be shown"... I doubt that is the exact message you are getting.
-
EJB to be used in the init of the servlet
Hi,
We are using Weblogic6.1 SP2.We have a bean that is called in the init of the
servlet which is executed when the server starts up. The EJB is called properly
when used in system having already deployed EJBs(ie when it has entries in config.xml).
But if we put the EJB jars in the application directory and without putting the
entries in config.xml(which is the probable deployment scenario), the EJB to be
called on startup is not deployed and we get an error saying unable to resolve
jndi name. Can we control the sequence of events in Weblogic ie. forcing the EJB
to be deployed first before calling it in init of servlet. Any pointers will be
helpful.
Thanks in advance,
Rajiv Nanda.No we are still doing the development.
"Guido Diener" <[email protected]> wrote:
Is your wls running in production mode?
Guido
"rajiv" <[email protected]> schrieb im Newsbeitrag
news:[email protected]..
Hi,
We are using Weblogic6.1 SP2.We have a bean that is called in theinit
of the
servlet which is executed when the server starts up. The EJB is calledproperly
when used in system having already deployed EJBs(ie when it has entriesin
config.xml).
But if we put the EJB jars in the application directory and withoutputting the
entries in config.xml(which is the probable deployment scenario), theEJB
to be
called on startup is not deployed and we get an error saying unableto
resolve
jndi name. Can we control the sequence of events in Weblogic ie. forcingthe EJB
to be deployed first before calling it in init of servlet. Any pointerswill be
helpful.
Thanks in advance,
Rajiv Nanda. -
Who calls doget() method of servlet
hello all,
i have typical customized webserver.
the problem i have with that is when i configure it with IP address and when i send a request through browser using HOST NAME ,its not recognizing.
the same happens vice versa
that is : set up host name in the http server, and when try a request through IP Address using a web browser.
can any body clear me who calls the doGet() method of servlet. if it is USER AGENT of web browser, is there any operation executes between
USER AGENT - DoGet() method of servlet?
regards
R
Message was edited by:
LoveOpensourceThe servlet is on the server, the browser is on the client, so, do it think it possible (unless the browser is written in Java and does it's browsing with RMI, which is patently absurd) that the browser call doGet()?
It is rather obvious, that the browser sends an HTTP request to the Application Container (or a web server such as apache which then uses some module to communicate with the Application Container, but the end effect is the same), and that Application Container calls the doGet() method.
Edit: And man am I slow and "wordy". -
When the init mehtod is called
When the init mehtod is called?
while running the server or by running the servlet program.
When u create a enterprice project in WSAD you will have JavaResource and Web Content in your project.
Say i have 10 servlet program in my JavaResource.
When running the JavaResource by right cliking and run on this server which servlet will run first and when will the init method is called.
** (I am using Websphere)**_If you have gone thorugh the servlet life cycle methods, you could have come to know when init method is called.
Servlet�s life cycle is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps. If an instance of the servlet does not exist, the Web container
a. Loads the servlet class.
b. Creates an instance of the servlet class.
c. Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet. 2. Invokes the service method, passing a request and response object.
If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method.
I think now you can understand when init method is called. -
All,
Any help on this would be appreciated. We have a servlet that calls a native method
and we load the native library in the servlet's 'init()' method so the servlet
gets loaded only once. However, periodically, I get the following error:
java.lang.UnsatisfiedLinkError : Native Library /opt/shared2/weblogic/myserver/servletclasses/twtc/servlet/toc/toclib.so
already loaded in another classloader
It seems to bring down weblogic when this happens.
Why does this happen?
Is there a way around this?
As a test, I called System.load() 10 times outside of the init function with the
same library and it did not fail once but it does periodically in the init() function
of my servlet, which implies that the init function is being called more than
once.Like what the error message says, you can only load a native library once per ClassLoader per VM.
You can test this by constructing two ClassLoaders and loading the same library.
The reason why a servlet will be constructed by different classloaders with a VM session is if:
1) the servlet is reloaded (hot-deployed)
2) the servlet belongs in more than one ear, since each ear has its own classloader.
Gene
"Michael" <[email protected]> wrote in message news:[email protected]..
>
All,
Any help on this would be appreciated. We have a servlet that calls a native method
and we load the native library in the servlet's 'init()' method so the servlet
gets loaded only once. However, periodically, I get the following error:
java.lang.UnsatisfiedLinkError : Native Library/opt/shared2/weblogic/myserver/servletclasses/twtc/servlet/toc/toclib.so
already loaded in another classloader
It seems to bring down weblogic when this happens.
Why does this happen?
Is there a way around this?
As a test, I called System.load() 10 times outside of the init function with the
same library and it did not fail once but it does periodically in the init() function
of my servlet, which implies that the init function is being called more than
once. -
How can I display the HTML page from servlet which is called by an applet
How can I display the HTML page from servlet which is called by an
applet using the doPost method. If I print the response i can able to see the html document. How I can display it in the browser.
I am calling my struts action class from the applet. I want to show the response in the same browser.
Code samples will be appreciated.hi
I got one way for this .
call a javascript in showDocument() to submit the form -
Can an applet call one of the methods of servlet??
hi everyone...
i m very new servlet and applet programming and i have come accross a problem....
i m using a applet which establishes connection with the servlet(residing on server)..i want to use few of the methods of the servlet....
now is it possible tfor me to call the methods of this servlet using its object.???
please help me..
thanx in advancefirst of all thanx a lot for the reply...
but i wanted to know can an applet call any other
function of servlet other than get and post....as i
hacve defined some more functions in servlet..
please reply...I did this a while back (2003/4?) and unless it's changed you cannot do it directly, it must be GETor POST, then you could just use conditional logic to invoke another method. -
Calling doGet() from in the doPost() method.
What is the conditions we have to cheak to call doGet() method from doPost().
doGet() using for request.getParameter(). the exact story is u want to get some data form html (or) data bases. it is usefu
-
DoFilter() method is being called only at the second request
Hi,
I have implemented a simple Filter class
Here is the code
public class BasicFilter implements Filter
FilterConfig config;
public void init(FilterConfig config)
System.out.println("Filter Initialised");
this.config = config;
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws ServletException,
IOException
System.out.println("In The doFilter() method");
ServletContext sc = config.getServletContext();
sc.setAttribute("Hello","Hell");
chain.doFilter(request,response);
public void destroy()
System.out.println("In the destroy method");
and a simple servlet
public class FilteredServlet extends HttpServlet
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Filter Demo</TITLE></HEAD>");
out.println("<BODY>");
out.println(getServletContext().getAttribute("Hello"));
out.println("</BODY>");
out.println("</HTML>");
Now when i start the server (Tomcat 4.0) i find that the filter's init() method is being called which is fine. But when i request the servlet (FilteredServlet) the doFilter() method is not called and only when i "refresh" it or call it a second time that the doFilter() method is actually called. What could be the reason for this.
Help will be greatly appreciated.
Thank You,
Phani KanuriHi jleech,
Thanks for the reply. But deleting all the temporary internet files as also the history files does not seem to have an effect. the doFilter is being called only at the second request. or did i miss anything??
Please help. unable to complete the assignment because of this.
Thank You,
Phani Kanuri -
Short Dump Error in deleting the Init request
Hi Gurus,
i am loading master data from sap r3 by init update.
now due to some requirement i have to delete the init request , but when i try to delete the request
it goes to short dump and gives the error message as
Runtime Errors MESSAGE_TYPE_X
Date and Time 01/05/2009 01:54:15
Short text
The current application triggered a termination with a short du
What happened?
The current application program detected a situation which real
should not occur. Therefore, a termination with a short dump wa
triggered on purpose by the key word MESSAGE (type X).
Error analysis
Short text of error message:
Error when opening an RFC connection
Long text of error message:
Technical information about the message:
Message class....... "RSAR"
Number.............. 051
Variable 1.......... "Error when opening an RFC connection"
Variable 2.......... " "
Variable 3.......... " "
Variable 4.......... " "
Last error logged in SAP kernel
Component............ "SAP-Gateway"
Place................ "SAP-Gateway on host sapdev / sapgw00"
Version.............. 2
Error code........... 631
Error text........... "max no of gateways exceeded (100)"
Description.......... " "
System call.......... " "
Module............... "gwxxrd.c"
Line................. 8438
The error reported by the operating system is:
Error number..... " "
Error text....... " "
Trigger Location of Runtime Error
Program SAPLRSSM
Include LRSSMF03
Row 1,627
Module type (FORM)
Module Name DEL_SOURCE_SYSTEM_INIT
1624 communication_failure = 1 message l_msg_text
1625 system_failure = 2 message l_msg_text.
1626 if sy-subrc <> 0.
>>>>> message x051(rsar) with l_msg_text(50) l_msg_text+50(50) '' ''.
1628 endif.
Please help me on this as untill it will not be deleted, I will be unable to load the data.
suitable answer will get Full points.
Thanks.Hi Saurabh,
PLEase go through these notes:
https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes/sdn_oss_bc_cst/~form/handler%7b5f4150503d3030323030363832353030303030303031393732265f4556454e543d444953504c4159265f4e4e554d3d383837393039%7d
https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes/sdn_oss_bc_cst/~form/handler%7b5f4150503d3030323030363832353030303030303031393732265f4556454e543d444953504c4159265f4e4e554d3d383934313030%7d
https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes/sdn_oss_bc_cst/~form/handler%7b5f4150503d3030323030363832353030303030303031393732265f4556454e543d444953504c4159265f4e4e554d3d393738303738%7d -
How to hide the parameters passed into servlet or make it read only
Hi,
I am calling a servlet to downlaod files, using
<a href="../servlet/DownloadFile?directory=<%=attachmentPath%>&fileName=<%=fileName%>">But this will display all the paramters passed , of course as I am using hyper link. However I can not use
<form> to call the servlet because otherwise I got nested form anyway.
So the users would be able to change the directory and file names to download files I do not like them to download. Somebody would suggest hardcode the directory and filename, but these two parameters are dynamic, so I have to pass them into the servlet everytime I call it.
Any advice to disable the users to change or even view the two parameters on the address bar?
Thanks
</a>Here some code snippets to give you an idea of what I do.
Let's say you want to retrieve a file from your server, and you need to pass the full directory path info in your URL. You might have code as follows:
String fileName = "/server/SomeUltraSecretHiddenDirectory/ImportantSecretFile.doc";
Click <a href="/fileservlet?fileName=<%=URLEncoder.encode(fileName)%>">HERE</a> to download file.Using the above code, ANYONE can retrieve this file if they know the URL. Also, they could try to change the URL paths to find other files. In other words, it's NOT SECURE.
Now, try it this way (all exception handling is left out):
private static final byte[] salt = { (byte)0xd4, (byte)0xa3, (byte)0xff, (byte)0x9e,
(byte)0x12, (byte)0xc7, (byte)0xd0, (byte)0x84 };
String fileName = "/server/SomeUltraSecretHiddenDirectory/ImportantSecretFile.doc";
base64Encoder = new BASE64Encoder();
base64Decoder = new BASE64Decoder();
// get key object
SecretKey key = null;
PBEKeySpec keySpec = new PBEKeySpec("somesecretkeystring");
SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
key = kf.generateSecret(keySpec);
// get parameter spec
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 1000);
// create cipher
Cipher c = Cipher.getInstance("PBEWithMD5AndDES");
c.init(Cipher.ENCRYPT_MODE, key, paramSpec);
// take string and get encrypt it (base-64 encode it to get rid of non-printable characters
byte[] aResult = c.doFinal(fileName.getBytes("UTF-8"));
String strResult = base64Encoder.encodeBuffer(aResult);
// print the link
Click <a href="/fileservlet?fileName=<%=URLEncoder.encode(strResult)%>">HERE</a> to download file.
// on the server side, do the following to decrypt the link
String encryptedFileName = request.getParameter("fileName");
// create decryption cipher (i'm skipping a lot of the init code this time - see above for code example)
Cipher c = Cipher.getInstance("PBEWithMD5AndDES");
c.init(Cipher.DECRYPT_MODE, key, paramSpec);
// decrypt string
byte[] aResult = c.doFinal(base64Decoder.decodeBuffer(encryptedFileName));
String strResult = new String(aResult, "UTF-8");Now you have the decrypted String. Your link will be unreadable and unbreakable. 100% safe as long as your key password is safe. I hope that gives you an idea of what you can do with cryptography!
A few notes:
- Most of the above code is in separate methods that can be easily reused (especially encrypt() and decrypt())
- All exception handling has been left out
- The above code was patched together from memory, so don't expect it to work as is (that's my disclaimer :)
- You'll need the JCE libraries to use this functionality.
- For REALLY sensitive data (such as passwords), make sure you use one-way encryption (hashes) if you don't ever need to decrypt it again.
Michael -
Init() method in Servlet
Hi All,
I am new in Servlet.So this question might sound silly to everyone.
As per the init() method takes a ServletConfig object as a parameter. This reference should be stored in a member variable so that it can be used later.
My doubt is why do we need to store the reference?What if you need to access the information later - init is only called once per Servlet. It is stored so you can call getServletConfig() in your Servlet and access any init params that you defined in web.xml. You do not need to store it though - GenericServlet (or HttpServlet?) will take care of it - although if you override the init method make sure you call super.init(config).
m -
How to get the value from a servlet?
Hello guys:
how can i get the value from a servlet on my jsp page,for example return a boolean variable from a servlet
which API to use?
thanksHi
There is no specific API for this, call the method of the servlet which returns the required value in your JSP page.
Thanks
Swaraj
Maybe you are looking for
-
Use of zero size arrays?
Hi In java i can initialize an array of 0 size, but where can i use it, and how can i use it. Please suggest!
-
I cannot compile Servlet files on my WinXP environment. my servlet.jar file is located at c:\tomcat\jakarta-tomcat-3.3.1\common\lib\servlet.jar what shall I do? The error messages are only for servlet portion of code?
-
Populating a Drop down menu JSP form
How to go about populating a drop-down form from Oracle Database using JSP? I have the connecting to the Oracle Database running. I also can query forms, but i can't create a drop-down menu form.
-
Hi all, I am totally new to informatica and have a task of extracting data to SAP BI. Please help me with the useful links and tell me where to start. Also, I would like to have basic understanding of informatica. Thanks Diksha.
-
Hi I try to call a webservice in netbeans 6. I have "linket" to the webservice see: [http://www.vels.dk/tmp/netbeans.jpg|http://www.vels.dk/tmp/netbeans.jpg] but how do I call the webservice...? I have tryed something like: org.me.calculator.Calculat