A Simple EJB 3.0 Example With JSP and Servlet

Yesterday I was trying to begin with EJB. There are lots of resources in web, but I found very less for EJB 3.0 in Netbeans. Among all tutorials, a video in Utube was easy to follow and very effective for understanding. Just few changes was required for me, because that tutorial is in Netbeans 6.1 and I am using Netbeans 6.9.

Here are those steps that I followed for a Stateless Session Bean program to combine with JSP and Servlet.

File -> New Project -> Java EE -> EJB Module

Next, provide the Project Name

Select Webserver and J2EE version, Finish.

Right click on the Project -> New -> Session Bean..

Provide a Bean Name
Assign a Package Name
Select Session Type as Stateless
And set the Interface as Remote, Finish

Open SessionBean.java
Press <alt + insert>, From the list select Add Business Method


Provide Menthod Name
Define a Return Type
Add Parameter by clicking on Add Button

Change the given method body to following code.

@Stateless
public class SessionBean implements SessionBeanRemote {

    public String businessMethod(String name) {
        return "Welcome " + name;
    }
}

Right Click on project and click on Build

Now the componenct is created and we have to use that component in Web Container. Here in this example we are going to use the EJB component via Servlet.

File -> New Project -> Java Web -> Web Application

Next, Provide Project Name

Next, Select  Web Server and J2EE version, Finish.

Right Click on Web Pages -> New -> Servlet..

Provide Servlet Name and Package location

Next, Provide a URL pattern for the Servlet, Finish.

In Servlet Page, remove comment from processRequest method body.
Press <alt + insert>, From the list Select Call Interprise Bean


Select SessionBean, Ok.

Go to index.jsp and create a form with a textbox and button and action to be use_ejb.do (servlet url pattern)

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>EJB Example</title>
    </head>
    <body>
        <form action="use_ejb.do" method="post">
            <input type="text" name="nm">
            <input type="submit" value="OK">
        </form>
    </body>
</html>

Then go to Servlet and send the received value from textbox to the RemoteBean method to get result from the RemoteBean.

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String str1=request.getParameter("nm");
        String str2=sessionBean.businessMethod(str1);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet UseBean</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>" + str2 + "</h1>");
            out.println("</body>");
            out.println("</html>");

        } finally {
            out.close();
        }
    }

Output :

@Stateless
public class SessionBean implements SessionBeanRemote { 

public String businessMethod(String name) {
return “Welcome ” + name;
}

}

Advertisements

Decimal to Hexadecimal in Java

One of my previous post, I had shown how to add HTML formatting to the Swing component. But while changing the color of the component while runtime, we have to change the color value to decimal to hexadecimal(r, g, b), to get it into HTML color format. So here is three way to convert decimal to hexadecimal value.

public class Hex
{
	public static void main(String args[])
	{
		int i = 14;
		String hexstr1 = Integer.toString(i, 16).toUpperCase();

		String hexstr2 = Integer.toHexString(i).toUpperCase();

		String hexstr3 = Integer.toHexString( 0x10 | 

i).substring(1).toUpperCase();

   		System.out.println("method 1:"+hexstr1); 
		System.out.println("method 2:"+hexstr2);

		System.out.println("method 3:" +hexstr3);
		
		/*output:
		method 1:E
		method 2:E
		method 3:E*/
     	}
}

Adding images in JLabel, Using HTML tags.

I was trying to add multiple images in a JLabel, which was only possible by adding HTML code in label. Most of the HTML tag works very similar as web page, but image URL is quite different when we have to provide relative address for image tag. Example goes here:

import javax.swing.JFrame;
import javax.swing.JLabel;
/**
 *
 * @author Prashant
 */
public class MultiImage extends JFrame{
 JLabel lbl;
 public MultiImage()
 {
 this.setLayout(null);

 String str="<html><img src='file:images/emoticons/01.png'>" +
 "<font color='red' size='4'><b>Happy Life</b></font>" +
 "<img src='file:images/emoticons/01.png'></html>";
 lbl=new JLabel(str);
 lbl.setBounds(15, 10, 120, 25);
 this.add(lbl);
 setSize(150,150);
 setVisible(true);
 setResizable(false);
 this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
 }
 public static void main(String[] args) {
 new MultiImage();
 }
}

Output:


Replacing bracket ( “(” ) in java

While doing my project I was facing this situation, which was solved as this:

public class ReplaceBracket
{
	public static void main(String[] args)
	{
		String str=":-)";
		String repStr=str.replaceAll("\\)","P");
		System.out.println(str +" is replcaed to  " +repStr);
	}
}
public class ReplaceBracket
{
public static void main(String[] args)
{
String str=”:-)”;
String repStr=str.replaceAll(“\\)”,”P”);
System.out.println(str +” is replcaed to  ” +repStr);
}
}

Here in this example, bracket is replaced by P.

Auto refreshing the content without reloading page, using JQuery

In my previous post I have given some tips to select multiple rows from a database table. Now we can import that page into a div, so that we can refresh the content of div without reloading the page (or you can create your own JSP page which content may dynamically change). In result, if the database content get change the page will auto refresh to get reload the changes.
For that we have JQuery framework, which you can download from here. And adding the below function of database we can reload the target JSP file in a DIV in every given time interval.

<html>
	<head>
		<Title>Just A Test</Title>
		<script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
        var auto_refresh = setInterval(
        function ()
        {
        $('#load_me').load('showdata.jsp').fadeIn("slow");
        }, 10000); // autorefresh the content of the div after
                   //every 10000 milliseconds(10sec)
        </script>
   </head>
    <body>
    <div id="load_me"> <%@ include file="showdata.jsp" %></div>
    </body>
</html>

Displaying Database Rows in JSP using Java Bean

Last few hours I spend for this solution. I was not getting the exact idea to use ArrayList for an Object, and access methods of that Object from the JSP page. Later I found the solution to be like this, If you have better solution than this please to comment me.

Here is the JavaBean  file were we access the data from the database and merge it to the List allData as objects of Datafields and returning the fields value using getter.



package beans;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ShowDataBean
{
    
    String error;
    List<Object> allData=new ArrayList<Object>();
    
    public String fname,lname,email,password,gender;
    Object obj=new Object();

    public void setObj(Object obj) {
        this.obj = obj;
    }
    public String getError() {
        return error;
    }
    public List getDb_Data()
    {
        int i=0;
        try
        {
                String qry;
                Class.forName("com.mysql.jdbc.Driver");
                Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_eexam","root","root");
                Statement s = con.createStatement();                
                qry="Select fname,lname,email,password,gender from tbl_user_primary";
                ResultSet r=s.executeQuery(qry);
                while(r.next())
                {
                    DataFields d=new DataFields(r.getString(1), r.getString(2), r.getString(3),r.getString(4), r.getString(5));                    
                    allData.add(i,d);
                    i++;
                }
                
        }
        catch(Exception ex)
        {
                error="<b>Contact Administrator :</b><br/>" + ex;
                System.out.println("Your query is not working" + ex);
        }
       return allData;
    }
    public String getFname()
    {
        this.fname=((DataFields)obj).fname;
        return this.fname;
    }
    public String getEmail() {
        this.email=((DataFields)obj).email;
        return this.email;
    }

    public String getGender() {
        this.gender=((DataFields)obj).gender;
        return this.gender;
    }
    public String getLname() {
        this.lname=((DataFields)obj).lname;
        return this.lname;
    }
    public String getPassword() {
        this.password=((DataFields)obj).password;
        return this.password;
    }

    public class DataFields
    {
        public String fname,lname,email,password,gender;

        public DataFields(String  fname,String  lname,String  email,String  password,String  gender)
        {
            this.fname=fname;
            this.lname=lname;
            this.email=email;
            this.password=password;
            this.gender=gender;
        }
    }
   
}

In JSP file we are accessing (getting) the fields after setting the object that is stored in each index of the List.


<%@ page import="java.util.*" %>
<jsp:useBean id="showDataBean" class="beans.ShowDataBean" scope="request" />

<table width="900" cellspacing="0" cellpadding="0">
    <tr>
  
        <td>
        Name
        </td>
        <td>
        Email
        </td>
        <td>
        PassWord
        </td>
        <td>
        Gender
        </td>
       
    </tr>
    <%
		List<Object> list=new ArrayList<Object>();
		list=showDataBean.getDb_Data();
		for(int i=0;i<list.size();i++)
        {
			showDataBean.setObj(list.get(i));
		%>
        
    <tr>
        <td>
        <%
			out.print(showDataBean.getFname() +" "+ showDataBean.getLname());
		
		%>
        </td>
        <td>
        <%
			out.print(showDataBean.getEmail());
		%>
        </td>
        <td>
        <%
			out.print(showDataBean.getPassword());
		%>
        </td>
        <td>
       <%
			out.print(showDataBean.getGender());
		%>
        </td>
		
    </tr>
    <% }%>
