Mybatis

Mybatis(一) 基于XML映射文件实现数据的CRUD

本实验过程参考:

【mybatis xml】数据层框架应用–Mybatis(一) 基于XML映射文件实现数据的CRUD

项目工程截图:
在这里插入图片描述

Bug1:javaBean类的@Data无法使用

solution:

使用lombak

Bug2.1:mybatis-config.xml文件头缺少信息

description:

Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 16; 文档根元素 "configuration" 必须匹配 DOCTYPE 根 "null"

solution:

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

Bug2.2:找不到jdbc.properties

description:

Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource jdbc.properties

Bug2.3:mapper.xml文件头缺少信息

solution:

在mapper.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>

Bug2.4:数据库的时间问题

description:

### Error updating database.  Cause: java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
### Cause: java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

solution:

把jdbc.properties的:

jdbc.url=jdbc:mysql://localhost:3306/javaweb2_mybatis?characterEncoding=UTF-8

改为:

jdbc.url=jdbc:mysql://localhost:3306/javaweb2_mybatis?serverTimezone=UTC&characterEncoding=UTF-8

运行结果

在这里插入图片描述
数据库中插入的记录:
在这里插入图片描述

其它参考

IntelliJ IDEA 自定义创建类生成注释模板

Junit单元测试 | 注解和执行顺序

Mybatis(二) 基于注解实现数据的CRUD

本实验过程参考
项目工程截图:
在这里插入图片描述

注解技术介绍

MyBatis是一个XML驱动的框架,到了MyBatis 3,通过注解提供一种简单的方式来实现简单映射语句,而不会引起大量的开销。但Java注解限制了映射的表现和灵活。

以数据表user_info为例,基于注解实现数据CRUD的过程如下所示。

步骤(1)

将项目mybatis-1复制并命名为“mybatis-2”,再导入到MyEclipse开发环境中。

步骤(2)

将项目mybatis-3的com/ury/mybatis/mapper/userInfoMapper.xml文件删除,新建接口UserInfoMapperAnnotation.java。 代码如下:

package com.ury.mybatis.mapper;
import com.ury.mybatis.entity.UserInfo;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * @Author: URYWU
 * @Date: 2020/5/4
 * @Time: 16:16
 * @Email: ury@qq.com
 */
public interface UserInfoMapperAnnotation {
    
    @Insert(" insert into user_info(userName, passWord, regDate)\n" +
            "        values(#{userName},#{passWord}, #{regDate})")
    int addUserInfo(UserInfo userInfo);
    
    @Delete("delete from user_info where id = #{id}")
    int deleteUserInfo(Integer id);
    
    @Select("select * from user_info where id = #{id}")
    UserInfo getUserInfoById(Integer id);
    
    @Select("select * from user_info")
    List<UserInfo> getALLUserInfo();

    @Update("update user_info set userName = #{userName}, passWord = #{passWord}, regDate = #{regDate} where id = #{id}")
    int updateUserInfo(UserInfo userInfo);
}

步骤(3)

修改XML映射配置文件mybatis-config.xml

在mybatis-config.xml文件中,先将原先注册的userInfoMapper.xml文件删除或注释掉,再添加对接口UserInfoMapper的注册。如下所示:

<mappers>
<!--        <mapper resource="com/ury/mybatis/mapper/userInfoMapper.xml"/>-->
	<mapper class="com.ury.mybatis.mapper.UserInfoMapperAnnotation"/>
</mappers>

步骤(4)

修改测试类MybatisTest中的测试方法,并观察测试结果。

testAddUserInfo()方法、testGetUserInfoById()方法、testGetAllUserInfo()方法、testUpdateUserInfo()方法、testDeleteUserInfo()方法修改如下所示:

package com.ury.mybatis.mapper;

/**
 * 描述:测试mybatis的配置是否成功
 *
 * @author UryWu
 * @create 2020-05-02 11:03
 * @Email: ury@qq.com
 */

import com.ury.mybatis.mapper.UserInfoMapperAnnotation;
import com.ury.mybatis.entity.UserInfo;
import com.ury.mybatis.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;

import java.util.Date;
import java.util.List;


public class MybatisTest {


