快速搭建SpringMVC4.0

快速搭建SpringMVC4.0

Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,从而在使用Spring进行WEB开发时,可以选择使用Spring的SpringMVC框架或集成其他MVC开发框架,如Struts1,Struts2等。

接下来就为搭建搭建一个简单的MVC4.0


准备环境: jdk 1.7,tomcat7.0


新建项目: 新建Maven工程,在Archetype类型中,选择“maven-archetype-webapp”。

快速搭建SpringMVC4.0_第1张图片


配置文件:

1. pom.xml配置

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>FirstgroupId>
  <artifactId>pcNewServerartifactId>
  <packaging>warpackaging>
  <version>0.0.1-SNAPSHOTversion>
  <name>pcNewServer Maven Webappname>
  <url>http://maven.apache.orgurl>

  <properties>  
      <spring.version>4.1.1.RELEASEspring.version>  
  properties>  

  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>3.8.1version>
      <scope>testscope>
    dependency>
  <dependency>  
        <groupId>org.springframeworkgroupId>  
        <artifactId>spring-coreartifactId>  
        <version>${spring.version}version>  
    dependency>  
    <dependency>  
        <groupId>org.springframeworkgroupId>  
        <artifactId>spring-webmvcartifactId>  
        <version>${spring.version}version>  
    dependency>  
    <dependency>  
        <groupId>org.springframeworkgroupId>  
        <artifactId>spring-beansartifactId>  
        <version>${spring.version}version>  
    dependency>  
    <dependency>  
        <groupId>org.springframeworkgroupId>  
        <artifactId>spring-contextartifactId>  
        <version>${spring.version}version>  
    dependency>  

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-aspectsartifactId>
        <version>4.1.1.RELEASEversion>
    dependency>

    <dependency>
        <groupId>org.perf4jgroupId>
        <artifactId>perf4jartifactId>
        <version>0.9.13version>
    dependency> 

    <dependency>  
        <groupId>jstlgroupId>  
        <artifactId>jstlartifactId>  
        <version>1.2version>  
    dependency>  
    <dependency>  
        <groupId>taglibsgroupId>  
        <artifactId>standardartifactId>  
        <version>1.1.2version>  
    dependency>  
  dependencies>
  <build>
    <finalName>pcNewServerfinalName>
  build>
project>

2. web.xml配置

  
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  

     <display-name>pcNewServerdisplay-name>  

     <filter>  
        <filter-name>encodingFilterfilter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>  
        <init-param>  
            <param-name>encodingparam-name>  
            <param-value>UTF-8param-value>  
        init-param>  
        <init-param>  
            <param-name>forceEncodingparam-name>  
            <param-value>trueparam-value>  
        init-param>  
    filter>  
    <filter-mapping>  
        <filter-name>encodingFilterfilter-name>  
        <url-pattern>/*url-pattern>  
    filter-mapping> 

     <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
    listener>  

    <context-param>
        <param-name>log4jConfigLocationparam-name>
        <param-value>/WEB-INF/classes/config/log4j.propertiesparam-value>
    context-param>

    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>
            /WEB-INF/classes/spring/applicationContext*.xml
        param-value>
    context-param>
    <servlet>  
        <servlet-name>springMVCservlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>  
        <init-param>  
            <param-name>contextConfigLocationparam-name>  
            <param-value>classpath*:spring/spring-context.xmlparam-value>  
        init-param>  
        <load-on-startup>1load-on-startup>  
    servlet>  

    <servlet-mapping>  
        <servlet-name>springMVCservlet-name>  
        <url-pattern>/url-pattern>  
    servlet-mapping>  
web-app>

3. applicationContext.xml配置


<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="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-4.1.xsd  
                        http://www.springframework.org/schema/mvc 
                        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
    <mvc:default-servlet-handler/>  
      
    <mvc:annotation-driven /> 
    <context:annotation-config /> 
    
    <context:component-scan base-package="com.labifenqi.pcNewServer" />
    
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
beans>

4. spring-context.xml配置

  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="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-4.1.xsd  
                        http://www.springframework.org/schema/mvc 
                        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
     
     <bean  
           class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
           <property name="messageConverters">  
               <list>  
                   <bean class="com.labifenqi.pcNewServer.base.UTF8StringHttpMessageConverter"/>  
               list>  
           property>  
    bean> 
    <context:annotation-config /> 
    <aop:aspectj-autoproxy />
    <context:component-scan base-package="com.labifenqi.pcNewServer">context:component-scan>  

    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">  
        <property name="viewClass"  
            value="org.springframework.web.servlet.view.JstlView" />  
        <property name="prefix" value="/WEB-INF/page" />  
        <property name="suffix" value=".jsp" />  
    bean>  
beans>

新建Controller类:


@Controller
public class HomeController {
    @RequestMapping(value="/home")
    public ModelAndView goHome(){
        Map<String ,String> map = new HashMap<String, String>();
        map.put("userName", "MVC4.1!");
        return new ModelAndView("/view",map);
    }
}

创建乱码处理类:

public class UTF8StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private final List availableCharsets;

    private boolean writeAcceptCharset = true;

    public UTF8StringHttpMessageConverter() {
        super(new MediaType("text", "plain", DEFAULT_CHARSET), MediaType.ALL);
        this.availableCharsets = new ArrayList(Charset.availableCharsets().values());
    }

    /**
     * Indicates whether the {@code Accept-Charset} should be written to any outgoing request.
     * 

Default is {@code true}. */ public void setWriteAcceptCharset(boolean writeAcceptCharset) { this.writeAcceptCharset = writeAcceptCharset; } @Override public boolean supports(Class clazz) { return String.class.equals(clazz); } @SuppressWarnings("rawtypes") @Override protected String readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException { Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType()); return FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset)); } @Override protected Long getContentLength(String s, MediaType contentType) { Charset charset = getContentTypeCharset(contentType); try { return (long) s.getBytes(charset.name()).length; } catch (UnsupportedEncodingException ex) { // should not occur throw new InternalError(ex.getMessage()); } } @Override protected void writeInternal(String s, HttpOutputMessage outputMessage) throws IOException { if (writeAcceptCharset) { outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets()); } Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType()); FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(), charset)); } /** * Return the list of supported {@link Charset}. * *

By default, returns {@link Charset#availableCharsets()}. Can be overridden in subclasses. * * @return the list of accepted charsets */ protected List getAcceptedCharsets() { return this.availableCharsets; } private Charset getContentTypeCharset(MediaType contentType) { if (contentType != null && contentType.getCharSet() != null) { return contentType.getCharSet(); } else { return DEFAULT_CHARSET; } } }

创建/WEB-INF/views/view.jsp,用来展现数据:

<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    <title>Hellotitle>  
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
  head>

  <body>
    hello ${userName }<br>
  body>
html>

启动项目访问对应的url就能看到页面上出现“hello MVC4.1!”的字样,说明你的springMVC4.1已经搭建完毕了!

你可能感兴趣的:(框架)