SpringMVC搭建

說明:
1、項目通過maven來創建,
2、開發工具使用Intellij
3、主要內容是 spring+SpingMVC 

SpringMVC項目的一般開發流程(不包括業務層、持久層、以及數據庫內容)
1、創建javaweb項目
2、導入springmvc相關依賴包
3、配置web.cml配置文件
4、配置springmvc配置文件
5、配置controller


主要內容:

pom依賴包:

<dependencies>
  <!--junit-->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>
  <!-- 導入webmvc以後,系統,自動導入所有所需依賴 -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.14.RELEASE</version>
  </dependency>
  <!-- 導入servlet依賴 -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
  </dependency>
  <!-- 爲了方便mvc獲取json數據對象,可以導入jackson以下三個依賴 -->
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.4</version>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.4</version>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.4</version>
  </dependency>
</dependencies>

所有jar包:

文件結構:


文件配置

applicationContext:
applicationContext.xml文件用於spring項目的全局配置,包括數據源配置、sessionFactory配置、事務配置、註解配置(注入bean依賴)等

<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置組件掃描器,使用註解方式開發,不用配置daoservice -->
    <!--如果工程比較簡單,姐可以直接統配,如果裏賣弄文件機構較爲複雜,可以按需掃描文件-->
    <context:component-scan base-package="com.tsy"/>
    <!--<context:component-scan base-package="com.eduask.entity,com.eduask.dao,com.eduask.service,com.eduask.controller">

    <!- 數據源 -->
    <!--<bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>-->

    <!-- 配置session工廠 -->
    <!--<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>-->

    <!-- 事務管理器 -->
    <!--<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>-->

    <!-- 配置AOP通知 -->
    <!-- <tx:advice id="txAdvice" transaction-manager="transactionManager">
         &lt;!&ndash; 配置事務屬性 &ndash;&gt;
         <tx:attributes>
             &lt;!&ndash; 添加事務管理的方法 &ndash;&gt;
             <tx:method name="save*" propagation="REQUIRED"/>
             <tx:method name="delete*" propagation="REQUIRED"/>
             <tx:method name="update*" propagation="REQUIRED"/>
             <tx:method name="select*" read-only="true"/>
         </tx:attributes>
     </tx:advice>-->

    <!-- 配置AOP,爲添加事務管理的操作配置AOP -->
    <!--<aop:config>
        &lt;!&ndash; 引入的Spring定義的事務通知,需要使用aop:advisor &ndash;&gt;
        &lt;!&ndash; 下面難 &ndash;&gt;
        <aop:advisor advice-ref="txAdvice"
                     pointcut="execution(* com.tsy.service.*.*(..))"
        />
    </aop:config>-->
</beans>

spring-mvc.xml
spring-mvc.xml 主要用於配置spring-mvc相關內容:比如視圖解析器、controller層的掃描配置、配置靜態資源的訪問權限、
<?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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       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.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 開啓mvc的註解驅動 -->
   <!-- <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean
                    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"
                    p:supportedMediaTypes="/"/>
        </mvc:message-converters>
    </mvc:annotation-driven>-->
    <!-- annotation-driven 控制器映射器和控制器適配器 ,用來控制@Controller處理http請求的方式-->
    <mvc:annotation-driven/>
    <!--以下配置可以註釋掉,系統默認就會有的-->
      <!--  <mvc:message-converters>&lt;!&ndash; register-defaults="true"表示使用默認的消息轉換器 &ndash;&gt;
            &lt;!&ndash; FastJson(Spring4.2x以上版本設置) &ndash;&gt;
            &lt;!&ndash; 使用@responsebody註解並且返回值類型爲String時,返回的string字符串帶有雙引號"{'user':'songfs'}",其原因是直接將string類型轉成了json字符串,應該在json解析器之前添加字符串解析器&ndash;&gt;
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
            &lt;!&ndash; FastJsonHttpMessageConverter4 使@ResponseBody支持返回Map<String,Object>等類型,它會自動轉換爲json&ndash;&gt;
            &lt;!&ndash; 需要返回json時需要配置 produces = "application/json"。不需要再指定utf-8 &ndash;&gt;
            <bean id="fastJsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                &lt;!&ndash; 加入支持的媒體類型 &ndash;&gt;
                <property name="supportedMediaTypes">
                    <list>
                        &lt;!&ndash; 這裏順序不能反,一定先寫text/html,不然IE執行AJAX,返回JSON會出現下載文件 &ndash;&gt;
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                        <value>application/xml;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>-->
    <!-- 自動掃描controller包下的所有類,使其默認爲spring mvc的控制器 -->
    <context:component-scan base-package="com.tsy.controller"/>
    <!-- 對模型視圖名稱的解析,即在模型視圖名稱添加前後綴 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/pages/" p:suffix=".jsp"/>
    <!--另一種複雜寫法
    <property name="prefix" value="/jsp/"></property>
         <property name="suffix" value=".jsp"></property>
            -->
    <!-- 靜態資源訪問  -->
    <!--<mvc:resources location="/img/" mapping="/img/**" />
    <mvc:resources location="/js/" mapping="/js/**" />
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="WEB-INF/pages/" mapping="/page/**" />-->
    <!--<bean id="jsonConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </bean>
    <bean id="stringConverter"
          class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <bean
            class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="stringConverter" />
                <ref bean="jsonConverter" />
            </list>
        </property>
    </bean>-->
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <display-name>spring_mvc_demo</display-name>
    <!--定製默認首頁,一般可以設置爲登陸或者index-->
    <!--<welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>-->

    <!--springMVC的核心分發器-->
    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 指定Spring的配置文件 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- spring容器配置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!-- 注意,spring加載配置文件-->
        <param-value>
            classpath*:applicationContext.xml,
        </param-value>
    </context-param>

    <!-- spring容器監聽器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- charactor encoding -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

說明:配置文件的註釋部分,主要目的,在於,讓自己瞭解更多的相關內容,或者配置的多種方式,拓寬自己的知識面。  正式項目裏,可以去掉那些註釋部分

JSP頁面
index:

web-inf文件內容,拒絕客戶端直接訪問。  故,需要客戶端通過servlet請求,由服務端調用
1、js以及ajax等方法  2、寫java代碼腳本進行重定向(如下),οnlοad=“window.localtion.href='yourServlet'”

<%--
  Created by IntelliJ IDEA.
  User: TSY
  Date: 2018/4/15
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>index</title>
</head>
<body>
<h1>##########Hello World##############</h1>
<h2 style="color:blue;">開啓SpringMVC之旅</h2>
<%--<a href="test/toLogin">click</a>--%>
<%--index頁面自動跳轉至login頁面,或則實現boday標籤的初始化事件--%>
<%    //request.getRequestDispatcher("index_toLoging.action").forward(request,response);
    response.sendRedirect("toLogin");
%>
</body>
</html>
register頁面

<%--
  Created by IntelliJ IDEA.
  User: TSY
  Date: 2018/4/15
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>註冊</title>
</head>
<body>
<form action="reg4" method="post">
    <h1>用戶註冊</h1>
    賬號:<input type="text" name="userId"/><br/>
    密碼:<input type="password" name="userPw"><br/>
    姓名:<input type="text" name="userName"/><br/>
    年齡:<input type="text" name="userAge"/><br/>
    生日:<input type="text" name="userBrithday"/><br/>
    興趣愛好:
    <input type="checkbox" name="xqs" value="LOL"/>LOL
    <input type="checkbox" name="xqs" value="DOTA"/>DOTA
    <input type="checkbox" name="xqs" value="看電影"/>看電影
    <input type="submit" value="提交"/>
</form>
</body>
</html>
login頁面
<%--
  Created by IntelliJ IDEA.
  User: TSY
  Date: 2018/4/15
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login</title>
</head>
<body>
<a href="<%=request.getContextPath() %>toRegister">註冊</a>

<form action="query5.do" method="post">
    <input type="submit" value="查詢"/>
</form>
<br/>
<br/>
userId:${list[0].userPw}
<br/>
userName:${user3.userName}
userName:${user2.userName}
userName:${user1.userName}
</body>
</html>

後臺源碼
User實體類

controller層(核心內容)

package com.tsy.controller;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by TSY on:2018/4/15
 */
@Controller
public class TestController {
    /*
     * 如果需要頁面的安全訪問,web-inf下,則需要通過servlet的服務端代碼。來實現跳轉
     */

    /**
     * 訪問內部資源(WEB-INF下)
     * 默認跳轉至登陸頁面
     *
     * @return "login"
     */
    @RequestMapping({"toLogin", "home"})
    public String toLogin() {
        return "login";
    }

    /**
     * 註冊頁面跳轉
     *
     * @return "register"
     */
    @RequestMapping("toRegister")
    public String toRegister() {
        return "register";
    }

    /**
     * 通過HttpServletRequest 獲取頁面數據  request.getParameter 再實現頁面跳轉
     */
    @RequestMapping("getParameterFromJSP")
    public String demo1(HttpServletRequest request) {
        String userId = request.getParameter("userId");
        String userPw = request.getParameter("userPw");
        String userAge = request.getParameter("userAge");
        String userBrithday = request.getParameter("userBrithday");
        String xqs = request.getParameter("xqs");
        System.out.println("賬號:" + userId);
        System.out.println("密碼:" + userPw);
        System.out.println("年紀:" + userAge);
        System.out.println("生日:" + userBrithday);
        System.out.println("興趣:" + xqs);
        return "login";
    }

    /**
     * 直接傳參數進來。此參數名要與頁面保持一致
     *
     * @param userId dd
     * @return dd
     */
    @RequestMapping("demo2")
    public String demo2(String userId, String userPw, String userAge) {
        System.out.println("姓名:" + userId);
        System.out.println("密碼:" + userPw);
        System.out.println("年紀:" + userAge);
        return "login";
    }

    /**
     * 獲取複選框的值:多個值/
     * RequestParam最好帶上去,不然可能接收異常
     */
    @RequestMapping("reg4")
    public String reg4(@RequestParam("xqs") String[] xqs) {

        for (String xq : xqs) {
            System.out.println("興趣:" + xq);
        }
        return "login";
    }

    /**
     * 通過對象來獲取頁面參數
     */
    @RequestMapping("reg5.do")
    public String reg5(User user) {

        System.out.println(user);

        return "login";
    }

    /**
     * 添加時間的屬性編輯器,
     * 設置完畢以後,系統會自動識別頁面傳過來的信息。如果信息是時間,則會自動轉換爲日期格式
     */
    @InitBinder
    public void InitBinder(ServletRequestDataBinder bin) {
        bin.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"), true));
    }


    /**
     * 利用ModelAndView方式,返回數據和視圖
     *
     * @return dd
     */
    @RequestMapping("/query2.do")
    public ModelAndView queryUser2() {
        User u1 = new User("tom1", "123");
        User u2 = new User("tom2", "123");
        User u3 = new User("tom3", "123");

        //model
        Map<String, Object> map = new HashMap<>();
        map.put("user1", u1);
        map.put("user2", u2);
        map.put("user3", u3);
        return new ModelAndView("login", map);
    }

    /**
     * request.setAttribute的方式,返回數據和視圖
     * 利用${user3.userName},可以接收參數。
     * url後面的參數,在新的頁面你可以通過${param:username}接收
     *
     * @param request HttpServletRequest
     * @return 返回登陸頁  其實其本身有一個刷新頁面的動作
     */
    @RequestMapping("/query1.do")
    public String queryUser1(HttpServletRequest request) {

        String name = "張三";
        request.setAttribute("name", name);
        User u3 = new User("tom3", "123");
        request.setAttribute("user", u3);
        return "login";
    }

    /**
     * Map模式,返回數據和視圖
     *
     * @param map aa
     * @return aa
     */
    @RequestMapping("/query3.do")
    public String queryUser3(Map<String, Object> map) {
        User u3 = new User("tom344", "12344");
        map.put("user3", u3);
        return "login";
    }

    /**
     * model模式返回數據和視圖
     *
     * @param model aa
     * @return aa
     */
    @RequestMapping("/query4.do")
    public String queryUser4(Model model) {
        User u3 = new User("tom3", "123");
        model.addAttribute("user4", u3);
        return "login";
    }

