SpringMVC-XML

工具

Spring
Maven 3

Maven Dependency

<properties>
        <spring.version>3.0.5.RELEASE</spring.version>
    </properties>

    <dependencies>

        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

    </dependencies>
```xml

### JAXB注解Model
```java
package com.mkyong.common.model;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "coffee")
public class Coffee {

    String name;
    int quanlity;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getQuanlity() {
        return quanlity;
    }

    @XmlElement
    public void setQuanlity(int quanlity) {
        this.quanlity = quanlity;
    }

    public Coffee(String name, int quanlity) {
        this.name = name;
        this.quanlity = quanlity;
    }

    public Coffee() {
    }

}

XMLController

package com.mkyong.common.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mkyong.common.model.Coffee;

@Controller
@RequestMapping("/coffee")
public class XMLController {

    @RequestMapping(value="{name}", method = RequestMethod.GET)
    public @ResponseBody Coffee getCoffeeInXML(@PathVariable String name) {

        Coffee coffee = new Coffee(name, 100);

        return coffee;

    }

}

输出

<coffee>
    <name>arabica</name>
    <quantity>100</quantity>
</coffee>
Advertisements

SpringMVC-View Resolver

InternalResourceViewResolver

Controller
//...
public class WelcomeController extends AbstractController{

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        ModelAndView model = new ModelAndView(&quot;WelcomePage&quot;);

        return model;
    }
}
InternalResourceViewResolver配置
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

   &lt;bean 
   class=&quot;org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping&quot; &gt;&lt;/bean&gt;

    &lt;!-- Register the bean --&gt;
    &lt;bean class=&quot;com.mkyong.common.controller.WelcomeController&quot; &gt;&lt;/bean&gt;

    &lt;bean id=&quot;viewResolver&quot;
              class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot; &gt;
              &lt;property name=&quot;prefix&quot;&gt;
                  &lt;value&gt;/WEB-INF/pages/&lt;/value&gt;
               &lt;/property&gt;
              &lt;property name=&quot;suffix&quot;&gt;
                 &lt;value&gt;.jsp&lt;/value&gt;
              &lt;/property&gt;
        &lt;/bean&gt;

&lt;/beans&gt;
解析结果

prefix + view name + suffix = /WEB-INF/pages/WelcomPage.jsp

XmlViewResolver

根据xml文件中配置进行解析
默认文件位置: /WEB-INF/views.xml,
自定义文件位置:

&lt;beans ...&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.view.XmlViewResolver&quot;&gt;
       &lt;property name=&quot;location&quot;&gt;
        &lt;value&gt;/WEB-INF/spring-views.xml&lt;/value&gt;
       &lt;/property&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
配置View Beans
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    &lt;bean id=&quot;WelcomePage&quot;
        class=&quot;org.springframework.web.servlet.view.JstlView&quot;&gt;
        &lt;property name=&quot;url&quot; value=&quot;/WEB-INF/pages/WelcomePage.jsp&quot; &gt;&lt;/property&gt;
    &lt;/bean&gt;

&lt;/beans&gt;
配置XmlViewResolver
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

   &lt;bean 
   class=&quot;org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping&quot; &gt;&lt;/bean&gt;

    &lt;!-- Register the bean --&gt;
    &lt;bean class=&quot;com.mkyong.common.controller.WelcomeController&quot; &gt;&lt;/bean&gt;

    &lt;bean class=&quot;org.springframework.web.servlet.view.XmlViewResolver&quot;&gt;
       &lt;property name=&quot;location&quot;&gt;
           &lt;value&gt;/WEB-INF/spring-views.xml&lt;/value&gt;
       &lt;/property&gt;
    &lt;/bean&gt;

&lt;/beans&gt;
完成Controller
public class WelcomeController extends AbstractController{

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        ModelAndView model = new ModelAndView(&quot;WelcomePage&quot;);

        return model;
    }
}

ResourceBundleViewResolver

根据xml文件中配置进行解析
默认文件位置: classpath 根目录下views.properties,
自定义文件位置:

&lt;beans ...&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.view.ResourceBundleViewResolver&quot;&gt;
        &lt;property name=&quot;basename&quot; value=&quot;spring-views&quot; &gt;&lt;/property&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
配置View Beans

spring-views.properties

