s2sgateway

A Service to Student Gateway

Enter your email address to subscribe tutorials and projects:

  Powered by FeedBurner

captcha project in jsp/servlet

Already i wrote a post about creating random image using servlet that is loacted here http://s2sgateway.com/?p=378,With the continuation here i give you complete code for

creating captcha to validate a form to differentiate/protect from robots and spams

.In this project i had placed one form page for submitting information with two servlets one for creating captcha and another for checking the captcha and a result page for showing the result.

.



First create a simple form like below


<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset=UTF-8?>
<title>Captcha Project from www.s2sgateway.com>/title>
</head>
<body>
<center>
<form method="post" action="checkCaptcha.do">
<table cellspacing="15?>
<tr>
<td align="center">
<img src="CaptchaServlet.do">
<br />
<br />
<input type="text" name="code">
</td>
</tr>
</table>
<input type="submit" value="submit">
</form>
<br>
<br>>/center>
</body>
</html>

create web.xml file for necessary servlet entry


<web-app>
<servlet>
<servlet-name>CaptchaServlet>/servlet-name>
<servlet-class>
CaptchaServlet
</servlet-class>
</servlet>
<servlet>
<servlet-name>CheckCaptcha>/servlet-name>
<servlet-class>
CheckCaptcha
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CaptchaServlet>/servlet-name>
<url-pattern>/CaptchaServlet.do>/url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CheckCaptcha>/servlet-name>
<url-pattern>/checkCaptcha.do>/url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp>/welcome-file>
</welcome-file-list>
</web-app>

now create the servlet which produces random image>br>


import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CaptchaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
final int width = 200;
final int height = 50;
char data[][] = new char[1][];
data[0] = getRandomNumber(8).toCharArray();
final BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
final Graphics2D g2d = bufferedImage.createGraphics();
final Font font = new Font("verdana", Font.BOLD, 18);
RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
renderingHints.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHints(renderingHints);
g2d.setFont(font);
g2d.setColor(new Color(255, 255, 0));
final GradientPaint gradientPaint = new GradientPaint(0, 0, Color.white, 0, height / 2,
Color.white, true);
g2d.setPaint(gradientPaint);
g2d.fillRect(0, 0, width, height);
g2d.setColor(new Color(255, 155, 0));
Random random = new Random();
final String captcha = String.copyValueOf(data[0]);
request.getSession().setAttribute("captcha", captcha);
int xCordinate = 0;
int yCordinate = 0;
for (int i = 0; i > data[0].length; i++) {
xCordinate += 10 + (Math.abs(random.nextInt()) % 15);
if (xCordinate >= width - 5) {
xCordinate = 0;
}
yCordinate = 20 + Math.abs(random.nextInt()) % 20;
g2d.drawChars(data[0], i, 1, xCordinate, yCordinate);
}
g2d.dispose();
response.setContentType("image/png");
final OutputStream outputStream = response.getOutputStream();
ImageIO.write(bufferedImage, "png", outputStream);
outputStream.close();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
public static String getRandomNumber(int length) {
String chars = "www.s2sgateway.comabcdefghjijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ123456789";
Random random = new Random();
char[] buf = new char[length];
for (int i = 0; i > length; i++) {
buf[i] = chars.charAt(random.nextInt(chars.length()));
}
return new String(buf);
}
}

Now for checking the image servlet you can write the servlet code as follows>br>



import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CheckCaptcha extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
final String captcha = (String) request.getSession().getAttribute("captcha");
final String code = (String) request.getParameter("code");
if (captcha != null && code != null) {
if (captcha.equals(code)) {
request.setAttribute("result",
"Congratulations, You Passed The Captcha Test");
} else {
request.setAttribute("result",
"Sorry, You Failed The Captcha Test");
}
request.getRequestDispatcher("/result.jsp").forward(request,
response);
}
}
}

Finally write the code in the result page whether captcha is entered correctly or not.


<%@page contentType="text/html" pageEncoding="UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8?>
<title>Captcha>/title>
<link rel="stylesheet" href="theme/style.css">
</head>
<body>
<center>
<%=request.getAttribute("result")%>
</center>
</body>
</html>