    @Test
    public void testAddUserInfo(){
        SqlSession sqlSession= MybatisUtils.getSession();
        UserInfo userInfo= new UserInfo("小明", "123", new Date());
        UserInfoMapperAnnotation userInfoMapper = sqlSession.getMapper(UserInfoMapperAnnotation.class);

        int i= userInfoMapper.addUserInfo(userInfo);
        System.out.println(i+ " record has inserted !");
//        sqlSession.commit();
//        sqlSession.close();
    }


    @Test
    public void testGetUserInfoById(){
        SqlSession sqlSession= MybatisUtils.getSession();
        UserInfoMapperAnnotation userInfoMapper = sqlSession.getMapper(UserInfoMapperAnnotation.class);
        System.out.println(userInfoMapper.getUserInfoById(1));
        System.out.println ("record has got !");
//        sqlSession.commit();
//        sqlSession.close();
    }

    @Test
    public void testGetAllUserInfo(){
        SqlSession sqlSession= MybatisUtils.getSession();
        UserInfoMapperAnnotation userInfoMapper = sqlSession.getMapper(UserInfoMapperAnnotation. class);
        List<UserInfo> uList = userInfoMapper.getALLUserInfo();
        System.out.println ("It has "+ uList.size() +"records!");
//        sqlSession.commit();
//        sqlSession.close();
    }

    @Test
    public void testUpdateUserInfo(){
        SqlSession sqlSession= MybatisUtils.getSession();
        UserInfoMapperAnnotation userInfoMapper = sqlSession.getMapper(UserInfoMapperAnnotation.class);
        //加载编号为7的用户
        UserInfo ui = userInfoMapper.getUserInfoById(8);
        //修改用户密码
        ui.setPassWord("123123");
        //执行更新操作
        int update = userInfoMapper.updateUserInfo(ui);
        System.out.println(ui);
    }

    @Test
    public void testDeleteUserInfo(){
        SqlSession sqlSession= MybatisUtils.getSession();
        UserInfoMapperAnnotation userInfoMapper = sqlSession.getMapper(UserInfoMapperAnnotation.class);
        int i= userInfoMapper.deleteUserInfo(1);
        System.out.println (i+ " record has deleted !");
//        sqlSession.commit();
//        sqlSession.close();
    }
}

Bug1:缺少无参构造器

description:

Cause: org.apache.ibatis.executor.ExecutorException: No constructor found in com.ury.mybatis.entity.UserInfo matching [java.lang.Integer, java.lang.String, java.lang.String, java.sql.Timestamp]

solution:

在你的UserInfo添加一个无参构造器就可以了。

public UserInfo() {
}

运行结果:

控制台:
在这里插入图片描述
数据库:
在这里插入图片描述

Mybatis(三) 关系映射之一对一关系映射

本实验过程参考

项目工程截图:
在这里插入图片描述

注意:

创建:adminDetailMapper.xml、adminInfoMapper.xml文件时注意添加文件头:

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

运行结果:

在这里插入图片描述

嵌套结果:
在这里插入图片描述

嵌套查询:
在这里插入图片描述

Mybatis(四)关系映射之一对多关系映射

参考
项目工程截图:
在这里插入图片描述
数据库添加的记录:
在这里插入图片描述
控制台输出:
在这里插入图片描述

Mybatis(五)整合Spring与MyBatis实现登录注册

参考来源

1)导入maven依赖项:

<?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>com.ury</groupId>
  <artifactId>digital-ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>digital-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>
    <spring.version>4.3.6.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>8.0.17</mysql.version>
    <mybatis.version>3.4.6</mybatis.version>

  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- spring -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.8</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <!-- log end -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
      <!--    lombok-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.16.10</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>digital-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)创建UserInfo实体类

先创建com.digital.pojo目录
然后创建UserInfo类

package com.digital.pojo;
import lombok.Data;

/**
 * 描述:实体类
 *
 * @author UryWu
 * @create 2020-05-04 14:23
 * @Email: ury@qq.com
 */

@Data
public class UserInfo {
    private int id;
    private String password;
    private String userName;

    public UserInfo() {
    }
}

3)Spring整合MyBatis

Spring整合MyBatis是在Spring配置文件applicationContext.xml中通过配置完成的,在src下创建此文件,在src目录下创建applicationContext.xml,依次配置1.数据源、2.配置SqlSessionFactoryBean、3.配置DataSourceTransactionManager(事务管理)、4.配置MapperScannerConfigurer

}配置MapperScannerConfigurer

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"

    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.2.xsd
    ">