</table>

Sending mail from your Java application using google SMTP

Previous few I was trying to send mail from my JSP page. I had tried every way to make that code work. Later I found that I have to set  Mail Authentication, which lead me to solution.
Here is my SendMail cass, which you can implement in any Java application to send mail.

SendMail.java

/**
 *
 * @author Prashant
 */
import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {

	private String to;
	private String subject;
	private String text;

	public SendMail(String to, String subject, String text){
		this.to = to;
		this.subject = subject;
		this.text = text;
	}

	public void send() throws NoSuchProviderException, AddressException{

		try
		{
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			Properties props=new Properties();
			props.setProperty("mail.transport.protocol","smtp");
			props.setProperty("mail.host","smtp.gmail.com");
			props.put("mail.smtp.auth","true");
			props.put("mail.smtp.port","465");
			props.put("mail.debug","true");
			props.put("mail.smtp.socketFactory.port","465");
			props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtp.socketFactory.fallback","false");
			Session session=Session.getDefaultInstance(props,new GJMailAuthenticator());
			session.setDebug(true);
			Transport transport=session.getTransport();
			InternetAddress addressFrom=new InternetAddress("sender@gmail.com");
			MimeMessage message=new MimeMessage(session);
			message.setSender(addressFrom);
			message.setSubject(subject);
			message.setContent(text,"text/html");
			InternetAddress addressTo=new InternetAddress(to);
			message.setRecipient(Message.RecipientType.TO,addressTo);
			transport.connect();
			Transport.send(message);
			transport.close();
			System.out.println("DONE");

		}
		catch(Exception e)
		{

			e.printStackTrace();
		}
	}
}
class GJMailAuthenticator extends javax.mail.Authenticator{
	protected PasswordAuthentication getPasswordAuthentication()
	{
		return new PasswordAuthentication("sender@gmail.com","sender_password");

	}
}

Mail.java

/**
 *
 * @author Prashant
 */
public class Mail {

	public static void main(String[] args) {

		String to = "yohoprashant@yahoo.com";
		String subject = "Test";
		String message = "A test message";

		SendMail sendMail = new SendMail(to, subject, message);
                try
                {
                    sendMail.send();
                }
                catch (Exception e)
                {
                    //
                }
	}
}

Note:  If you want to use yahoo server instead of google, just you have to change the Port address to 25.

  1. import javax.mail.*;
  2. import javax.mail.internet.*;
  3. import java.util.*;
  4. public class Mail
  5. {
  6. String d_email = “iamdvr@gmail.com”,
  7. d_password = “****”,
  8. d_host = “smtp.gmail.com”,
  9. d_port  = “465”,
  10. m_to = “iamdvr@yahoo.com”,
  11. m_subject = “Testing”,
  12. m_text = “Hey, this is the testing email using smtp.gmail.com.”;
  13. public static void main(String[] args)
  14. {
  15. String[] to={“XXX@yahoo.com”};
  16. String[] cc={“XXX@yahoo.com”};
  17. String[] bcc={“XXX@yahoo.com”};
  18. //This is for google
  19. Mail.sendMail(“venkatesh@dfdf.com”,“password”,“smtp.gmail.com”,“465”,“true”,
  20. “true”,true,“javax.net.ssl.SSLSocketFactory”,“false”,to,cc,bcc,
  21. “hi baba don’t send virus mails..”,“This is my style…of reply..
  22. If u send virus mails..”);
  23. }
  24. public synchronized static boolean sendMail(String userName,String passWord,String host,String port,String starttls,String auth,boolean debug,String socketFactoryClass,String fallback,String[] to,String[] cc,String[] bcc,String subject,String text){
  25. Properties props = new Properties();
  26. //Properties props=System.getProperties();
  27. props.put(“mail.smtp.user”, userName);
  28. props.put(“mail.smtp.host”, host);
  29. if(!“”.equals(port))
  30. props.put(“mail.smtp.port”, port);
  31. if(!“”.equals(starttls))
  32. props.put(“mail.smtp.starttls.enable”,starttls);
  33. props.put(“mail.smtp.auth”, auth);
  34. if(debug){
  35. props.put(“mail.smtp.debug”, “true”);
  36. }else{
  37. props.put(“mail.smtp.debug”, “false”);
  38. }
  39. if(!“”.equals(port))
  40. props.put(“mail.smtp.socketFactory.port”, port);
  41. if(!“”.equals(socketFactoryClass))
  42. props.put(“mail.smtp.socketFactory.class”,socketFactoryClass);
  43. if(!“”.equals(fallback))
  44. props.put(“mail.smtp.socketFactory.fallback”, fallback);
  45. try
  46. {
  47. Session session = Session.getDefaultInstance(props, null);
  48. session.setDebug(debug);
  49. MimeMessage msg = new MimeMessage(session);
  50. msg.setText(text);
  51. msg.setSubject(subject);
  52. msg.setFrom(new InternetAddress(“p_sambasivarao@sutyam.com”));
  53. for(int i=0;i<to.length;i++){
  54. msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
  55. }
  56. for(int i=0;i<cc.length;i++){
  57. msg.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
  58. }
  59. for(int i=0;i<bcc.length;i++){
  60. msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i]));
  61. }
  62. msg.saveChanges();
  63. Transport transport = session.getTransport(“smtp”);
  64. transport.connect(host, userName, passWord);
  65. transport.sendMessage(msg, msg.getAllRecipients());
  66. transport.close();
  67. return true;
  68. }
  69. catch (Exception mex)
  70. {
  71. mex.printStackTrace();
  72. return false;
  73. }
  74. }
  75. }

