Friday 4 October 2013

Internationalization(i18N) in Spring MVC

In this example we will learn i18N in Spring mvc.

for this we have to make properties file of languages which languages you want to implement in your application.

Here we make two properties files

1.  message_en.properties


  • msg.welcome=Welcome


2.  message_de.properties


  • msg.welcome=willkommen

Here we use english and german languages and put files into the resource folder.

Set the following  Spring configuration in spring-servlet.xml file.



<bean id="messageSource"
          class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
       
    </bean>
    <bean id="localeChangeInterceptor"
      class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="language" />
    </bean>
    <bean id="localeResolver"
      class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="en"/>
    </bean>
    <bean id="handlerMapping"
      class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="interceptors">
            <ref bean="localeChangeInterceptor" />
        </property>
    </bean>


put the above code into your dispatcher xml file.


JSP page includes link for the english and german languages and add the following lines into your jsp page



<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>

<a href="?language=en">English</a>  | <a href="?language=de">German</a>

See <h3><spring:message code="msg.welcome"/> language</h3>




Regards
Rajnikant Panchal

Read XML file in Java

In this tutorial we learn how to read xml file in java.

Here is the program to read a xml file from java.

we also call it to DOM parser.

ReadXml.java file


import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author rajnikant panchal
 */
public class ReadXml {

    public static void main(String[] args) {


        try {

            File xmlfile = new File("/root/Documents/college.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document parsedoc = db.parse(xmlfile);

            NodeList nodeList = parsedoc.getElementsByTagName("student");

            for (int i = 0; i < nodeList.getLength(); i++) {

                Node node = nodeList.item(i);


                if (node.getNodeType() == Node.ELEMENT_NODE) {

                    Element emnt = (Element) node;

                    System.out.println("Student id : " + emnt.getAttribute("stuId"));
                    System.out.println("First Name : " + emnt.getElementsByTagName("firstname").item(0).getTextContent());
                    System.out.println("Date of Birth : " + emnt.getElementsByTagName("dob").item(0).getTextContent());

                }
            }


        } catch (Exception e) {
            e.getMessage();
        }
    }
}



Regards,
Rajnikant Panchal

Thursday 3 October 2013

Tutorials

WelCome

Welcome to my hompage This is Rajnikant Panchal worked as Java Developer  since 1.6 year.

How to Count number of files and directories in folder

In this Example we learn counting files and directories in folder in Java

For this we should  know about the File class in Java


Here is the Example for that


import java.io.File;
import java.util.Scanner;

public class CountFileDirectories {

static int cnt=0;
 
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter File Path");
String str = in.next();

File file  = new File(str);

showDirectoryFile(file);
}

static void showDirectoryFile(File file)
{
cnt++;
for(int i=0;i<cnt;i++)
{
if(file.isFile())
{
System.out.println("           [This is File]" + file.getName());
}
else if(file.isDirectory())
{
System.out.println("[This is Directory]    " + file.getName());
File[] f = file.listFiles();
if(f!=null)
{
for (int j = 0; j < f.length; j++)
{
showDirectoryFile(f[j]);
}

}


}
}
cnt--;
}

}


here we use recursion function for counting files and directories 


Regards,

Rajnikant

How to Send Email from Jsp/Servlet.

Send a Simple Email from JSP

for that you have to add mail.jar into your web application project.

First of all you have to get following parameters from jsp to the servlet

String login=request.getParameter("your username");
String password=request.getParameter("your password");
String from = request.getParameter("from");
String to = request.getParameter("to");
String subject = request.getParameter("your subject");
String message = request.getParameter("your message");

in the above code we get necessary parameters from the jsp and set to the String.

following code is for the send email from the Java

                          Properties props = new Properties();

            props.put("mail.smtp.host", "smtp.gmail.com");
   
           Authenticator auth = new SMTPAuthenticator(login, password);

           Session session = Session.getInstance(props, auth);

           MimeMessage msg = new MimeMessage(session);
           msg.setText(message);
           msg.setSubject(subject);
           msg.setFrom(new InternetAddress(from));
           msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
           Transport.send(msg);


and finally you add following class to your servlet file