<!--    配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///digital"/>
        <property name="user" value="root"/>
        <property name="password" value="1234"/>
        <property name="minPoolSize" value="5"/>
        <property name="maxPoolSize" value="10"/>
    </bean>

<!--    配置SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--        注入数据源-->
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:com.digital.mapping/*.xml"/>
    </bean>

<!--    配置mapper扫描器,配置mapper接口所在类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--        包扫描,配置MapperScannerConfigurer,basePackage属性指定Dao接口所在的包,Spring会自动查找其下的类或接口-->
        <property name="basePackage" value="com.digital.dao"/>
<!--        将sqlSessionFactory实例注入sqlSessionFactoryBeanName属性-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

<!--    配置事务管理,依赖于数据源-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--        使用本地实例,用ref-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

4)配置DAO层

在项目digital-ssm的src目录下创建包com.digital.dao,在包中创建接口UserInfoDAO,在UserInfoDAO接口中声明方法findUserInfoByCond,用于登录验证。

UserInfoDAO接口:

package com.digital.dao;

import com.digital.pojo.UserInfo;

/**
 * 描述:用户信息接口
 *
 * @author UryWu
 * @create 2020-05-04 15:00
 * @Email: ury@qq.com
 */
public interface UserInfoDao {
    public UserInfo getUserInfoByCond(UserInfo ui);
}

创建包com.digital.mapping,在包中创建映射文件userInfoMapper.xml

<?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">
<!--映射文件需要实现DAO接口里的方法,所以命名空间指定的是这个接口-->
<mapper namespace="com.digital.dao.UserInfoDao">
<!--select元素的id要和接口的方法名一致,所执行的查询针对我们的接口
    输入的参数是用户,(可以去看接口的getUserInfoByCond方法的输入参数),所以parameterType="com.digital.pojo.UserInfo
    返回的参数也是用户,所以resultType="com.digital.pojo.UserInfo">-->
    <select id="getUserInfoByCond" parameterType="com.digital.pojo.UserInfo" resultType="com.digital.pojo.UserInfo">
#         占位符#{}代表的是从输入的UserInfo类中取到的属性,user_info是数据库里的字段
        select * from user_info where userName=#{userName} and password=#{password}
    </select>
</mapper>

5)Service层开发

在项目digital-ssm中创建包com.digital.service,在包中创建接口UserInfoService,在UserInfoService接口中声明方法getUserInfoByCond,用于登录验证。

实际上这个接口和UserInfoDAO完全一样,除了名字:

UserInfoService接口:

package com.digital.service;

import com.digital.pojo.UserInfo;

/**
 * 描述:用户信息接口
 *
 * @author UryWu
 * @create 2020-05-04 15:00
 * @Email: ury@qq.com
 */
public interface UserInfoService {
    public UserInfo getUserInfoByCond(UserInfo ui);
}

创建UserInfoService接口的实现类UserInfoServiceImpl,存放在com.digital.service.impl包中,实现getUserInfoByCond方法:

UserInfoServiceImpl类:

package com.digital.service.impl;

import com.digital.dao.UserInfoDao;
import com.digital.pojo.UserInfo;
import com.digital.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 描述:用户信息服务接口的实现类
 *
 * @author UryWu
 * @create 2020-05-04 15:42
 * @Email: ury@qq.com
 */
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoDao userInfoDao;
    @Override
    public UserInfo getUserInfoByCond(UserInfo ui){
        return userInfoDao.getUserInfoByCond(ui);
    };
}

6)控制器开发

在项目src目录下创建包com.digital.controller,在包中创建类UserInfoController。这是SpringMVC的控制器

com.digital.controller.UserInfoController.java:

package com.digital.controller;

import com.digital.pojo.UserInfo;
import com.digital.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 描述:SpringMVC的控制器
 *
 * @author UryWu
 * @create 2020-05-04 15:45
 * @Email: ury@qq.com
 */
@Controller
@RequestMapping("/userinfo")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping("/login")
    public String login(UserInfo ui){
        UserInfo u = userInfoService.getUserInfoByCond(ui);
        if(u!=null && u.getUserName()!=null){
            return "index";
        }{
            return "redirect:/login.jsp";
        }
    }
}