Simple Database Application with JSF (User Login)

Here I am not going to show you step wise operation but I am only providing you the source code for each file that I have implemented for a Login application based on database. I hope you can easily follow these instructions after going through first three tutorials that I had published in previous post .

Here in this example we are having a login page. On Login button click, the username and password will get checked for login, if succeed then directed to success page otherwise ask to retry. And yes, I have used JDBC connectivity for MYSQL database. and I have used Netbeans IDE for this application.

Here we have files:

Inside Web Pages directory

login.jsp            -for login interface
login_fail.jsp     -for re-login interface
success.jsp        -page after successful login

Inside WEB-INF directory

faces-config.xml  – JSF configuration file

Inside beans package

login_bean.java  – here we define the connectivity and logic of the program.

Inside messages package

message.property  -It holds the message for validation.

Inside CSS directory

style.css  -CSS styles for the given JSP pages.

Database -db_jsf
Table – tbl_users
Fields -ID, UName, PWord

login.jsp

<%--
    Document   : Login
    Created on : Jan 18, 2010, 7:58:03 PM
    Author     : Prashant
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>LOGIN</title>
    </head>
    <link rel="stylesheet" type="text/css" href="CSS/style.css">
    <body>

        <f:view>
            <h:form id="login_frm">
                <h2>Login Please:</h2>
                <table width="250" border="0" cellspacing="0" cellpadding="2">
                  <tr>
                      <td colspan="2">
                            <h:message for="username" styleClass="errorMsg"/><br>
                            <h:message for="password" styleClass="errorMsg"/>
                        </td>
                  </tr>
                  <tr>
                    <td><h:outputText value="Username : "/></td>
                    <td><h:inputText id="username" value="#{login_bean.username}" required="true" styleClass="input_text"/></td>
                  </tr>
                  <tr>
                    <td><h:outputText value="Password : "/></td>
                    <td><h:inputSecret id="password" value="#{login_bean.password}" required="true" styleClass="input_text"/></td>
                  </tr>
                  <tr>
                      <td colspan="2" align="center">
                          <h:commandButton action="#{login_bean.checkValidUser}" value="Login" type="submit"/></td>
                  </tr>
                </table>
            </h:form>
        </f:view>
    </body>
</html>

success.jsp

<%--
    Document   : success
    Created on : Jan 18, 2010, 9:35:40 PM
    Author     : Prashant
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <f:view>
            <h:form>
                <h2>Hello <h:outputText value="#{login_bean.username}"/>, you are successfully login.</h2>
            </h:form>
        </f:view>
    </body>
</html>

login_fail.jsp

