Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket s = new Socket("Localhost", 9999);
BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter w = new PrintWriter(s.getOutputStream(), true);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
String line;
do {
line = r.readLine();
if( line != null )
System.out.println(line);
line = con.readLine();
w.println(line);
}
while ( !line.trim().equals("bye") );
}
catch (Exception err) {
System.err.println(err);
}
}
}
Server.java
import java.io.*;
import java.net.*;
public class Server {
private ServerSocket server;
public Server(int portnum) {
try{
server = new ServerSocket(portnum);
}
catch (Exception err) {
System.out.println(err);
}
}
public void serve() {
try {
while (true) {
Socket client = server.accept();
BufferedReader r = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter w = new PrintWriter(client.getOutputStream(), true);
w.println("Welcome to the Java EchoServer. Type 'bye' to close.");
String line;
do {
line = r.readLine();
if( line != null )
w.println("Got: "+ line);
}
while ( !line.trim().equals("bye") );
client.close();
}
}
catch (Exception err) {
System.err.println(err);
}
}
public static void main(String[] args){
Server s = new Server(9999);
s.serve();
}
}
Output
Welcome to the Java EchoServer. Type 'bye' to close.
hi
Got: hi
whats up
Got: whats up
f9
Got: f9
A blog provide anexample with sample code for swing , servlet, jdbc and odbc connection to database, jsp, servlets, taglib, sql server, cassandra and many more. we also provide Apache camel sample code for integration.
Saturday, October 20, 2012
Echoserver
Tag library with coustom tag
author.tld
authorTagHandler.java
index.jsp
file Structure
output
1.0
au
/WEB-INF/tlds/author ;
authorTagHandler
handler.authorTagHandler
scriptless
authorTagHandler.java
package handler;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class authorTagHandler extends SimpleTagSupport {
@Override
public void doTag() throws JspException {
JspWriter out = getJspContext().getOut();
try {
out.println("welcome to my business");
JspFragment f = getJspBody();
if (f != null) {
f.invoke(out);
}
} catch (java.io.IOException ex) {
throw new JspException("Error in authorTagHandler tag", ex);
}
}
}
index.jsp
<%--
Document : index
Created on : Oct 18, 2012, 8:17:18 PM
Author : UTTAM KASUNDARA
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Your Standard Hello World Demo</title>
</head>
<body bgcolor="#ffffff">
<%@taglib uri="/WEB-INF/tlds/author" prefix="au" %>
<au:authorTagHandler></au:authorTagHandler>
</body>
</html>
file Structure
output
Tuesday, October 16, 2012
my sql connectivity
Connection to demonstrate My sql connectivity to student with name and id filled
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class mysql1 {
public static void main(String[] args)
{
try {
System.out.println("My sql Connect Example.");
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","root","");
System.out.println("Connected to the database");
Statement statement = conn.createStatement();
//create table statement
String createStudentTable = "CREATE TABLE student(NAME VARCHAR(64),ID number(10))";
statement.executeUpdate(createStudentTable);
statement.executeUpdate("INSERT INTO student VALUES ( 'UML User Guide','1909')");
statement.executeUpdate("INSERT INTO student VALUES ( 'UML User Guide2','2909')");
statement.execute("UPDATE student SET id=27889 WHERE id=28889");
statement.executeQuery("delete * from student");
conn.close();
System.out.println("Disconnected from database");
} catch (InstantiationException ex) {
Logger.getLogger(mysql1.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(mysql1.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(mysql1.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(mysql1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Connect java to Microsoft access(odbc) database
In this example demonstrate the Microsoft access(odbc) connectivity database contain the bank table with sr_no,name,Ac.no,balance,ph.no.
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Connectivity {
public static void main(String args[]){
try {
Connection c;
Statement st;
ResultSet r;
Class.forName("sun.jdbc.odbc.JdcbOdbcDrive");
c = DriverManager.getConnection("jdbc:odbc:Pruthvi”);
st = c.createStatement();
st.executeUpdate("insert into Bank(name,account_no,balance,pn_no) values('uttam',1005,10512,1612)");
r = st.executeQuery("select * from Bank");
System.out.println("Sr.No."+"\t"+"Name"+"\t"+"Ac.No."+"\t"+"Balance"+"\t"+"Ph.No");
while (r.next()) {
System.out.print(r.getInt(1)+"\t");
System.out.print(r.getString(2)+"\t");
System.out.print(r.getInt(3)+"\t");
System.out.print(r.getInt(4)+"\t");
System.out.print(r.getInt(5)+"\t");
System.out.println("");
}
c.close();
st.close();
} catch (SQLException ex) {
Logger.getLogger(Connectivity.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Connectivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
statefull visitor counter
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class counter extends HttpServlet
{
@Override
public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException
{
HttpSession session=req.getSession(true);
Integer count=(Integer)session.getAttribute("count");
if(count==null)
{
count=1;
}
else
{
count=new Integer(count.intValue()+1);
}
session.setAttribute("count", count);
PrintWriter pw=res.getWriter();
pw.println("counter is="+count);
}
}
Saturday, October 13, 2012
Create login servlet
Loginservlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author UTTAM KASUNDARA
*/
@WebServlet(name = "NewServlet", urlPatterns = {"/NewServlet"})
public class Loginservlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String unm=request.getParameter("unm");
String pass=request.getParameter("pass");
if(unm.equals("uttam") && pass.equals("123")){
out.println("<html><body>wel-come "+unm+"</body></html>");
}
else{
out.println("<html><body>sign again "+unm+"</body></html>");
}
/* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Loginservlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Loginservlet at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
*/
} finally {
out.close();
}
} // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
URL connection send and properties
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class URLTesting
{
private static Map<String, List<String>> headerMap;
private static boolean key;
public static void main(String args[]) throws MalformedURLException, IOException
{
URL url=new URL("http://www.google.com:80/html/default.asp");
URLConnection urlcon=url.openConnection();
URL urltemp=new URL("http://www.google.com/html/default.asp");
HttpURLConnection httpurlcon=(HttpURLConnection) url.openConnection();
System.out.println("Protocol:"+url.getProtocol());
System.out.println("Port for URL:"+url.getPort());
System.out.println("Port for urltemp:"+urltemp.getPort());
System.out.println("Host:"+url.getHost());
System.out.println("File:"+url.getFile());
//System.out.println("String representation of URl:"+url.getExternalForm());
System.out.println("Content Type:"+urlcon.getContentType());
System.out.println("Content Encoding:"+urlcon.getContentEncoding());
System.out.println("Content Length:"+urlcon.getContentLength());
System.out.println("Date:"+ new Date(urlcon.getDate()));
System.out.println("Last Modified:"+new Date(urlcon.getLastModified()));
System.out.println("Expiration:"+new Date(urlcon.getExpiration()));
System.out.println("Request method:"+httpurlcon.getRequestMethod());
System.out.println("Responsee Message:"+httpurlcon.getResponseMessage());
System.out.println("Response code:"+httpurlcon.getResponseCode());
Map<String, List<String>>
HeaderMap=httpurlcon.getHeaderFields();
Set<String> headerKeys=(Set<String>) HeaderMap.keySet();
System.out.println("....NOW THW HEADER....");
for(String key:headerKeys)
{
System.out.println("Key:"+key);
System.out.println("value:"+HeaderMap.get(key));
System.out.println("--------------");
}
}
static class string {
public string() {
}
}
private static class set<T> {
public set() {
}
}
}
how to create dropdown list in java swing
Dropdownlist.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Dropdownlist extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Dropdownlist</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Dropdownlist at " + request.getContextPath () + "</h1>");
out.println("<form method='get'>");
out.println("<select name='s'>");
for(int i=0;i<10;i++){
out.println("<option name="+i+">"+i+"</option>");
}
out.println("</select>");
out.println("<input type='submit'>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
int b=Integer.parseInt(request.getParameter("s"));
for(int j=1;j<=10;j++){
out.print(b+"*"+j+"=");
out.println(j*b);
out.println("<br>");
}
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
create stateless visitor counter
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author UTTAM
*/
@WebServlet(name = "Visitorcoounter", urlPatterns = {"/Visitorcoounter"})
public class Visitorcoounter extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
public static int counter=0;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession ses=request.getSession(true);
Integer count=(Integer)ses.getAttribute("count");
if(count == null){
count=1;
}
else{
count=new Integer(count.intValue()+1);
}
ses.setAttribute("counter",count);
out.println("<html><body>my sessiion"+count+"<body><html> ");
try {
/* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Visitorcoounter</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Visitorcoounter at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
*/
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Subscribe to:
Posts (Atom)