7)Spring整合SpringMVC

首先创建SpringMVC的配置文件,然后在web.xml中配置整合。在项目src/main/resources目录下创建SpringMVC的配置文件springmvc.xml,记得resources目录右键Mark Resource as->Resources root,依次配置自动扫描的包;配置视图解析器;启用MVC注解驱动;配置允许对静态资源文件的访问。

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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"

    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.2.xsd
    ">
<!--    开启Spring的Bean自动扫描的基包-->
    <context:component-scan base-package="com.digital"/>
    
<!--    配置数据源-->
    <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/javaweb2_mybatis"/>
        <property name="user" value="root"/>
        <property name="password" value="1234"/>
        <property name="minPoolSize" value="5"/>
        <property name="maxPoolSize" value="10"/>
    </bean>

<!--    配置SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--        注入数据源-->
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:com.digital.mapping/*.xml"/>
    </bean>

<!--    配置mapper扫描器,配置mapper接口所在类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--        包扫描,配置MapperScannerConfigurer,basePackage属性指定Dao接口所在的包,Spring会自动查找其下的类或接口-->
        <property name="basePackage" value="com.digital.dao"/>
<!--        将sqlSessionFactory实例注入sqlSessionFactoryBeanName属性-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

<!--    配置事务管理,依赖于数据源-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--        使用本地实例,用ref-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

在web.xml文件中,依次配置ContextLoaderListener加载Spring配置文件、编码过滤器,防止Spring内存溢出监听器。配置SpringMVC的DispatcherServlet。

WEB-INF/web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
         version="2.5">
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <!-- 配置DispatcherServlet -->
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <!-- 指定spring mvc配置文件位置 不指定使用默认情况 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>
  <!-- ServLet 匹配映射 -->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--  解决乱码问题-->
  <filter>
    <filter-name>CharacterEncodingFilter</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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

8)创建页面

创建登录页login.jsp

<%--
  Created by IntelliJ IDEA.
  User: UryWu
  Date: 2020/4/20
  Time: 15:30
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>Login</title>
</head>
<body>
<form action="userinfo/login" method="post"><!-- 表单提交 -->
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <td>密码:</td>
        <td><input type="text" name="password"></td>
        <tr>
            <td><input type="submit" value="登录"></td>
            <td></td>
        </tr>
    </table>
</form>

</body>
</html>

编辑登录成功页success.jsp

<%--
  Created by IntelliJ IDEA.
  User: UryWu
  Date: 2020/5/4
  Time: 16:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success</title>
</head>
<body>

    <h3>登录成功!</h3>
    <a href="index.jsp">返回主页</a>
</body>
</html>

主页index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<html>
<head>
</head>
<body>
<h2>Hello World</h2>
    <a href="login.jsp">登录</a>
</body>
</html>

Bug1:数据库的url写错了

solution:

applicationContext.xml里的数据库的数据源配置改一下

<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/javaweb2_mybatis"/>

Bug2:找不到springmvc.xml文件

description:

严重: StandardWrapper.Throwable
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [springmvc.xml]; nested exception is java.io.FileNotFoundException: class path resource [springmvc.xml] cannot be opened because it does not exist

solution:

创建src/main/resources目录,在之下创建SpringMVC的配置文件springmvc.xml,记得resources目录右键Mark Resource as->Resources root

Bug3.1:无法注入UserInfoService,它不存在

description:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userInfoController': Unsatisfied dependency expressed through field 'userInfoService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.digital.service.UserInfoService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

solution:

@Autowired添加一个参数

@Autowired
private UserInfoService userInfoService;

改为:

@Autowired(required = false)
private UserInfoService userInfoService;

Bug3.2

description:

严重: Servlet.service() for servlet [dispatcherServlet] in context with path [/digital-ssm] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException

运行结果:

在这里插入图片描述

dependencyException: Error creating bean with name 'userInfoController': Unsatisfied dependency expressed through field 'userInfoService'; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type 'com.digital.service.UserInfoService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

solution:

@Autowired添加一个参数

@Autowired
private UserInfoService userInfoService;

改为:

@Autowired(required = false)
private UserInfoService userInfoService;

Bug3.2

description:

严重: Servlet.service() for servlet [dispatcherServlet] in context with path [/digital-ssm] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException

运行结果:

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值