private class SMTPAuthenticator extends Authenticator {



       private PasswordAuthentication authentication;

       public SMTPAuthenticator(String login, String password) {
           authentication = new PasswordAuthentication(login, password);
       }

       protected PasswordAuthentication getPasswordAuthentication() {
           return authentication;
       }
   }

and done!!!

Regards,
Rajnikant

Java Swing Tutorial

Swing is used for creating a desktop application in Java its provide better GUI compare to AWT.

Swing is a primary GUI toolkit for the Java. It is a part of the JFC (Java Foundation Classes), which is an API for providing a graphical user interface for Java programs. 


Swing provides a native look and feel that emulates the look and feel of several platforms


let's start with the simple program in Swing.


creating sample form in Swing.



package sampleswing;

import java.awt.FlowLayout;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author rajnikant panchal
 */
public class JOptionTest {
    
    public static void main(String[] args) {
        
        String arr[] = {"cow","dog","lion","tiger"};
        
        JComboBox comboArr = new JComboBox(arr);
        JTextField txt1 = new JTextField("1234");
        JTextField txt2 = new JTextField("4567");
        
        JPanel panel = new JPanel(new FlowLayout());
        
        panel.add(combo);
        panel.add( new JLabel("Field 1:-"));
        panel.add(txt1);
        panel.add( new JLabel("Field 2:-"));
        panel.add(txt2);
        
        int result = JOptionPane.showConfirmDialog(null, panel,"Test",JOptionPane.OK_OPTION,JOptionPane.CANCEL_OPTION);
        
        if(result==JOptionPane.OK_OPTION){
            System.out.println(combo.getSelectedItem()+" "+ txt1.getText()+" "+ txt2.getText());
        }else{
            System.out.println("cancelled");
        }
            
    }
    

}


Here!!!

JComboBox is used for creating option tag in desktop application.
JTextField is add textfield in application.
JPanel is generic lightweight container for adding form field in application.


Regards,
Rajnikant Panchal.

How to fill Dynamic Dropdown list in Spring.

In this tutorial we will learn "how to fill dynamic dropdown list in spring and hibernate using ajax and Json".

Let us impletement this feature in Spring MVC application using Json and ajax.

For this we have to create following Java Class file


let's start example

Domain

1. CountryBean.java file

package com.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;


/**
 *
 * @author rajnikant panchal
 */
@Entity
@Table(name="country")
public class CountryBean {

    @Id
    @Column(name="countryId")
    @GeneratedValue
    private Integer countryId;
    
    @Column(name="countryName")
    private String countryName;
        
    
    public Integer getCountryId() {
        return countryId;
    }

    public void setCountryId(Integer countryId) {
        this.countryId = countryId;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    
}

  • In this we mapped country table and make getter and setter for variables.

2. StateBean.java file



package com.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 *
 * @author rajnikant panchal
 */
@Entity
@Table(name="state")
public class StateBean {
    
    
    @Id
    @Column(name="stateId")
    @GeneratedValue
    private Integer stateId;
    
    @Column(name="stateName")
    private String stateName;
    
    @ManyToOne
    @JoinColumn(name="countryId", insertable = false, updatable = false)
    private CountryBean country;
    
    @Column(name = "countryId")
    private Integer countryId;

    public Integer getCountryId() {
        return countryId;
    }

    public void setCountryId(Integer countryId) {
        this.countryId = countryId;
    }
    
    
    public Integer getStateId() {
        return stateId;
    }

    public void setStateId(Integer stateId) {
        this.stateId = stateId;
    }

    public String getStateName() {
        return stateName;
    }

    public void setStateName(String stateName) {
        this.stateName = stateName;
    }

    public CountryBean getCountry() {
        return country;
    }

    public void setCountry(CountryBean country) {
        this.country = country;
    }
    
        
}

  • In this we mapped state table and make getter and setter for variables and also defined countryId as foreign key.


DaoLayer

In this layer we create database accessing object and interact with database and create two method loadState and loadCountry.

StateDao.java file

package com.dao;

import com.bean.CountryBean;
import com.bean.StateBean;
import java.util.List;

/**
 *
 * @author rajnikant panchal
 */
public interface StateDao {
    
