SpringMVC(二)—— SpringMVC的基本使用(配置和註解實現)


這節主要講述 SpringMVC的基本使用,注意我用的是僞代碼,即並沒有與底層數據庫交互,主要在於SpringMVC的基本使用(配置和註解實現);

操作步驟:

  1. 引入依賴(主要是Spring核心包、SpringMVC相關的包);
  2. 配置和開發(配置:前端控制器、處理器映射器、處理器適配器、配置視圖解析器,開發:開發Handler、開發視圖);
  3. 部署到服務器上(Tomcat、Jetty);

配置實現

一、引入依賴

Spring的核心包前面Spring已經介紹過了(Spring(一)),所以這裏只寫SpringMVC的:

   <!--SpringMVC相關-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>

二、配置和開發

1、創建bean類、開發Handler:

創建bean類Student:

public class Student {
    private int SID;
    private String Sname;
    private String Ssex;
    private int Age;
    //get、set方法,toString方法
}

開發Handler:

public class ControllerTest1 implements Controller {
    /**
     * Handler必須實現org.springframework.web.servlet.mvc.Controller接口
     * 並且實現handleRequest方法
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     * @throws Exception
     */
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //查詢
        List<Student> list = new ArrayList<>();
        Student student1 = new Student();
        student1.setSID(1);
        student1.setSname("張三");
        student1.setSsex("男");
        student1.setSage(22);
        Student student2 = new Student();
        student2.setSID(2);
        student2.setSname("小麗");
        student2.setSsex("女");
        student2.setSage(21);
        list.add(student1);
        list.add(student2);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("students",list);

        //邏輯視圖名
        modelAndView.setViewName("jsp1");
        return modelAndView;
    }
}

2、開發視圖:

我是在WEB-INF下創建的jsp包裏面創建的jsp1.jsp:
在這裏插入圖片描述

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>用戶列表</title>
</head>
<body>

<table width="80%" border="1" align="center">
    <h1 align="center">用戶列表</h1>
    <tr>
        <%--<td>選擇</td>--%>
        <td>編號</td>
        <td>姓名</td>
        <td>性別</td>
        <td>年齡</td>
    </tr>


    <%-- students 要與後臺保持一致--%>
    <c:forEach items="${students }" var="student">
        <tr>
            <td>${student.SID }</td>
            <td>${student.sname} </td>
            <td>${student.ssex }</td>
            <td>${student.sage }</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

3、創建配置文件springmvc1.xml:

<?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">

    <!--通過配置實現-->

    <!--配置處理器映射器-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <!--配置處理器適配器-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
    <!--配置視圖解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前綴 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 後綴 -->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--管理handler-->
    <!--name="/springmvc1"   /springmvc1就是訪問的URL-->
    <bean name="/springmvc1" class="com.tulun1.controller.ControllerTest1"/>
</beans>

4、配置前端控制器

打開對應的web.xml(這個相當於main方法):
在這裏插入圖片描述

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>springmvc</display-name>

  <!--配置前端控制器-->
  <servlet>
    <!-- 第 3 步走到這-->
    <servlet-name>springmvc</servlet-name>
    <!--前端控制器的全路徑名-->
    <!-- 第 4 步走到這,交給DispatcherServlet解析-->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--初始化用的-->
    <init-param>
      <!--contextConfigLocation 配置處理器映射器、處理器適配器,如果不寫的話,
      默認在當前的web的同級目錄添加web-INF/servler名稱(就是外層的servlet-name對應的值)-servlet.xml-->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:配置實現/springmvc1.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <!-- 第 2 步走到這-->
    <servlet-name>springmvc</servlet-name>
    <!--設置訪問地址 交給DispatcherServlet解析-->
    <!-- 訪問這個地址之後第 1 步走到這-->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

三、部署項目

