Wednesday, August 29, 2012

Spring MVC tutorial

Before Starting, I believe you must have basic idea about JAVA, SPRING and Spring MVC.

For Spring MVC : http://waheedtechblog.blogspot.in/2012/08/spring-mvc.html

In this tutorial , I will just tell you what are the basic thing that you need to start MVC.

Step 1 : Create a class 


@Controller
public class HelloWorld {
 
    @RequestMapping("/hello")
    public String helloWorld() {
         return = "Hello World, Spring 3.0!";
    }
}


1 . The class HelloWorld  has the annotation @Controller and @RequestMapping("/hello"). When Spring scans this class, it will recognize this bean as being a Controller bean for processing requests. 2 .The @RequestMapping annotation tells Spring that this Controller should process all requests beginning with /hello in the URL path.

Step 2. Mapping Spring MVC in WEB.xml

The entry point of Spring 3.0 MVC is the DispatcherServlet. DispatcherServlet is a normal servlet class which implements HttpServlet base class. Thus we need to configure it in web.xml.

<!-- ========================== -->
    <!-- Spring MVC: Core -->
    <!-- ========================== -->

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

<!-- This loads the root webapp Spring context -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:beans.xml</param-value>
    </context-param>
   
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

Note that I have mapped /rest/* url pattern with example DispatcherServlet. Thus any url with /rest/* pattern will call Spring MVC Front controller.

                  The REST call would be http://ip:port/rest/hello

If your controller class has some dependency which you have defined in your spring context file.Then you have to load it in <context-param>.(red line).
Once the DispatcherServlet is initialized, it will looks for a file name [servlet-name]-servlet.xml in WEB-INF folder of web application. I have created the file named spring-servlet.xml


3 . Spring Configuration file

Create a file spring-servlet.xml in WEB-INF folder and copy following content into it.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-3.0.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-2.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        ">

    <!-- ========================== -->
    <!-- Spring MVC: Core -->
    <!-- ========================== -->

    <context:annotation-config />
    <mvc:annotation-driven />
    <mvc:default-servlet-handler />

    <!-- class name of the controller or If you have package use component-scan -->
    <bean class="com.waheed.spring.hibernate.HelloWorld" />

 </beans>

The highlighted red line allow Spring to load the components from class. This will load our HelloWorld class.

Congratulation..!!! You are done here...

Download source code : https://github.com/abdulwaheed18/SpringMVC-Hibernate-Integration

Spring MVC

Spring MVC helps in building flexible and loosely coupled web applications. The Model-view-controller design pattern helps in seperating the business logic, presentation logic and navigation logic. Models are responsible for encapsulating the application data. The Views render response to the user with the help of the model object . Controllers are responsible for receiving the request from the user and calling the back-end services.


When a request is sent to the Spring MVC Framework the following sequence of events happen.
  • The DispatcherServlet first receives the request.
  • The DispatcherServlet consults the HandlerMapping and invokes the Controller associated with the request.
  • The Controller process the request by calling the appropriate service methods and returns a ModeAndView object to the DispatcherServlet. The ModeAndView object contains the model data and the view name.
  • The DispatcherServlet sends the view name to a ViewResolver to find the actual View to invoke.
  • Now the DispatcherServlet will pass the model object to the View to render the result.
  • The View with the help of the model data will render the result back to the user.

The new Servlet
•DispatcherServlet requests are mapped to @Controller methods
–@RequestMapping annotation used to define mapping rules
–Method parameters used to obtain request input
–Method return values used to generate responses
•Simplest possible @Controller

@Controller
public class HelloController {
    @RequestMapping(“/”)
    public @ResponseBody String hello() {
        return “Hello World”;
    }
}

Mapping Requests
•By path
–@RequestMapping(“path”)
•By HTTP method
–@RequestMapping(“path”,method=RequestMethod.GET)
–POST,PUT,DELETE,OPTIONS and TRACE are also supported
•By presence of query parameter
–@RequestMapping(“path”,method=RequestMethod.GET,params=“foo”)
–Negation also supported: params={“foo”,”!bar”}
•By presence of request header
–@RequestMapping(“path”,header=“content-type=text/*”)
–Negation also supported

For more details : Click Here

For tutorial: http://waheedtechblog.blogspot.in/2012/08/spring-mvc-tutorial.html
 



Sending Email Via JavaMail API Example

From last one month, My internet device is missing from my terrace. So, Mostly I use mobile to access my mail but accessing mail via mobile is very irritating thing because of the slow bandwidth. To send one single mail I have to wait till the mailbox get opened.

This is very simple way to send mail without opening your account. :)

This is the example to show you how to use JavaMail API method to send an email via Gmail SMTP server.

You need mail.jar library to run this code.


import java.util.Properties;

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

/**
 * @author abdul
 *
 */
public class SendEmail {

    public static void main(String[] args) {
       
        final String username="YOUR_USER_NAME"; //abdulwaheed18
        final String password="YOUR_PASSWORD";   //*******

        final String to = "SENDER_EMAIL"; // abdulwaheed143@yahoo.co.in
        final String from = "YOUR_EMAIL"; // abdulwaheed18@gmail.com

       
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        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(username,password);
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(to));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(from));
            message.setSubject("Hi");
            message.setText("Hi User,\n Surprise Message.\n Regards,\nWaheed");
            Transport.send(message);
            System.out.println(“Message sent Successfully");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}


Gmail SMTP Detail : http://support.google.com/mail/bin/answer.py?hl=en&answer=13287

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...