    public List<StateBean> loadState(Integer countryId);
    public List<CountryBean> listCountry123();
    
}


StateDaoImpl.java file

package com.dao;

import com.bean.CountryBean;
import com.bean.StateBean;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 * @author rajnikant panchal
 */
@Repository
public class StateDaoImpl implements StateDao {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }



@Override

public List<CountryBean> listCountry(){

        return getCurrentSession().createQuery("from CountryBean").list();
    }

@Override
public List<StateBean> loadState(Integer countryId) {

        return getCurrentSession().createQuery("from StateBean s where s.countryId=" + countryId + ")").list();

    }


}



ServiceLayer

In this layer we create one interface and one java file for defining method and accessing this method using dao object

StateService.java file

package com.service;

import com.bean.CountryBean;
import com.bean.StateBean;
import java.util.List;

/**
 *
 * @author root
 */
public interface StateService {
      
    public List<StateBean> loadState(Integer countryId);
    public List<CountryBean> listCountry();
    
}


StateServiceImpl.java file


package com.service;

import com.bean.CountryBean;
import com.bean.StateBean;
import com.dao.StateDao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author rajnikant panchal
 */
@Service
public class StateServiceImpl implements StateService{

    @Autowired
    private StateDao stateDao;
    
    @Override
    @Transactional
    public List<StateBean> loadState(Integer countryId) {
        return stateDao.loadState(countryId);
    }

    @Override
    @Transactional
    public List<CountryBean> listCountry() {
        return stateDao.listCountry();
                
    }
 }



Controller Layer

We now create one Controller for interacting with jsp and dao.

StateController.java file


package com.controller;

import com.bean.StateBean;
import com.service.StateService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author rajnikant panchal
 */

@Controller
public class StateController {

    
    @Autowired
    private StateService stateService;
    private ModelAndView mav;

    @RequestMapping(value = "/loadCountry", method = RequestMethod.GET)
    public ModelAndView loadCountry() {

        mav = new ModelAndView();
        mav.addObject("countryList", stateService.listCountry());
        
        return mav;
    }

    @RequestMapping(value = "/loadStates", headers = "Accept=*/*", method = RequestMethod.GET)
    public @ResponseBody
    List<StateBean> loadStates(@RequestParam(value = "countryId", required = true) Integer countryId) throws IllegalStateException {

        //Specify the returning object you want here
        return stateService.loadState(countryId);
    }
}


ViewLayer 

In this layer we define jsp.

index.jsp


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    </head>
    <script>
        
        $(document).ready(
        function() {

            $('#countryId').change(
            function() {
                
                $.getJSON('loadStates.htm', {
                    countryId : $(this).val(),
                    ajax : 'true'
                }, function(data) {
                    
                    var html = '<option value="">----Select State----</option>';
                    var len = data.length;
      
                    for ( var i = 0; i < len; i++) {
                        html += '<option value="' + data[i].stateId + '">' + data[i].stateName + '</option>';
                    }
                    html += '</option>';
   
                    $('#stateId').html(html);
                });
            });
            
        });
        
    </script>

    <body>

        <h3>Countries</h3>

        <table class="data">
            
            <tr>
                <td>Country-Name</td>
                <td>
                    <select id="countryId" name="countryId">
                        <option value="">Select Country</option> 
                        <c:forEach items="${countryList}" var="country">
                            <option   value="${country.countryId}"  >${country.countryName}</option>
                        </c:forEach>
                    </select>
                </td>
            </tr>

            <tr>
                <td>State-Name</td>
                <td>
                    <select  id="stateId">
                        <option value="">Select State</option> 
                    </select>
                </td>
            </tr>                    
        </table>
    </body>
</html>



after creating above class files you have to 
set annotation configuration in spring-servlet.xml file.
jdbc.properties file for database connection.
set hibernate configuration file.

also you have to add following extra jars into project

jackson-core-asl-1.9.7.jar
jackson-mapper-asl-1.9.7.jar
mysql-connector-java-5.1.21.jar


Regards
Rajnikant Panchal