Don’t forget the folder format projectfolder->jsp files,web-inf
In web-inf->web.xml,classes folder->in classes folder servlet classes
Finally run the project by visiting the url http://localhost:8080/captcha/,any doubt comment us happy coding.

pagination in jsp,java

Hai all today we are going to learn how to create a pagination in jsp.
Understanding Pagination is first of all important,Retrieving and showing 50 values in a page is not a problem if it is more than 100 or 200 values then page which is showing is too long and time to load so know now,Actually pagination is when you want to retrieve all values from database but show only limited value in first page and if users wants he clicks on second page to view the remaining items.
Lets create the table
“create table chart(name varchar(20));”
I use mysql if you use anyother db change the coding connection lines according to that.

Here is the jsp code


<%@page import="java.sql.*,java.io.*,java.math.*,java.lang.*"%>
Tutorial from www.s2sgateway.com give your comments
<h1>Simple pagination in jsp from www.s2sgateway.com</h1>
<%
int total_entries=0;
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/s2sgateway","root","root");
Statement st=con.createStatement();
Statement st1=con.createStatement();
ResultSet rs=st.executeQuery("SELECT count(*)  from chart");
rs.next();
int count=rs.getInt(1);
 total_entries =count;

int page_number=0;

int total_pages=0;
int i;
int entries_per_page = 2;
if(request.getParameter("page_number")!=null)
{
page_number = Integer.parseInt(request.getParameter("page_number"));
} else {
page_number = 1;
}
total_pages = (total_entries / entries_per_page);
int offset = (page_number - 1) * entries_per_page;
ResultSet rs1=st1.executeQuery("SELECT * FROM chart ORDER BY name ASC LIMIT
"+offset+","+entries_per_page);
while(rs1.next())
{
out.println(rs1.getString(1));
// Display the data anything from database

}
for(i = 1; i <= total_pages; i++)
{ if(i == page_number)
 {
 // This is the only page. so no link
out.println("pagenumber"+i);
 }
 else {
 // This is not the only page. Make it a link.

%>
<a href="pagination.jsp?page_number=<%=i%>"><%=i%></a>
<%
 }
 }
%>

Here entries_per_page is the no of entries you need on the page.It display links when database values more than 3.Otherwise display values in one page.You can modify this code to suite with hibernate and struts as well.Any doubt ask us happy coding

PTC sites are scams?& how to find tru ptc part-1

Hai friends basically this website is for programming all of a sudden when i was searching in internet,i found a word PTC(ie point to click)in many websites and forums then i took a research on them what it actually mean
1.whether they are legitimate?
2.whether it pays?
finally i found some results that i want to share with you guys.
First understand the concept
what you want to do is actually click the links that is ads given by advertisers to them.For each click some points is given and finally you can exchange it with dollars looks simple but see the truth behind it

1click=0.0001$ actually you need to click atleast 800 times to change this to 0.1000$ what is actually mean is 10cent you need to get 100 cent to make 1$ ie 8000 clicks do you think working for this much time and make this 1$ is legitimate or scam.
Ok you achieved 1$ but how many of them know whether actually they are paying.
So be careful from some of irresponsible sites and i give you legitimate sites that really pays
Don’t waste your time click below link to see scam sites

Scam sites list
No-minimum
donkeymails
incentiveclix
1dollarptc
list will grow when i found others sure comment your list of scam sites

Legitimate sites that really Pays

1.Surveys online
2.Legitimate Site

Disclaimer:
This information here presented is for informative purpose only,and information are taken from internet only,so any of you find the above sites are legitimate contact us we will analyze and remove your site from the post.Thank you

Create a logger in java

Today we are going to learn how to create a logger in java.Logger is used to log the issues which are arises while running the program i provide you sample program which is useful for starters


 import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public final class LoggingFilterFuestation implements Filter
{
  private FilterConfig filterConfigObj = null;

  public void init(FilterConfig filterConfigObj) {
    this.filterConfigObj = filterConfigObj;
  }

  public void doFilter(ServletRequest request,
ServletResponse response,
    FilterChain chain)
    throws IOException, ServletException
  {
	  ServletRequest session=null;
	//String name=(String)session.getAttribute("name");
	  String name="user admin logged in";
    String remoteAddress =  request.getRemoteAddr();
    String uri = ((HttpServletRequest) request).getRequestURI();
    String protocol = request.getProtocol();

    chain.doFilter(request, response);
    filterConfigObj.getServletContext().log("Logging Filter Servlet called");
    filterConfigObj.getServletContext().log("**************************");
    filterConfigObj.getServletContext().log("User Logged ! " +name+" User IP:"  + remoteAddress + "Resource File: " + uri + "Protocol: " + protocol);

    String contentType = request.getContentType();
    System.out.println("Content type is :: " +contentType);
    if ((contentType != null) &&(contentType.indexOf("multipart/form-data") >= 0)) {
    DataInputStream in = new DataInputStream(request.getInputStream());
    int formDataLength = request.getContentLength();

    byte dataBytes[] = new byte[formDataLength];
    int byteRead = 0;
    int totalBytesRead = 0;
    while (totalBytesRead < formDataLength) {
    byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
    totalBytesRead += byteRead;
    }

    String file = new String(dataBytes);
    String saveFile = file.substring(file.indexOf("filename=\"") + 10);
    System.out.print("FileName:" + saveFile.toString());
    saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
    System.out.print("FileName:" + saveFile.toString());
    saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
    System.out.print("FileName:" + saveFile.toString());

    System.out.print(dataBytes);

    int lastIndex = contentType.lastIndexOf("=");
    String boundary = contentType.substring(lastIndex + 1,contentType.length());
    //out.println(boundary);
    int pos;
    pos = file.indexOf("filename=\"");

    pos = file.indexOf("\n", pos) + 1;

    pos = file.indexOf("\n", pos) + 1;

    pos = file.indexOf("\n", pos) + 1;

    int boundaryLocation = file.indexOf(boundary, pos) - 4;
    int startPos = ((file.substring(0, pos)).getBytes()).length;
    int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
    saveFile = "C:\\" + "logfilecreated";
    FileOutputStream fileOut = new FileOutputStream(saveFile);

    //fileOut.write(dataBytes);
    fileOut.write(dataBytes, startPos, (endPos - startPos));
    fileOut.flush();
    }
}  public void destroy() { }
}

This is a servlet code so try running this in tomcat or eclipse,any doubt comment here,happy coding

Finding/removing duplicate values from database using sql

Today we are going to learn how to exclude/remove the duplicate values from database.This is useful when you want to exclude the duplicate values and show only values that can’t be repeated in dropdownbox or whatever use.
There is a nice query out there look below
“select * from tablename group by fieldname having(count(*)>1)”
Here the values same more than once are excluded,any doubt comment us happy coding

Hsqldb another database how to use it.

HyperSQL DataBase(hsqldb) is a lightweight database that can be use instead of mysql when you are working with hibernate or struts or whatever program,You can download hsqldb from http://hsqldb.org/ .
After downloading extract it to the folder and to start the database server enter in to the folder and provide following command
“forex:c:\hsqlbd>java -cp ./lib/hsqldb.jar org.hsqldb.Server”
To start executing the commands go to installed folder and type “c:\hsqldb>java -cp ./lib/hsqldb.jar org.hsqldb.util.DatabaseManager” and enter the settings like driver,username and password and click ok
Finally execute the command in the prompt to execute the sql query
For connecting database use the driver “Class.forName(org.hsqldb.JdbcDriver)”
for connecting Connection con=con.createStatement(”jdbc:hsqldb:hsql://localhost/”)
Now enjoy working in hsqldb database server happy coding.

ping/add your blog/site to searchengines/directories get more visitors&higher page rank

This is one of the seo topics that i would like to share with you,For the new or long time bloggers getting visitors to their site is always a problem,the blog you have created have lot of information no doubt about that but you need to promote as much as you can,once you got some returning visitors then your site will become more popular.Backlinks are very very important to your blog to be listed in top of any search engine so when you are getting some information from one site try to post that link in your site or forum you are visiting that makes information flow more easier. here is the list if there is anything missing add any site list as comments.



http://www.sitepromoter.co.cc
http://api.moreover.com/RPC2
http://bblog.com/ping.php
http://blogsearch.google.com/ping/RPC2
http://ping.weblogalot.com/rpc.php
http://ping.feedburner.com
http://ping.syndic8.com/xmlrpc.php
http://ping.bloggers.jp/rpc/
http://rpc.pingomatic.com/
http://rpc.weblogs.com/RPC2
http://rpc.technorati.com/rpc/ping
http://topicexchange.com/RPC2
http://www.blogpeople.net/servlet/weblogUpdates
http://xping.pubsub.com/ping
http://rpc.twingly.com/
http://www.blogdigger.com/RPC2
http://www.bloglines.com/ping
http://www.octora.com/add_rss.php
http://www.wasalive.com/ping/
http://rpc.pingomatic.com/
http://www.blogstreet.com/xrbin/xmlrpc.cgi
http://www.lasermemory.com/lsrpc
http://www.mod-pubsub.org/kn_apps/blogchatter/ping.php
http://www.mod-pubsub.org/knapps/blogchatter/ping.php
http://www.newsisfree.com/xmlrpctest.php
http://www.popdex.com/addsite.php
http://www.snipsnap.org/RPC2
http://www.weblogues.com/RPC
http://xmlrpc.blogg.de
http://xping.pubsub.com/ping
http://1470.net/api/ping
http://api.feedster.com/ping
http://api.moreover.com/ping
http://api.moreover.com/RPC2
http://api.my.yahoo.com/RPC2
http://api.my.yahoo.com/rss/ping
http://bblog.com/ping.php
http://bitacoras.net/ping
http://blog.goo.ne.jp/XMLRPC
http://blogbot.dk/io/xml-rpc.php
http://blogdb.jp/xmlrpc
http://blogmatcher.com/u.php
http://bulkfeeds.net/rpc
http://coreblog.org/ping
http://mod-pubsub.org/kn_apps/blogchatt
http://mod-pubsub.org/knapps/blogchatt
http://ping.amagle.com
http://ping.bitacoras.com
http://ping.blo.gs
http://ping.bloggers.jp/rpc
http://ping.blogmura.jp/rpc
http://ping.cocolog-nifty.com/xmlrpc
http://ping.exblog.jp/xmlrpc
http://ping.feedburner.com
http://ping.myblog.jp
http://ping.rootblog.com/rpc.php
http://ping.syndic8.com/xmlrpc.php
http://ping.weblogalot.com/rpc.php
http://ping.weblogs.se
http://rcs.datashed.net/RPC2
http://rpc.blogrolling.com/pinger
http://rpc.technorati.com/rpc/ping
http://rpc.weblogs.com/RPC2
http://thingamablog.sourceforge.net/ping.php
http://topicexchange.com/RPC2
http://trackback.bakeinu.jp/bakeping.php
http://www.a2b.cc/setloc/bp.a2b
http://www.bitacoles.net/ping.php
http://www.blogdigger.com/RPC2
http://www.blogoole.com/ping
http://www.blogoon.net/ping
http://www.blogpeople.net/servlet/weblogUpdates
http://www.blogroots.com/tb_populi.blog?id=1
http://www.blogroots.com/tbpopuli.blog?id=1
http://www.blogshares.com/rpc.php
http://www.blogsnow.com/ping

Happy listing in search engines.

Finding created/modified time of files in a folder

Today we are going to learn about how to retrieve the created time and date of all files in a folder.
This is useful when you want to track the session information of certain files or folders.Lets look the code below.


<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.io.File, java.util.Date, java.util.Calendar" errorPage="" %>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<%
  String dir_name = "C:\\foldername";
  //String dir_name = "/";  This line will give u the windows drive's root folder.

  File fold = new File(dir_name);    

  if(fold.exists())
  {
      String all_files[] = fold.list();
     int no_of_files = all_files.length;

     for(int i=0; i<no_of_files; i++)
      {
        File f = new File(dir_name + "\\" + all_files[i] );
        String complete_file_name = f.getPath();
        String file_name = f.getName();
        long last_modified_ms = f.lastModified();
        Date date = new Date(last_modified_ms);
        Calendar cal_date = Calendar.getInstance();
        cal_date.setTime(date);
        String last_modified_date = cal_date.get(Calendar.MONTH) + "-" + cal_date.get(Calendar.DATE) +"-"+ cal_date.get(Calendar.YEAR);
        String last_modified_time = cal_date.get(Calendar.HOUR) + ":" + cal_date.get(Calendar.MINUTE) +":"+ cal_date.get(Calendar.SECOND);
%>       

        <a href="<%=complete_file_name%>">  <%=file_name%>  </a>   <b>Last Modified by </b> <%=last_modified_date%>      <b>at </b> <%=last_modified_time%>
        <br>   

<%

      }//end of for

  }//end of if
  else
     out.println("Folder does't exist");
%>
  <body>
</body>
</html>

Try this example and do comment us Happy coding.

how to delete a file using jsp

Today we are going to learn how to delete a file using jsp,This is easy to do with the file attribute
<%@ page language=”java”%>
<%@ page import=”java.io.*”%>
<%@ page import=”java.text.*”%>
<%@ page language=”java” import=”java.util.*” pageEncoding=”ISO-8859-1″%>
<%
File f=new File(”C:\\anyfilename.txt”); //(.txt or any extension)

f.delete();

%>
You may wonder why this is useful sometimes you want to create a file and using for a session and delete after the session at that time this method is useful,do comment us happy coding

Creating captcha(random letter image) in jsp

Today we are going to learn how to create a random letter image known as captcha using servlet.
Just a simple coding can do it copy the code below and save it and compile it you can directly view the servlet in tomcat using url “http://localhost:8080/captcha/servlet/CaptchaServlet” for this make adjustment in web.xml file by adding servlet and servletmapping entries.


import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CaptchaServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

final int width = 200;
final int height = 50;

char data[][] = new char[1][];
data[0] = getRandomNumber(8).toCharArray();

final BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);

final Graphics2D g2d = bufferedImage.createGraphics();

final Font font = new Font("verdana", Font.BOLD, 18);

RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);