<%--
    Document   : Login
    Created on : Jan 18, 2010, 7:58:03 PM
    Author     : Prashant
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>LOGIN</title>
    </head>
    <link rel="stylesheet" type="text/css" href="CSS/style.css">
    <body>

        <f:view>
            <h:form id="login_frm">
                <h2>Login Please:</h2>
                <table width="250" border="0" cellspacing="0" cellpadding="2">
                  <tr>
                      <td colspan="2">
                            Incorrect Username or Password!!<br>
                            <h:message for="username" styleClass="errorMsg"/><br>
                            <h:message for="password" styleClass="errorMsg"/>
                        </td>
                  </tr>
                  <tr>
                    <td><h:outputText value="Username : "/></td>
                    <td><h:inputText id="username" value="#{login_bean.username}" required="true" styleClass="input_text"/></td>
                  </tr>
                  <tr>
                    <td><h:outputText value="Password : "/></td>
                    <td><h:inputSecret id="password" value="#{login_bean.password}" required="true" styleClass="input_text"/></td>
                  </tr>
                  <tr>
                      <td colspan="2" align="center">
                          <h:commandButton action="#{login_bean.checkValidUser}" value="Login" type="submit"/></td>
                  </tr>
                </table>
            </h:form>
        </f:view>
    </body>
</html>

faces-config.xml

<?xml version='1.0' encoding='UTF-8'?>

<!-- =========== FULL CONFIGURATION FILE ==================== -->

<faces-config version="2.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">

        <managed-bean>
            <managed-bean-name>login_bean</managed-bean-name>
            <managed-bean-class>beans.login_bean</managed-bean-class>
            <managed-bean-scope>request</managed-bean-scope>
        </managed-bean>
    <navigation-rule>
        <description>Loging Page</description>
        <from-view-id>/login.jsp</from-view-id>
        <navigation-case>
            <from-action>#{login_bean.checkValidUser}</from-action>
            <from-outcome>valid</from-outcome>
            <to-view-id>/success.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{login_bean.checkValidUser}</from-action>
            <from-outcome>invalid</from-outcome>
            <to-view-id>/login_fail.jsp</to-view-id>
        </navigation-case>

    </navigation-rule>
    <navigation-rule>
        <description>ReLoging Page</description>
        <from-view-id>/login_fail.jsp</from-view-id>
        <navigation-case>
            <from-action>#{login_bean.checkValidUser}</from-action>
            <from-outcome>valid</from-outcome>
            <to-view-id>/success.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{login_bean.checkValidUser}</from-action>
            <from-outcome>invalid</from-outcome>
            <to-view-id>/login_fail.jsp</to-view-id>
        </navigation-case>

    </navigation-rule>
    <application>
        <message-bundle>messages.message</message-bundle>
    </application>
</faces-config>

login_bean.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

/**
 *
 * @author Prashant
 */
import java.sql.*;
import java.util.*;

@ManagedBean(name="login_bean")
@RequestScoped
public class login_bean {
    private String username;
    private String password;
    private String dbusername;

    public String getDbpassword() {
        return dbpassword;
    }
    public String getDbusername() {
        return dbusername;
    }

    private String dbpassword;
    Connection con;
    Statement ps;
    ResultSet rs;
    String SQL_Str;

    public void dbData(String UName)
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_jsf","root","root");
            ps = con.createStatement();
            SQL_Str="Select * from tbl_users where UName like ('" + UName +"')";
            rs=ps.executeQuery(SQL_Str);
            rs.next();
            dbusername=rs.getString(2).toString();
            dbpassword=rs.getString(3).toString();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            System.out.println("Exception Occur :" + ex);
        }
    }
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
    public String checkValidUser()
    {
        dbData(username);

        if(username.equalsIgnoreCase(dbusername))
        {

            if(password.equals(dbpassword))
                return "valid";
            else
            {
                return "invalid";
            }
        }
        else
        {
            return "invalid";
        }
    }
}

message.property

# To change this template, choose Tools | Templates
# and open the template in the editor.

javax.faces.component.UIInput.REQUIRED=Please enter a value for this field.

style.css

/*
    Document   : style
    Created on : Jan 18, 2010, 8:29:32 PM
    Author     : Prashant
    Description:
        Purpose of the stylesheet follows.
*/

/*
   TODO customize this sample style
   Syntax recommendation http://www.w3.org/TR/REC-CSS2/
*/