1、使用Jetty插件(這個比Tomcat輕量級):

        <!--引入jetty插件-->
          <plugin>
              <groupId>org.mortbay.jetty</groupId>
              <artifactId>maven-jetty-plugin</artifactId>
              <version>6.1.24</version>
              <configuration>
                  <connectors>
                      <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                          <port>8080</port>
                          <maxIdleTime>30000</maxIdleTime>
                      </connector>
                  </connectors>
                  <contextPath>/</contextPath>
              </configuration>
          </plugin>

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
點擊上圖那個按鈕啓動項目:
在這裏插入圖片描述
打開瀏覽器,輸入http://localhost:8080/springmvc1,訪問本地的springmvc1:
在這裏插入圖片描述
2、使用Tomcat,這是使用最廣的方式:
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
同樣的,啓動項目,訪問http://localhost:8080/springmvc1:
在這裏插入圖片描述
使用Tomcat的過程中,遇到了這個錯誤:
在這裏插入圖片描述
只要引入這個依賴就好了:

   <!--加入jstl包-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

註解實現

一、引入依賴

一樣的,略;

二、配置和開發

1、創建bean類、開發Handler:

創建bean類,還是那個Student類,略;

開發Handler:

@Controller
@RequestMapping(value = "/student")  //這個不要也可以,訪問http://localhost:8080/springmvc2就好
public class ControllerTest2 {
    @RequestMapping(value = "/springmvc2")  //這個相當於把http://localhost:8080/springmvc2和getStudentList方法綁定了
    public ModelAndView getStudentList(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) {
        //查詢
        List<Student> list = new ArrayList<>();
        Student student1 = new Student();
        student1.setSID(1);
        student1.setSname("張三");
        student1.setSsex("男");
        student1.setSage(22);
        Student student2 = new Student();
        student2.setSID(2);
        student2.setSname("小麗");
        student2.setSsex("女");
        student2.setSage(21);
        list.add(student1);
        list.add(student2);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("students",list);

        //邏輯視圖名
        modelAndView.setViewName("jsp1");
        return modelAndView;
    }

}

2、開發視圖

和上面一樣的,略;

3、創建配置文件:

這個有兩種寫法:

㈠springmvc2.xml:

<?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">


    <!--基於註解-->

    <!--處理器映射器-->
    <!--spring 3.1版本之後-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>

    <!--處理器適配器-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>

    <!--配置視圖解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置jsp的視圖解析類-->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <!-- 前綴 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 後綴 -->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 註解掃描 -->
    <context:component-scan base-package="com.tulun2.controller"/>
</beans>

㈡springmvc3.xml,這種更簡單,直接使用默認的配置:

<?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"
        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">


    <!--基於註解-->

    <!-- 註解掃描 -->
    <context:component-scan base-package="com.tulun2.controller"/>

    <!--自動掃描mvc相關的註解 適配器、映射器等,都有相關的默認配置-->
    <mvc:annotation-driven/>

    <!--配置視圖解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置jsp的視圖解析類-->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <!-- 前綴 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 後綴 -->
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

4、配置前端控制器:

還是web.xml,改一下使用的配置文件就好了:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>springmvc</display-name>

  <!--配置前端控制器-->
  <servlet>
    <!-- 第 3 步走到這-->
    <servlet-name>springmvc</servlet-name>
    <!--前端控制器的全路徑名-->
    <!-- 第 4 步走到這,交給DispatcherServlet解析-->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--初始化用的-->
    <init-param>
      <!--contextConfigLocation 配置處理器映射器、處理器適配器,如果不寫的話,
      默認在當前的web的同級目錄添加web-INF/servler名稱(就是外層的servlet-name對應的值)-servlet.xml-->
      <param-name>contextConfigLocation</param-name>
      <!--也可以見springmvc2.xml改成springmvc3.xml,都可以-->
      <param-value>classpath:註解實現/springmvc2.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <!-- 第 2 步走到這-->
    <servlet-name>springmvc</servlet-name>
    <!--設置訪問地址 交給DispatcherServlet解析-->
    <!-- 訪問這個地址之後第 1 步走到這-->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

三、部署服務器

略,

直接使用吧,啓動服務器,在瀏覽器輸入http://localhost:8080/student/springmvc2:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章