Spring MVC篇一、搭建Spring MVC框架


本項目旨在搭建一個簡單的Spring MVC框架,了解Spring MVC的基礎配置等內容。

一、項目結構
本項目使用idea intellij創建,配合maven管理。整體的目錄結構如圖:
其中java文件夾是sources文件夾,resources是資源文件夾。spring文件夾里是Spring上下文配置和Spring MVC配置文件。
 
需要注意的是,項目自動生成以后會有兩個web文件目錄,一個是web文件夾(我這里已經刪除了),另一個是默認的webapp文件夾。我這里使用默認的目錄,也就是說webapp文件夾。頁面文件都放在該目錄里面。
                                                                                         *如圖可配置默認的web文件默認路徑。*
二、配置文件
maven配置,添加各種依賴
省略,這個不是重點。需要注意的是,添加依賴的時候不能重復添加不同版本的包。
web.xml文件配置
首先,添加spring 上下文配置,指定Spring Context由classpath下的spring文件夾中的app-context.xml提供:
  1. <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/app-context.xml</param-value>
    </context-param>

    然后添加Spring監聽器:

  1. <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    接下來配置Spring MVC的dispatherservlet,同時配置該servlet要攔截的URL。

  1. <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/mvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- 配置要攔截的URL -->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>            

    最后,配置一個welcom-file-list。

web.xml全部的代碼如下:
  1. <?xml version="1.0" encoding="UTF-8"?>
    <web-appxmlns="http://java.sun.com/xml/ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"version="2.4"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
        <!-- spring context 配置文件 -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/app-context.xml</param-value>
        </context-param>
        <!-- spring 監聽器配置 -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <listener>
            <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
        </listener>
        <!--spring 防內存溢出監聽器 -->
        <listener>
            <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
        </listener>
        <!-- spring mvc servlet配置文件 -->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/mvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        </servlet>
        <!-- 配置要攔截的URL -->
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        <welcome-file-list>
        <welcome-file></welcome-file>
        </welcome-file-list>
    </web-app>            

    配置Spring MVC文件

這里主要配置自動注解、mvc資源引用、視圖解析器等
代碼如下:
  1. <?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">
    
        <mvc:resources location="/js/" mapping="/js/**"/>
    
        <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
        <mvc:annotation-driven/>
        <context:annotation-config/>
        <mvc:default-servlet-handler/>
    
        <!--添加component掃描,使package下面的注解生效 -->
        <context:component-scan base-package="com.wxspringmvc.controller"/>
    
        <!--添加頁面視圖解析器-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/page/"/>
            <property name="suffix" value=".jsp"/>
            <property name="contentType" value="text/html;charset=UTF-8"/>
        </bean>
    </beans>

    配置applicationContext.xml

這里主要是提供默認的上下文,不需要額外的配置,直接使用生成的文件就可以。代碼就省略了。
要注意的是,applicationContext.xml是一定要配置的。在web.xml文件中如果不配置,系統會自動到WEB-INF目錄下尋找。
View和Controller
這里使用一個簡單的用戶登錄,完成后在頁面顯示用戶名和密碼的流程來展示。
View:index.jsp
  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>請登錄</title>
    </head>
    <body>
    <h5>this is index.jsp</h5>
    <form action="/user/index" method="post">
      <p>用戶名:</p><input type="text" id="username" name="username">
      <p>密碼:</p><input type="password" id="password" name="password">
      <p><input type="submit" value="提交"></p>
    </form>
    </body>
    </html>

    表單使用post的方式提交到/user/index路徑。

Controller:UserController.java
  1. @Controller
    @RequestMapping(value = "/user")
    public class UserController {
        @RequestMapping(value = "/index" ,method= RequestMethod.POST)
        public ModelAndView userIndex(String username,String password){
            ModelAndView mav = new ModelAndView("user/success");
           
            mav.addObject("username",username);
            mav.addObject("password",password);
            return mav;
        }
    
    }

    這里可以添加一個簡單的校驗,如果用戶名和密碼有一個為空,則不能提交:

修改UserController.java的代碼如下:
  1. @Controller
    @RequestMapping(value = "/user")
    public class UserController {
        @RequestMapping(value = "/index" ,method= RequestMethod.POST)
        public ModelAndView userIndex(String username,String password){
            ModelAndView mav = new ModelAndView("user/success");
            if(!matchParams( username, password)){
                return new ModelAndView("/index");
            }
            mav.addObject("username",username);
            mav.addObject("password",password);
            return mav;
        }
    
        private boolean matchParams(String username,String password){
            if(isEmpty(username)||isEmpty(password))
                return false;
            else
                return true;
        }
    
        private boolean isEmpty(String s){
            if(s==null || "".equals(s))
                return true;
            else
                return false;
        }
    }

    View:登錄成功界面:success.jsp

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>用戶首頁</title>
      </head>
      <body>
    <p>用戶名:${username}</p>
    <p>密碼:${password}</p>
      </body>
    </html>

    效果展示

默認頁:
輸入不正確,提交結果:
輸入正確提交:
 
----------------------------------------------------------------------------------------------------------------------------
 
以上就是一個簡單的Spring MVC演示了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM