Pages
▼
Saturday, April 20, 2013
Friday, April 19, 2013
How to debug a client side script
All we know that javascript/jquery are client side Script and only run on web browser like Mozilla Firefox.Google chrome.Safari etc.but there is no way to find bug on clientside script,we have to alert at many places to find bug.Now like sever side script we can also debug client side script ,for this web developer tool required of that browser.For exmaple Firebug in Mozilla Firefox.
Steps to add Firebug on your mozilla firefox

Steps to add Firebug on your mozilla firefox
- Press Ctrl+Shift+A

- In Search box type Firebug and click on install.if you don't find it here then you can download it from Download Firebug and when it install ,it require restart browser
- After restart you can see inspect element with firebug in Mozilla firefox by Right click

<html>
<head>
<title>index</title>
</head>
<script src="YourJavaScript.js" type="text/javascript"></script>
<script>
display function()
{
var name = document.getElementById("name").value;
alert(name);
}
</script>
<body>
<form action="#">
<label>Enter Name</label> <input type="text" id="name"> <input
id="btn" onclick="display();" type="submit">
</form>
</body>
</html>
Now It will not run .<head>
<title>index</title>
</head>
<script src="YourJavaScript.js" type="text/javascript"></script>
<script>
display function()
{
var name = document.getElementById("name").value;
alert(name);
}
</script>
<body>
<form action="#">
<label>Enter Name</label> <input type="text" id="name"> <input
id="btn" onclick="display();" type="submit">
</form>
</body>
</html>
Open console panel that show error in the script
Error Say Missing ; before statement because it assume display as token of previous block ,which is not yet close by semicolon.Now we got the idea how to fix it ,it's Syntax error function is a type and display is name of this type ,so it must be place after the type like this
Place this in coding function display()
Now correct the syntax and run it.It work fine,if we want to see what happen after that onsubmit of button where control goes,then we can debug it
Open Script panel and choose your particular script because it show html file containing script ,Jscript api and script of event .Chosse html file containing script

Now place a breakpoint by simple click on leftpane corresponding to particular line.As shown below
It time run a page, fill name in the text field and click on SubmitQuery.Page load will pause on this breakpoint,move the control one step to next line by pressing F11.

Now on place your mouse cursor on "name" and it show it's value