WelcomePage.(class)=org.springframework.web.servlet.view.JstlView
WelcomePage.url=/WEB-INF/pages/WelcomePage.jsp
配置ResourceBundleViewResolver
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

  &lt;bean 
  class=&quot;org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping&quot; &gt;&lt;/bean&gt;

    &lt;!-- Register the bean --&gt;
    &lt;bean class=&quot;com.mkyong.common.controller.WelcomeController&quot; &gt;&lt;/bean&gt;

    &lt;bean class=&quot;org.springframework.web.servlet.view.ResourceBundleViewResolver&quot;&gt;
        &lt;property name=&quot;basename&quot; value=&quot;spring-views&quot; &gt;&lt;/property&gt;
    &lt;/bean&gt;

&lt;/beans&gt;
完成Controller
public class WelcomeController extends AbstractController{

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        ModelAndView model = new ModelAndView(&quot;WelcomePage&quot;);

        return model;
    }
}

多个Resolver配置方式

&lt;beans ...&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.view.XmlViewResolver&quot;&gt;
         &lt;property name=&quot;location&quot;&gt;
            &lt;value&gt;/WEB-INF/spring-views.xml&lt;/value&gt;
         &lt;/property&gt;
         &lt;property name=&quot;order&quot; value=&quot;0&quot; &gt;&lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean class=&quot;org.springframework.web.servlet.view.ResourceBundleViewResolver&quot;&gt;
         &lt;property name=&quot;basename&quot; value=&quot;spring-views&quot; &gt;&lt;/property&gt;
         &lt;property name=&quot;order&quot; value=&quot;1&quot; &gt;&lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;viewResolver&quot;
          class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot; &gt;
              &lt;property name=&quot;prefix&quot;&gt;
                 &lt;value&gt;/WEB-INF/pages/&lt;/value&gt;
              &lt;/property&gt;
              &lt;property name=&quot;suffix&quot;&gt;
                 &lt;value&gt;.jsp&lt;/value&gt;
              &lt;/property&gt;
          &lt;property name=&quot;order&quot; value=&quot;2&quot; &gt;&lt;/property&gt;
        &lt;/bean&gt;
&lt;/beans&gt;

优先级顺序

XmlViewResolver --&gt; ResourceBundleViewResolver --&gt; InternalResourceViewResolver

SpringMVC-Controller

Group Action

一个Controller中多个action

package com.mkyong.common.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CustomerController{

    @RequestMapping(&quot;/customer/add.htm&quot;)
    public ModelAndView add(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        return new ModelAndView(&quot;CustomerAddView&quot;);

    }

    @RequestMapping(&quot;/customer/delete.htm&quot;)
    public ModelAndView delete(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        return new ModelAndView(&quot;CustomerDeleteView&quot;);

    }

    @RequestMapping(&quot;/customer/update.htm&quot;)
    public ModelAndView update(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        return new ModelAndView(&quot;CustomerUpdateView&quot;);

    }

    @RequestMapping(&quot;/customer/list.htm&quot;)
    public ModelAndView list(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        return new ModelAndView(&quot;CustomerListView&quot;);

    }
}

Return ModelAndView

SpringMVC Mapping

BeanNameUrlHandlerMapping

spring 默认使用的HandlerMapping实现,通过bean配置实现url转发

ControllerClassNameHandlerMapping

启用这个HandlerMapping后,spring采用约定方式实现url转发

<br /> 

 

 

WelcomeController -> /welcome*
HelloGuestController -> /helloguest*
/helloGuest匹配/helloguest错误

Case sensitive
配置启用caseSensitive属性

<br /> 

 

 

WelcomeController -> /welcome*
HelloGuestController -> /helloGuest*

pathPrefix

<br /> 

 

 

WelcomeController -> /customer/welcome*
HelloGuestController -> /customer/helloGuest*

SimpleUrlHandlerMapping

通过url pattern配置转发
两种配置方式