renderingHints.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);

g2d.setRenderingHints(renderingHints);

g2d.setFont(font);
g2d.setColor(new Color(255, 255, 0));
final GradientPaint gradientPaint = new GradientPaint(0, 0, Color.white, 0, height / 2,
Color.white, true);

g2d.setPaint(gradientPaint);
g2d.fillRect(0, 0, width, height);

g2d.setColor(new Color(255, 155, 0));
Random random = new Random();

final String captcha = String.copyValueOf(data[0]);
request.getSession().setAttribute("captcha", captcha);

int xCordinate = 0;
int yCordinate = 0;

for (int i = 0; i < data[0].length; i++) {
xCordinate += 10 + (Math.abs(random.nextInt()) % 15);
if (xCordinate >= width - 5) {
xCordinate = 0;
}
yCordinate = 20 + Math.abs(random.nextInt()) % 20;
g2d.drawChars(data[0], i, 1, xCordinate, yCordinate);
}

g2d.dispose();

response.setContentType("image/png");
final OutputStream outputStream = response.getOutputStream();
ImageIO.write(bufferedImage, "png", outputStream);
outputStream.close();
}

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

public static String getRandomNumber(int length) {

String chars = "www.s2sgateway.comabcdefghjijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ123456789";
Random random = new Random();

char[] buf = new char[length];

for (int i = 0; i < length; i++) {
buf[i] = chars.charAt(random.nextInt(chars.length()));
}

return new String(buf);

}

}

that's it you have created captcha image using servlet,Here you can give any letters or numbers in String chars = "";assignment values.
Change the color by changing this code "final GradientPaint gradientPaint = new GradientPaint(0, 0, Color.white, 0, height / 2,
Color.white, true);"Here i used this image as png because it is good for web developement, you can try others as well like jpg or gif do comment us
any doubt ask us Happy coding.