Friday 23 March 2012

Spring's DispatcherServlet

Spring's DispatcherServlet do more than just dispatches requests to controllers. It is completely integrated with the Spring IoC container and as such allows you to use every other feature that Spring has.



The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base class), and as such is declared in the web.xml of your web application. Requests that you want the DispatcherServlet to handle will have to be mapped using a URL mapping in the same web.xml file. This is standard J2EE servlet configuration.

code eg:

<web-app>

    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

</web-app>
 
In a application there can be more than one DispatcherServlet defined 
and each DispatcherServlet have its own WebApplicationContest.

The framework will, on initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).
 
The WebApplicationContext is an extension of the plain ApplicationContext
that has some extra features necessary for web applications. It differs 
from a normal ApplicationContext in that it is capable of resolving themes
and that it knows which servlet it is associated with. The WebApplicationContext
is bound in the ServletContext.
 
The Spring DispatcherServlet has a couple of special beans it uses in 
order to be able to process requests and render the appropriate 
views. These beans are included in the Spring framework and can be
configured in the WebApplicationContext, just as any other bean would
be configured. 

1.  Controllers
2. Handler mappings
3. View resolvers
4. Locale resolver
5. Theme resolver
6. multipart file resolver
7. Handler exception resolver(s) 

Thursday 22 March 2012

Spring MultiActionController

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>MultiActionController</display-name>

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>

---------------------------------------------------------------------


dispatcher-servlet.xml





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

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"><value>/WEB-INF/jsp/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
<bean name="/*.html" class="lnt.infotech.spring.MultiActionControllerExample" />

</beans>

---------------------------------------------------------------------



index.jsp







<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Success Page</title>
</head>
<body>
<h4>Multi Action Controller Example</h4>

<a href="add.html">Add</a>
<br />

<a href="update.html">Update</a>
<br />

<a href="edit.html">Edit</a>
<br />

<a href="remove.html">Remove</a>
</body>
</html>


In the above code as you can see we have given the url as add.html, update.html, edit.html, remove.html but we have given the common bean for all the four url i.e "/*.html". which passes the control to the "MultiActionControllerExample" controller. In this controller we have extended to MultiActionController class given by spring. Due to this the controller search for the url named method (eg. add, update, edit, remove) and executes it respectively when ever called.

-------------------------------------------------------------------------

MultiActionControllerExample


package lnt.infotech.spring;



import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.multiaction.MultiActionController;



public class MultiActionControllerExample extends MultiActionController {

  

  public ModelAndView add(HttpServletRequest request,

  HttpServletResponse response) throws Exception {

  return new ModelAndView("showmessage", "message", "Add method called");

  }  

  public ModelAndView update(HttpServletRequest request,

  HttpServletResponse response) throws Exception {

  return new ModelAndView("showmessage", "message", "Update method called");

  }

  public ModelAndView edit(HttpServletRequest request,

  HttpServletResponse response) throws Exception {

  return new ModelAndView("showmessage", "message", "Edit method called");

  }

  public ModelAndView remove(HttpServletRequest request,

  HttpServletResponse response) throws Exception {

  return new ModelAndView("showmessage", "message", "Remove method called");

  }

}

-------------------------------------------------------------------------------



showmessage.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Success Page</title>
</head>
<body>
${message}
</body>
</html>


In the  above code ${message} is accessing the message set by the controller and displaying it.

--------------------------------------------------------------------------------

Jars required
----------------
1. commons-logging.jar
2. jstl.jar
3. mail.jar
4. spring-webmvc.jar
5. spring.jar
6. standard.jar
---------------------------------------------------------------------

project layout




Monday 19 March 2012

Spring email setting with attachment facility

Web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>ReportGeneration</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>


<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>

</web-app>

---------------------------------------------------------------------

springapp-servlet.xml

In the below settings, please change the username and password with your email ID and password. In the bean "customeMailMessage" please change the "from" and "to" property to your email ID and email ID in which the email has to be sent. Please note both the property can be dynamically set in the code as well.



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

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<!-- the application context definition for the springapp DispatcherServlet -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp"></property>
</bean>

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="your@emailid.com" />
<property name="password" value="password" />

<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>

<bean id="eMail" class="com.lnt.infotech.EMail">
<property name="mailSender" ref="mailSender" />
<property name="simpleMailMessage" ref="customeMailMessage" />
</bean>

<bean id="customeMailMessage" class="org.springframework.mail.SimpleMailMessage">

<property name="from" value="your@emailid.com" />
<property name="to" value="reciever@emailid.com" />
<property name="subject" value="Testing Subject" />
<property name="text">
<value>
<![CDATA[
Dear %s,
Mail Content : %s
]]>
</value>
</property>
</bean>

</beans>

In the above bean "eMail" configuration, two property marked in background colour green is Dependency Injection where we are injecting the configuration values into the class com.lnt.infotech.EMail.



---------------------------------------------------------------------

SendEmail.java

package com.lnt.infotech;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SendEmail {

public static void main(String[] args) {
System.out.println("--------Start---------");
ApplicationContext context = new ClassPathXmlApplicationContext("springapp-servlet.xml");

EMail mm = (EMail) context.getBean("eMail");
mm.sendMail("Prajith", "This is text content");

}
}



In the above code we are just getting the object of class EMail.java from the WebApplicationContext.xml(spring-app.xml) and accessing the method sendMail.


----------------------------------------------------------------------

EMail.java

package com.lnt.infotech;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class EMail {
private JavaMailSender mailSender;
private SimpleMailMessage simpleMailMessage;

public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
this.simpleMailMessage = simpleMailMessage;
}

public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}

public void sendMail(String dear, String content) {
System.out.println("sendMail");
MimeMessage message = mailSender.createMimeMessage();

try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);

helper.setFrom(simpleMailMessage.getFrom());
helper.setTo(simpleMailMessage.getTo());
helper.setSubject(simpleMailMessage.getSubject());
helper.setText(String.format(simpleMailMessage.getText(), dear,
content));

FileSystemResource file = new FileSystemResource("/Users/pkomalac/Downloads/unix.pdf");
helper.addAttachment(file.getFilename(), file);

} catch (MessagingException e) {
throw new MailParseException(e);
}
mailSender.send(message);
}
}



---------------------------------------------------------------------


Required jar

1. commons-logging.jar
2. jstl.jar
3. mail.jar
4. spring-webmvc.jar
5. spring.jar
6. standard.jar

---------------------------------------------------------------------

Project Structure