welcomeControllerwelcomeControllerhelloGuestController

 

 
<br />/welcome.htm=welcomeController
/*/welcome.htm=welcomeController
/helloGuest.htm=helloGuestController
 

 

handler mapping priority

ControllerClassNameHandlerMapping配置所有符合约定的mapping
SimpleUrlHandlerMapping配置所有由特殊需求的mapping
然后指定order

<br />/index.htm=welcomeController
/welcome.htm=welcomeController
/main.htm=welcomeController
/home.htm=welcomeController
 

 

 

SpringMVC-HelloWorld – Annotation

工具

  1. Spring 3.2.13
  2. Maven 3
  3. JDK 1.6
  4. Tomcat 7
  5. Eclipse 4.4
  6. Boostrap 3

Project Structure

project structure
spring3-mvc HelloWorld project structure

Dependencies

&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;com.mkyong&lt;/groupId&gt;
&lt;artifactId&gt;spring3-mvc-maven-annotation-hello-world&lt;/artifactId&gt;
&lt;packaging&gt;war&lt;/packaging&gt;
&lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
&lt;name&gt;spring mvc&lt;/name&gt;

&lt;properties&gt;
&lt;jdk.version&gt;1.6&lt;/jdk.version&gt;
&lt;spring.version&gt;3.2.13.RELEASE&lt;/spring.version&gt;
&lt;jstl.version&gt;1.2&lt;/jstl.version&gt;
&lt;servletapi.version&gt;3.1.0&lt;/servletapi.version&gt;
&lt;/properties&gt;

&lt;dependencies&gt;

&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
&lt;version&gt;${spring.version}&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
&lt;artifactId&gt;jstl&lt;/artifactId&gt;
&lt;version&gt;${jstl.version}&lt;/version&gt;
&lt;/dependency&gt;

&lt;!-- compile only, deployed container will provide this --&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
&lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
&lt;version&gt;${servletapi.version}&lt;/version&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;

&lt;/dependencies&gt;

&lt;build&gt;
&lt;plugins&gt;

&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
&lt;version&gt;3.3&lt;/version&gt;
&lt;configuration&gt;
&lt;source&gt;${jdk.version}&lt;/source&gt;
&lt;target&gt;${jdk.version}&lt;/target&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;

&lt;!-- embedded Jetty server, for testing --&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.eclipse.jetty&lt;/groupId&gt;
&lt;artifactId&gt;jetty-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;9.2.11.v20150529&lt;/version&gt;
&lt;configuration&gt;
&lt;scanIntervalSeconds&gt;10&lt;/scanIntervalSeconds&gt;
&lt;webApp&gt;
&lt;contextPath&gt;/spring3&lt;/contextPath&gt;
&lt;/webApp&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;

&lt;!-- configure Eclipse workspace --&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-eclipse-plugin&lt;/artifactId&gt;
&lt;version&gt;2.9&lt;/version&gt;
&lt;configuration&gt;
&lt;downloadSources&gt;true&lt;/downloadSources&gt;
&lt;downloadJavadocs&gt;true&lt;/downloadJavadocs&gt;
&lt;wtpversion&gt;2.0&lt;/wtpversion&gt;
&lt;wtpContextName&gt;spring3&lt;/wtpContextName&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;

&lt;/plugins&gt;
&lt;/build&gt;

&lt;/project&gt;

Java Code

SpringWebConfig.java

配置Spring Bean,代替applicationContext.xml配置文件

package com.mkyong.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc //mvc:annotation-driven
@Configuration
@ComponentScan({ &quot;com.mkyong.web&quot; })
public class SpringWebConfig extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(&quot;/resources/**&quot;).addResourceLocations(&quot;/resources/&quot;);
}

@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix(&quot;/WEB-INF/views/jsp/&quot;);
viewResolver.setSuffix(&quot;.jsp&quot;);
return viewResolver;
}

}

MyWebInitializer.java

初始化并启动Spring,代替web.xml

package com.mkyong.servlet3;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.mkyong.config.SpringWebConfig;

public class MyWebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class&lt;?&gt;[] getServletConfigClasses() {
return new Class[] { SpringWebConfig.class };
}

@Override
protected String[] getServletMappings() {
return new String[] { &quot;/&quot; };
}

@Override
protected Class&lt;?&gt;[] getRootConfigClasses() {
return null;
}

}

HelloController.java

package com.mkyong.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {

@RequestMapping(value = &quot;/&quot;, method = RequestMethod.GET)
public String printWelcome(ModelMap model) {

model.addAttribute(&quot;message&quot;, &quot;Spring 3 MVC Hello World&quot;);
return &quot;hello&quot;;

}

@RequestMapping(value = &quot;/hello/{name:.+}&quot;, method = RequestMethod.GET)
public ModelAndView hello(@PathVariable(&quot;name&quot;) String name) {

ModelAndView model = new ModelAndView();
model.setViewName(&quot;hello&quot;);
model.addObject(&quot;msg&quot;, name);

return model;

}

}