    /**
     * Model模式返回List數據和視圖
     *
     * @param model aa
     * @return aa
     */
    @RequestMapping("/query5.do")
    public String queryUser5(Model model) {
        User u1 = new User("tom1", "123");
        User u2 = new User("tom2", "123");
        User u3 = new User("tom3", "123");
        List<User> list = new ArrayList<>();
        list.add(u3);
        list.add(u2);
        list.add(u1);
        model.addAttribute("list", list);
        return "login";
    }

    /**
     * 比較原始的一種方式將後臺數據傳給頁面,可以通過
     * PrintWriter out = response.getWriter();這種方式
     *
     * @param useId useId
     * @param response response
     */
    @RequestMapping("ajax1.do")
    public void ajax1(String useId, HttpServletResponse response) {
        try {
            System.out.println(useId);
            // 響應
            response.setContentType("text/html");
            response.setCharacterEncoding("utf-8");
            PrintWriter out = response.getWriter();
            if ("admin".equals(useId)) {
                out.println("對不起,您賬號已經被註冊,請從新輸入!");
            } else {
                out.println("恭喜你,賬號可以使用!");
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 利用ResponseBody,可以將對象自動按照json格式,傳給頁面。
     * 前提是,需要有jacksonjar包的依賴(通過註解方式,就不需要在mvc的配置文件進行過多的配置)
     * ResponseBody 將內容或對象作爲 HTTP 響應正文返回
     *
     * @param userId id
     * @return 返回給頁面一個User對象
     */
    @ResponseBody
    @RequestMapping("/ajax2.do")
    public User ajax2(String userId) {
        System.out.println(userId);
        User u1 = new User("tom1", "123");
        if ("1001".equals(userId)) {
            u1.setUserName("悟空");
            u1.setUserPw("321");
        } else {
            u1.setUserName("八戒");
            u1.setUserPw("412");
        }
        return u1;
    }

    /**
     *
     * @return List集合
     */
    @ResponseBody
    @RequestMapping("/ajax3.do")
    public List<User> ajax3() {
        List<User> list = new ArrayList<>();
        User u1 = new User("tom1", "123");
        User u2 = new User("tom2", "123");
        User u3 = new User("tom3", "123");
        list.add(u1);
        list.add(u2);
        list.add(u3);
        return list;
    }
    /**
     *
     * @return Map集合
     */
    @ResponseBody
    @RequestMapping("/ajax4.do")
    public Map<String,User> ajax4() {
        Map<String,User> map=new HashMap<>();
        User u1 = new User("tom1", "123");
        User u2 = new User("tom2", "123");
        User u3 = new User("tom3", "123");
        map.put("testList1",u1);
        map.put("testList2",u2);
        map.put("testList3",u3);
        return map;
    }
    /**
     *
     * @return Map集合2
     */
    @ResponseBody
    @RequestMapping("/ajax5.do")
    public Map<String,List<User>> ajax5() {
        Map<String,List<User>> map=new HashMap<>();
        List<User> list = new ArrayList<>();
        User u1 = new User("tom1", "123");
        User u2 = new User("tom2", "123");
        User u3 = new User("tom3", "123");
        list.add(u1);
        list.add(u2);
        list.add(u3);
        map.put("testList1",list);
        map.put("testList2",list);
        map.put("testList3",list);
        return map;
    }
}

遺留問題:
當在controller類上使用@RequestMapping("/test"),給定統一路徑時,只能有一個“/”下的動作聲明,動作跳轉異常(在方法上是同樣情況),
http://localhost:8080/test/test/torRegister ,即會出現一個重複的路徑名稱,導致訪問異常。 暫時還未解決。 只能不給他添加複雜的路徑


答:jsp頁面請求數據時,配置絕對路徑,不要配置相對路徑            218-05-26

注意點:
1、對於擁有日期屬性的對象,   springmvc傳對象進方法,需要通過initbinder設置日期格式,進行轉換。
2、springMVC原理:


發佈了33 篇原創文章 · 獲贊 26 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章