root {
    display: block;
}
body
{
    font-family: sans-serif;
    font-size: 10px;
    color: #000000;
}
h2
{
    font-size: 16px;
    color: #3d2dff;
    font-family:serif;
}
.errorMsg
{
    font-size: 12px;
    font-family: serif;
    font-weight: bold;
    color: #FF0000;
    padding: 5px;
}

.input_text{
	font-family:Arial, Helvetica, sans-serif;
	font-size:10px;
	border:1px solid #FF7C08;
}

Snaps:

Table: tbl_users

Login Page

Unsuccessful Login

Successful Login

If you have any comment or suggestion on this post, please do comment me.

ref: http://www.roseindia.net/jsf/JSFLoginApplication.shtml

[/sourcecode][/sourcode]

Begining With JSF

I began JSF from just yesterday. After various suggestion I have selected Netbeans for JSF. So here are some steps to begin with JSF in Netbeans. I hope it will be helpful to you. (Download Netbeans from here)

Step 1:

File > New Project

Step 2:

From the New Project dialogue box, Select Web from Category and Web Application From Rejects, then click Next button.

Step 3:

Provide the Project Name and Location for the project, then click Next button.

Step 4:

Select server, As in Netbeans, if you have GlassFish, you will get GlassFish as default. Otherwise you have to click on Add button to add Tomcat. Then click on Next button.

Step 5:

Here we select the Framework for the project, and we have to select JavaServer Faces. Then click on finish.

Step 6:

Project will get created. Press CTRL+1 to go to Project tab. Open the project list and right click on WebPages and create new JSP file with name “HelloWorld”.

Step 7:

Code in the page will looks like this.

<%--
 Document   : HelloWorld
 Created on : Jan 11, 2010, 10:43:11 AM
 Author     : prashant
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>JSP Page</title>
 </head>
 <body>
 <h1>Hello World!</h1>
 </body>
</html>

Step 8:

To add JavaServer Faces components in JSP pages, you need to give your pages access to the two standard tag libraries, the HTML component tag library and the core tag library using taglib declarations. So, add these lines before <html> tag.

<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

Step 9:

Add these lines to the body part.


<f:view>

<h:outputText lang="en_US" value="Hello World"/>

</f:view>

Step 10:

Press Shift+F6 to run.

Match Finder (FLAME)

As I was going through the Infosys given code file, I found one program to be interesting. It really remind me my primary level days and it is really helpful to learn some of the string operation. So here I am providing the code for “match finder” based on the word “FLAME”. I hope it will be useful to you too.

Code Goes Like This:

/**
 *
 * @author Prashant
 */
public class MatchFinder {
    public String matchfinder(String str1, String str2) {
        int alp1[]=new int[65];
        int alp2[]=new int[97];
        String result = "";
        int k = 0;
        int count = 6;
        char c1[] = str1.toCharArray();
        for (int i = 0; i = 65) && ((int) c1[i] = 97) && ((int) c1[i] <= 122))
                alp1[(int) c1[i] -97]++;
        }
        char c2[] = str2.toCharArray();
        for (int i = 0; i = 65) && ((int) c2[i] = 97) && ((int) c2[i] <= 122))
            alp2[(int) c2[i] -97]++;
        }
        int t;
        boolean flag = true;
        for (int i = 0; i < 26; i++) {
            if (alp1[i] != alp2[i])
               flag = false;
            t = 0;
            t = alp1[i] -alp2[i];
            if (t  1; f++) {
            if (f == 6)
            f = 0;
            if (flames[f] != 'Z') {
                if (c == k) {
                   flames[f] = 'Z';
                   c = 1;
                   count--;
                } else
                c++;
            }
         }
        if (flames[0] == 'F')
            return "FRIEND";
        if (flames[1] == 'L')
            return "LOVE";
        if (flames[2] == 'A')
            return "AFFECTION";
        if (flames[3] == 'M')
            return "MARRIAGE";
        if (flames[4] == 'E')
            return "ENEMY";
        if (flames[5] == 'S')
            return "SISTER";
        return result;
    }
    public static void main(String a[]) {
        String k1 = "Prashant";
        String k2 = "Shruti P";
        String val = new MatchFinder().matchfinder(k1, k2);
        System.out.println(val);
    }
}

Output:
FRIEND