Click F8 to continue.It's a small example but in large program it is very helpful.If you have any doubt place a comment below
Tuesday, April 16, 2013
How to upload file using jsp using FileRenamePolicy
How to upload file from jsp?Java servlet API doesn't provide any class to handle file upload.So we have to download external library to upload file Download Jar.File uploading can be done only with doPost and by using enctype "multipart/form-data" .By default it's enctype is"application/x-www-form-urlencoded" Feature of various enctype given below
value | Description |
application/x www form urlencoded | Space of url converted to "+" symbols and special characters are converted into ASCII HEX values.All characters are encoded before sent |
mulipart/form-data | Value is required when you are using rms that have a file upload file contol(no characters are encoded) |
text/plain | Spaces are converted into "+" symbols.No specical character are encoded. |
<form name="form" method="post" enctype="multipart/form-data"action="YourController">
<input type="file" name="file" size="50" />
<input type="submit" name="Insert" value="Insert">
</form>
Coding at Controller<input type="file" name="file" size="50" />
<input type="submit" name="Insert" value="Insert">
</form>
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
if (ContextType.indexOf("multipart/form-data") >= 0) {
MultipartRequest m = new MultipartRequest(request, "yourpath");
m.getOriginalFileName("file") ;//return the name of uploaded file
}
}
MultipartRequest Constructor have if (ContextType.indexOf("multipart/form-data") >= 0) {
MultipartRequest m = new MultipartRequest(request, "yourpath");
m.getOriginalFileName("file") ;//return the name of uploaded file
}
}
MultipartRequest(HttpServletRequest request, String saveDirectory,int maxPostSize,String encoding,FileRenamePolicy policy) Source Code
request the servlet request.
- saveDirectory the directory in which to save any uploaded files.
- maxPostSize the maximum size of the POST content.
- encoding the encoding of the response, such as ISO-8859-1
- policy a pluggable file rename policy
- It automatically add number to file name
- Example sample.txt ,sample1.txt,sample2.txt and so on
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
MultipartRequest m = new MultipartRequest(request, Path, 5024 * 1024, new DefaultFileRenamePolicy());
It automatically add number to filename.MultipartRequest m = new MultipartRequest(request, Path, 5024 * 1024, new DefaultFileRenamePolicy());
But if you want to give name according to your standard then
MultipartRequest m = new MultipartRequest(request, Path,
5024 * 1024, new FileRenamePolicy() {
@Override
public File rename(File arg0) {
boolean result = arg0.renameTo(new File(arg0
.getParentFile().getAbsolutePath()
+ File.separator + "Standard"));
if (result) {
System.out.println("Renamed");
}
return arg0;
}
});
5024 * 1024, new FileRenamePolicy() {
@Override
public File rename(File arg0) {
boolean result = arg0.renameTo(new File(arg0
.getParentFile().getAbsolutePath()
+ File.separator + "Standard"));
if (result) {
System.out.println("Renamed");
}
return arg0;
}
});
But file.renameTo() have unpredictable behaviour on Windows, it seems. As the API documentation says,
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make sure
that the rename operation was successful.
You can use apache.commons.io library, which includes
You can use apache.commons.io library, which includes
FileUtils.moveFile()
or also the Files.move()
method in JDK 7.At bottom line we can successfully use DefaultFileRenamePolicy on windows.If you have any Confusion or any doubt then leave a message below or email me
Saturday, April 13, 2013
How to create gridview dynamically in jsp
How to generate gridview dynamically on runtime.We all waste lot of time ,to manage data in Grid view (Table Form ) Each Time when there is another Database table,we have to create a new Grid view for that.We can utilize this time while creating a single Grid view control that automatically generate Grid view.That Control accept Collection and bean object from us and generate the corresponding Grid View.This can be done by using reflection,Now there is no need to typecast the collection(ArrayList) and iterate it.While using reflection we can retrive the fields of any object. there is example
for (Field field : bean.getClass().getDeclaredFields())
{
field.setAccessible(true); //set it to make Accessiable
System.out.println( field.getName());
}
{
field.setAccessible(true); //set it to make Accessiable
System.out.println( field.getName());
}
Here bean is object and field object save the Fields retrive form bean object This code print the field name of your bean object(In Control this fieldname became the heading of grid view).Now how to retrive the value from the collection Object
for (Field field : collection.getClass().getDeclaredFields())
{
field.setAccessible(true);
Object value;
value = field.get(collection);// Retrive the vale from the Collection object
System.out.println(value);
}
{
field.setAccessible(true);
Object value;
value = field.get(collection);// Retrive the vale from the Collection object
System.out.println(value);
}
field.get(Object) return the value in field From this code we retrive the value's of collection.Now you got the basic idea how control works.I already created Grid view Control,You just have only to use it Download Code .Here is Smaple view for the output of control
Pass the Collection and bean object,name of servlet .when you click on Select or Delete the form is submitted and control goes to servlet (which you specify).And you have to chosse one unique field accordingly which perform Select or Delete operation .Suppose I want to select or delete field according to Id (As specified in Image),then I set index in my code to 0 and if I want to do operation according to Name then I set index to 1 and so on ,Start it from 0.Here is Code for Passing bean object,Collection Object ,Servlet Name and Index.
<%
SignupDA sa = new SignupDA();
Signups da = sa.Getall();//collection object
Signup be = new Signup();//bean object
int ind = 0; // It is index
application.setAttribute("bean", be);
application.setAttribute("coll", da);
application.setAttribute("action", "ManageCategory"); servlet name
application.setAttribute("index", ind);
%>
<%@ include file="/Control/Gridview.jsp"%>
SignupDA sa = new SignupDA();
Signups da = sa.Getall();//collection object
Signup be = new Signup();//bean object
int ind = 0; // It is index
application.setAttribute("bean", be);
application.setAttribute("coll", da);
application.setAttribute("action", "ManageCategory"); servlet name
application.setAttribute("index", ind);
%>
<%@ include file="/Control/Gridview.jsp"%>
Collection is nothing new ,it is same as Arraylist<bean> you can use ArrayList<yourbean> instead of Singups,sa is object of DBoperation,be is object of bean class,ind is index,ManageCategory is Servlet.Now how to use the Control on your jsp page.Grid view control is also a jsp page.For this we have to include the Gridview.jsp file on current Jsp which is specifed in previous Code.This way you can use Gridview Control in your project
If you click on Link select or delete it will go to the servlet, you can recieve the value in doPost section as shown below
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String Id = request.getParameter("index");
String Operation = request.getParameter("operation");
System.out.println(Id + " " + Operation);
}
HttpServletResponse response) throws ServletException, IOException
{
String Id = request.getParameter("index");
String Operation = request.getParameter("operation");
System.out.println(Id + " " + Operation);
}
Here you recieve the index and operation.if you want to delete then you can use"if(Operation.equals("Delete")) {your code}" by using Id (Index value)For Select "if (Operation.equals("Select")) {your code}"
Here is code for Gridview Control Download Code
If you have any confusion .Please Drop your Comment Below
Thursday, April 4, 2013
Where does Eclipse store generated servlet files after jsp run on server?
I wonder many time that where the compiled jsp goes.I can't find it in the Eclipse workspace not in tomcat server directory.I read it in the book ,it say that the compiled servlet save in the work directory,but I still can't find it.After some effort's fortunately, I find the storage location in the environment variables of Project. but it is tricky way.
Now in good manner how to find the storage location of your tomcat server
Now in good manner how to find the storage location of your tomcat server
- Double Click on the server

