Friday, 17 August 2012

Spring web

Servlets and Naming

When defining a spring web project, requests come through to the DispatcherServlet. Therefor this must be defined in the WEB-INF/web.xml.

1
2
3
4
5
6
7
8
9
<servlet>
    <servlet-name>test</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
    
<servlet-mapping>
    <servlet-name>test</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

The important thing to note with this config is the name however. The name test is used and will result in spring looking for a WEB-INF/test-servlet.xml.

Components and Config

Now that the servlet is defined, the config that goes into spring can be configured. With this example i'm using component scan to pickup beans automatically and i'm specifying the view finder which i'll explain next.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<?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:mvc="http://www.springframework.org/schema/mvc"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

 <context:component-scan base-package="com.aphexmunky.web" />

 <mvc:annotation-driven />

 <mvc:resources location="/resources/" mapping="/resources/**" />

 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
  <property name="prefix" value="/WEB-INF/views/" />
  <property name="suffix" value=".jsp" />
 </bean>

</beans>

So the InternalResourceViewResolver points to locations where spring can find files. Should a bean return a String "home", it will then as part of it's view cycle go to /WEB-INF/views/home.jsp to find the content. The jsp could be anything really but here is an example of the bean.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package com.aphexmunky.web;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {
 
 @RequestMapping({"/","/home"})
 public String showHomePage(Map<String, Object> model) {
  model.put("hello", "Hello, World!");
  return "home";
 }
}

No comments:

Post a Comment