1. 程式人生 > 實用技巧 >servlet 讀取表單資料

servlet 讀取表單資料

SSM整合

本節要做的是進行SSM整合,為了穩妥一點,我決定先把SpringMVC的環境準備好,再加入MyBatis。

1.準備資料

create database nyf;
USE nyf;
 
CREATE TABLE category_ (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(32) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

USE nyf;
INSERT INTO category_ VALUES (null,'category1');
INSERT INTO category_ VALUES (null,'category2');

2.新建一個maven專案

  1. 新建一個名為SSM的maven專案。

  2. 一路下一步,建好之後目錄如下圖,只有main,需要手動新建一些包和檔案。

3.開始SpringMVC

  1. main目錄下新建java和resources目錄。java目錄下新建一個名為com.example.web的包,然後新建一個CategoryController類。resources目錄中新建一個springmvc.xml檔案。所有檔案內容見下文,新的目錄如下:

  2. 新增pom依賴如下:

    	<dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>5.2.9.RELEASE</version>
        </dependency>
    
  3. 編寫web.xml

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
      <display-name>Archetype Created Web Application</display-name>
      <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:springmvc.xml</param-value>
        </init-param>
      </servlet>
      <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
    </web-app>
    
    
  4. 編寫springmvc.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-3.2.xsd">
    
        <mvc:annotation-driven/>
    
        <!--自動掃描元件-->
        <context:component-scan base-package="com.example.*"></context:component-scan>
    
        <!-- 配置檢視解析器 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
    </beans>
    
  5. 編寫controller

    package com.example.web;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    public class CategoryController {
        @RequestMapping("/test")
        public String test(){
            System.out.println("測試");
            return "test";
        }
    }
    

test.jsp裡隨便寫點東西顯示就可以,比如就展示個字串“test”,測試用而已。然後瀏覽器輸入http://localhost:8080/ssm/test之後跳轉到test.jsp這個頁面顯示那個字串就算成功。

4.開始整合mybatis

在真正開始整合MyBatis之前,需要為操作資料庫做幾步準備工作。

  1. 編寫實體類

    package com.example.entity;
    
    public class Category {
        private int id;
        private String name;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "Category [id=" + id + ", name=" + name + "]";
        }
    
    }
    
  2. 準備編寫mapper介面,其實也就是dao層,這裡不需要寫實現類,訪問資料庫的SQL語句會寫在對映檔案中。

    package com.example.mapper;
    
    import com.example.entity.Category;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public interface CategoryMapper {
        Category getCategory(int id);
    }
    
  3. 編寫服務層

    package com.example.service;
    
    import com.example.entity.Category;
    import com.example.mapper.CategoryMapper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class CategoryService {
        @Autowired
        CategoryMapper categoryMapper;
    
        public Category getCategory(int id){
            return categoryMapper.getCategory(id);
        }
    }
    
  4. 編寫controller

    package com.example.web;
    
    import com.example.service.CategoryService;
    import org.springframework.beans.factory.annotation.Autowired;
    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.ResponseBody;
    
    @Controller
    public class CategoryController {
    
        @Autowired
        CategoryService categoryService;
    
        @RequestMapping("test/{id}")
        @ResponseBody
        public String test(@PathVariable int id){
            return categoryService.getCategory(id).toString();
        }
    
        @RequestMapping("/test")
        @ResponseBody
        public String test(){
            System.out.println("測試");
            return "test";
        }
    }
    
    