- Now as arrow point to the location ,Catch this location in your Eclipse Workspace
- This folder contain the Tomcat Server Container and other important stuff

- Conf is same as Same as Servers folder in your eclipse workspace
- work folder contain the servlet file of jsp. "work\Catalina\localhost\YourProjectName\org\apache\jsp"
- jsp folder contain the java file and class file .Open Java file in the eclipse,this is compiled form of your jsp file
Tuesday, April 2, 2013
Send Email through Java via Gmail,Yahoo,Hotmail or your hosting Email server
How to send email from java? .For this we need an JavaMail API .Include this jar file in your class path by placing it into YourProject\WebContent\WEB-INF\lib or if you are not using EE version then add it into environment variable.
First we need to login to mail account.
- Email server consist two types of port, one is for incoming mail(POP, IMAP) and another is for outgoing mail(SMTP).For sending purpose we only need SMTP port of that particular Email server.
- Second thing is how to send authentication data to server using insecure network.To maintain security there is two protocol SSL and TLS which send authentication data(Email,Password) to server in encrypted form,If we use TLS ,it allow both secure and unsecure connection,and if SSL it only allow secure Connection.That is up to user to choose the protocol
- In java to carry Email account setting,we use Properties,These Email settings are
2. smtp port (either for protocol SSL or for protocol TLS)
3 valid EmailId and password of active account
- And for Authentication we use javax.mail.Authenticator() and save it into session while getting the Default instance of Properties and Authenticator().
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); / / Host Name
props.put("mail.smtp.socketFactory.port", "465");/ / SSL Port
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator()
{ protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication("YOUREMAIL@GMAIL.COM", "PASSWORD");
}
});
props.put("mail.smtp.host", "smtp.gmail.com"); / / Host Name
props.put("mail.smtp.socketFactory.port", "465");/ / SSL Port
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator()
{ protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication("YOUREMAIL@GMAIL.COM", "PASSWORD");
}
});
Now Code for Login in Gmail using TLS protocol
Actually Gmail use STARTTLS
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");/ / Host Name
props.put("mail.smtp.port", "587"); / / TLS Port
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator()
{ protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication("YOUREMAIL@GMAIL.COM", "PASSWORD");
}
});
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");/ / Host Name
props.put("mail.smtp.port", "587"); / / TLS Port
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator()
{ protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication("YOUREMAIL@GMAIL.COM", "PASSWORD");
}
});
- Now after login we have to compose email,First understand our email message cannot simply transfer through http,for this a particular standard are set and those are mime standard,our email server use mime to transfer email ,first it convert the email message into mime format and transfer it on network Know more about Mime
- Email Header contain all the information about the message and Routing information.
- Use MimeMessage to create mail format. It provide option to set From ,where and To whom ,email is going to be sent and it also provide setSubject to set the Subject of Email.
- After that,it give freedom to setContext of email.Use text/html if you want to send html in message else there is no need to setContext to text/html
- At Last Transport.send(message),same as we click on send button in email client application
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("YOUREMAIL@GMAIL.COM"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(TO@XYZ.COM));
message.setSubject("My First Email using Behind Java Scene");
String msg="Thank's to Behind Java Scene to teach the core aspect of Email sending "
message.setContent(msg, "text/html; charset=utf-8");
Transport.send(message);
message.setFrom(new InternetAddress("YOUREMAIL@GMAIL.COM"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(TO@XYZ.COM));
message.setSubject("My First Email using Behind Java Scene");
String msg="Thank's to Behind Java Scene to teach the core aspect of Email sending "
message.setContent(msg, "text/html; charset=utf-8");
Transport.send(message);
Email Server Settings for Yahoo
Only change the host Name and SMTP port from Login code
Host Name :smtp.mail.yahoo.com
SMTP port: 465
Properties props = new Properties();
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.host", "smtp.mail.yahoo.com");
props.put("mail.smtp.auth", true);
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.host", "smtp.mail.yahoo.com");
props.put("mail.smtp.auth", true);
Email Server Settings for Hotmail
Only change the host Name and SMTP port from Login code in SSL section
Host Name: smtp.live.com
SMTP port: 25
Host Name: smtp.live.com
SMTP port: 25
Same for Hosting Server only change your particular Host Name and change your specific SMTP port