上邊1-4步準備程式碼看起來就跟一般訪問資料庫的準備工作差不多,第五步才十分明顯地跟MyBatis有關係對吧,接下來就要開始真正的整合mybatis步驟了。

  1. 修改pom檔案新增新的依賴,完整檔案如下:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <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/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>org.example</groupId>
      <artifactId>ssm</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>war</packaging>
    
      <name>ssm Maven Webapp</name>
      <!-- FIXME change it to the project's website -->
      <url>http://www.example.com</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>5.2.9.RELEASE</version>
        </dependency>
    
        <!-- 連線資料庫 -->
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.37</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>5.2.9.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>c3p0</groupId>
          <artifactId>c3p0</artifactId>
          <version>0.9.1.2</version>
        </dependency>
    
        <!-- mybatis -->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.3.0</version>
        </dependency>
    
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.2.3</version>
        </dependency>
      </dependencies>
    
      <build>
        <finalName>ssm</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
          <plugins>
            <plugin>
              <artifactId>maven-clean-plugin</artifactId>
              <version>3.1.0</version>
            </plugin>
            <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
            <plugin>
              <artifactId>maven-resources-plugin</artifactId>
              <version>3.0.2</version>
            </plugin>
            <plugin>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>3.8.0</version>
            </plugin>
            <plugin>
              <artifactId>maven-surefire-plugin</artifactId>
              <version>2.22.1</version>
            </plugin>
            <plugin>
              <artifactId>maven-war-plugin</artifactId>
              <version>3.2.2</version>
            </plugin>
            <plugin>
              <artifactId>maven-install-plugin</artifactId>
              <version>2.5.2</version>
            </plugin>
            <plugin>
              <artifactId>maven-deploy-plugin</artifactId>
              <version>2.8.2</version>
            </plugin>
          </plugins>
        </pluginManagement>
      </build>
    </project>
    
    
  2. 修改springmvc.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-3.2.xsd">
    
        <mvc:annotation-driven/>
    
        <!--自動掃描元件-->
        <context:component-scan base-package="com.example.*"></context:component-scan>
    
        <!-- 配置檢視解析器 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
    
    
        <!-- 2.資料庫連線池 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <!-- 配置連線池屬性 -->
            <property name="driverClass" value="com.mysql.jdbc.Driver" />
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/nyf?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=true&amp;serverTimezone=UTC" />
            <property name="user" value="root" />
            <property name="password" value="root" />
    
            <!-- c3p0連線池的私有屬性 -->
            <property name="maxPoolSize" value="30" />
            <property name="minPoolSize" value="10" />
            <!-- 關閉連線後不自動commit -->
            <property name="autoCommitOnClose" value="false" />
            <!-- 獲取連線超時時間 -->
            <property name="checkoutTimeout" value="10000" />
            <!-- 當獲取連線失敗重試次數 -->
            <property name="acquireRetryAttempts" value="2" />
        </bean>
    
        <!-- 3.配置SqlSessionFactory物件 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 注入資料庫連線池 -->
            <property name="dataSource" ref="dataSource" />
            <!-- 配置MyBaties全域性配置檔案:mybatis-config.xml -->
            <property name="configLocation" value="classpath:mybatis-config.xml" />
            <!-- 掃描entity包 使用別名 -->
            <property name="typeAliasesPackage" value="com.example.entity" />
            <!-- 掃描sql配置檔案:mapper需要的xml檔案 -->
            <property name="mapperLocations" value="classpath:mapping/*.xml" />
        </bean>
    
        <!-- 4.配置掃描Dao介面包,動態實現Dao介面,注入到spring容器中 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 注入sqlSessionFactory -->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
            <!-- 給出需要掃描Dao介面包 -->
            <property name="basePackage" value="com.example.mapper" />
        </bean>
    
    </beans>
    
  3. resources目錄下新建mybatis-config.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <!-- 配置全域性屬性 -->
        <settings>
            <!-- 使用jdbc的getGeneratedKeys獲取資料庫自增主鍵值 -->
            <setting name="useGeneratedKeys" value="true" />
    
            <!-- 使用列別名替換列名 預設:true -->
            <setting name="useColumnLabel" value="true" />
    
            <!-- 開啟駝峰命名轉換:Table{create_time} -> Entity{createTime} -->
            <setting name="mapUnderscoreToCamelCase" value="true" />
        </settings>
    </configuration>
    
    
  4. 編寫對映檔案CategoryMapper.xml,放在resources下的mapping資料夾下。

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.example.mapper.CategoryMapper">
    
        <select id="getCategory" resultType="com.example.entity.Category">
            select * from category_ where id = #{id}
        </select>
    
    </mapper>
    
  5. 完畢之後,目錄結構如下:

大功告成

啟動專案,瀏覽器輸入http://localhost:8080/ssm/test/1 ,然後顯示Category [id=1, name=category1]就是成功了。