MyBatis_SpringMVC

前置工具:Maven

  • Maven是一个自动管理工具,可以帮我们省去大部分引入jar包,配置环境等重复繁琐无意义的操作。
  • Maven是apache项目的根,他可以管理所有Apache项目相关的jar包。
  • 下载网址:https://maven.apache.org/ 找到Download下载zip压缩包文件。
  • 配置:略
  • Maven工程规范:
    • Web 项目文件夹
      	\src
      		\main		//主程序目录
      			\java	//主程序源代码
      			\resources//配置文件,资源文件
      		\test		//测试目录
      			\java
      			\resources
      	\pom.xml		//maven的配置文件,核心。
      
  • Maven的gav坐标
    • groupId:这个是组织或个人的唯一标识。大部分是公司域名的倒写,如:com.baidu com.laptop
    • artifactId:项目名称,如com.laptop.web
    • version:版本,版本由3个数字构成,如:5.4.1
      • 若版本还在开发中,属于不稳定版本,在后面加上-SNAPSHOT
  • 项目使用gav
    • 管理依赖时,需要向pom.xml文件中添加依赖,如:
      • <dependencies>
        	<dependency>
        		<groupId>mysql</groupId>
        		<artifactId>mysql-connector-java</artifactId>
        		<version>8.0.21</version>
        	</dependency>
        </dependencies>
        
    • 在哪里可以查到这些依赖呢?
      • https://mvnrepository.com/
    • 仓库:在pom.xml中设置自定义的本地仓库
  • 如何解决IDEA部署maven项目时很慢,甚至卡死?
    • 提前下载好archetype-catalog.xml,放在本地仓库中

MyBatis前置课程:JDK代理模式

  • JDK静态代理:
    • 定义接口,定义代理类和实现类
    • 代理类和实现类要继承接口,导致的缺点:不方便,每次在接口中新增功能都要同时修改代理类和实现类。
  • JDK动态代理:
    • 只需要实现类继承接口即可
    • 动态代理类:
      • 
        public class ProxyFactory {
            private Service target;
        
            public ProxyFactory(Service target){
                this.target = target;
            }
        
            public Object getAgent(){
                return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                        target.getClass().getInterfaces(),
                        new InvocationHandler() {
                            @Override
                            public Object invoke(Object proxy,
                                                 Method method,
                                                 Object[] args) throws Throwable {
                                System.out.println("代理协商中。。");
                                Object obj = method.invoke(target, args);
                                System.out.println("代理协商完毕");
        
                                return obj;
                            }
                        });
            }
        }
        
      • 首先,创建私有接口对象作为成员变量

      • 在构造函数中需要传入目标接口的对象

      • 定义方法获得JDK动态代理对象

        •  return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                          target.getClass().getInterfaces(),
                          new InvocationHandler() {
                              @Override
                              public Object invoke(Object proxy,
                                                   Method method,
                                                   Object[] args) throws Throwable {
                                  System.out.println("代理协商中。。");
                                  Object obj = method.invoke(target, args);
                                  System.out.println("代理协商完毕");
          
                                  return obj;
                              }
                          });
          
        • Proxy.newProxyInstance(
          	target.getClass().getClassLoader(),//第一个参数,类加载器
          	target.getClass().getInterfaces(),//第二个参数,获得继承的所有接口
          	new InvocationHandler(){
          		@Override
                              public Object invoke(Object proxy, //代理对象
                                                   Method method,//代理对象的方法
                                                   Object[] args) throws Throwable
           {//代理代码
                                  System.out.println("代理代码");
                                  Object obj = method.invoke(target, args);
                                  System.out.println("代理代码");
          
                                  return obj;
                              }
          }
          )
          
      • //调用
        @Test
            public void test(){
        //创建代理工厂,传入实现类对象(匿名内部类)
                ProxyFactory factory = new ProxyFactory(new SuperIdol());
        //取得代理对象
                Service agent = (Service)factory.getAgent();
        //调用代理对象动态获取的方法。
                agent.sing();
                agent.meme();
            }
        
    • (了解)cglib
      • JDK动态代理无法代理接口中没有定义的方法,此时需要用cglib。(在spring框架中有集成)

MyBatis框架

创建maven文件,选择quickstart。

MyBatis目录的配置:

  • [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ema479Ze-1677056368977)(image/SSM框架/1654245067899.png)]
    • jdbc.properties:
      • jdbc.driverClassName=com.mysql.cj.jdbc.Driver
        jdbc.url=jdbc:mysql://localhost:3306/scott?useUnicode=true&characterEncoding=utf8
        jdbc.username=root
        jdbc.password=123456
        
    • SqlMapConfig.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">
        
      • <!--设置jdbc.properties文件的位置。
        -->
        <configuration>
        	<properties resource="jdbc.properties"></properties>
        </configuration>
        
      • <environments default="development">
                <environment id="development">
        
        <!--   transactionManager type:   JDBC 由程序员手动管理事务
                        		  MANAGED 由容器管理事务
                    -->
                    <transactionManager type="JDBC"></transactionManager>
        <!--    dataSource type:    POOLED 使用数据库连接池
                                    UNPOOLED 不使用数据库连接池
                                    JNDI java命名目录接口 在服务器端进行数据库连接池的管理
                                    -->
                    <dataSource type="POOLED">
                        <property name="driver" value="${jdbc.driverClassName}"/>
                        <property name="url" value="${jdbc.url}"/>
                        <property name="username" value="${jdbc.username}"/>
                        <property name="password" value="${jdbc.password}"/>
        	    </dataSource>
                </environment>
            </environments>
        
    • 创建Emp实体类,类中成员变量要与数据库中的字段一致。
    • 在mapper中创建EmpMapper.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">
        
      • <mapper namespace="laptop">
            <select id="getAll" resultType="com.laptop.entity.Emp">
                select empno,ename,job,mgr,hiredate,sal,comm,deptno
                from emp;
            </select>
        </mapper>
        
        • namespace用于区分不同mapper文件中相同的id
        • id在调用时使用,resultType是返回集合的类型(泛型)
      • 完成后在SqlMapConfig中配置

        • <mappers>
                  <!--注册mapper.xml文件
                  resource:从resource目录下寻找指定的文件
                  url:使用绝对路径注册
                  class:动态代理的方式下的注册
                  -->
                  <mapper resource="EmpMapper.xml"></mapper>
              </mappers>
          
  • 调用sql语句
    •         //使用文件流读取核心配置文件
              InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
              //创建SqlSessionFactory工厂
              SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
              //取出sqlSession对象
              SqlSession sqlSession = factory.openSession();
              //完成查询操作
              List<Emp> list = sqlSession.selectList("laptop.getAll");
              list.forEach((emp)-> System.out.println(emp));
      	//查询一条sql语句操作
      	Emp emp = (Emp)sqlSession.selectOne("laptop.getById",7698);
              //关闭sqlSession
              sqlSession.close();
      
    • 结果集是一个集合,用sqlSession.selectList(String method)
    • 结果集是一条记录,用sqlSession.selectOne(String method,Object obj)
    • 模糊查询
      •     public void getLike() throws IOException{
                //1
                InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
                //2.创建工厂
                SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
                //3.获得sqlSession
                SqlSession sqlSession = factory.openSession();
                //4.调用
                List<Emp> list =  sqlSession.selectList("getLike","k");
                list.forEach(emp -> System.out.println(emp));
                //5.close
                sqlSession.close();
            }
        
    • 增删改不需要写返回值

MyBatis类

  • Resources:
    • InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
    • 解析XML文件
  • SqlSessionFactory:
    • 是一个接口,定义了openSession()
    • SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);

如何给对象类创建别名?

  • 在properties之后,environments之前加上
    • 单个注册(指定类名)

      <typeAliases>
             <typeAlias type="com.laptop.entity.Emp" alias="emp"></typeAlias>
          </typeAliases>
      
    • 批量注册(直接指定包名)批量注册时,自动给每一个类起别名,起名方式遵循驼峰命名法

      <typeAliases>
              <package name="com.laptop.entity"/>
          </typeAliases>
      

设置在标准控制台输出mybatis日志。

<settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

指定java下的mapper和main下的resources为资源文件夹


  <resources>
  	<resource>
  		<directory>src/main/java</directory>
  		<includes>
  			<include>**/*.xml</include>
  			<include>**/*.properties</include>
  		</includes>
  	</resource>
  </resources>

<resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.xml</include>
          <include>**/*.properties</include>
        </includes>
</resource>

mapper接口

  • 创建mapper接口需要:

    1. 与数据库字段一致的实体类,实现setter,getter方法,创建无参构造方法,全参构造方法,没有主键ID的构造方法。

    2. 创建mapper包。

    3. 在mapper包下创建mapper类,例如:UsersMapper,里面规定方法名,参数类型以及返回类型。

    4. 在mapper包下创建mapper.xml文件,例如:UsersMapper.xml,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">
        <!--mapper映射文件头-->
        <mapper namespace="com.laptop.mapper.UsersMapper">
        <!--命名空间必须是mapper接口的引用路径,不能写错,否则无法关联。-->
        
    5. 在SqlMapConfig.xml中配置mapper映射。

      • 重点在最后的mappers配置

        <?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>
        <!--    设置资源文件-->
            <properties resource="jdbc.properties"></properties>
        <!--    设置日志输出到控制台-->
            <settings>
                <setting name="logImpl" value="STDOUT_LOGGING"/>
            </settings>
        <!--    起别名-->
            <typeAliases>
                <package name="com.laptop.bean"/>
            </typeAliases>
        
            <environments default="development">
                <environment id="development">
                    <transactionManager type="JDBC"></transactionManager>
                    <dataSource type="POOLED">
                        <property name="driver" value="${jdbc.driverClassName}"/>
                        <property name="url" value="${jdbc.url}"/>
                        <property name="username" value="${jdbc.username}"/>
                        <property name="password" value="${jdbc.password}"/>
                    </dataSource>
                </environment>
            </environments>
        
            <mappers>
        <!--       单个注册↓
         <mapper class="com.laptop.mapper.UsersMapper"></mapper>
                    多个注册↓-->
                <package name="com.laptop.mapper"/>
            </mappers>
        </configuration>
        
    6. 在mapper接口中,定义好方法,如:Users getById(Integer id);

    7. 在mapper.xml文件中写mybatis语句。如:

      <select id="getById" parameterType="int" resultType="users">
              select id,username,birthday,sex,address
              from users where id = #{id};
          </select>
      

      注意:id必须和mapper接口中的方法名一致,参数类型int代表Integer,_int代表int。

    8. 调用:

      @org.junit.Test
          public void testGetById(){
              UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
      
              Users user = usersMapper.getById(5);
          }
      

      UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);这句话可以提到外面代理部分。

  • 使用concat拼接字符串,可以在模糊查询中使用#{},防止sql注入

    • 例如:

      <select id="getLikeGood" parameterType="string" resultType="users">
              select id,username,birthday,sex,address
              from users where username like concat('%',#{username},'%')
          </select>
      
  • 传入的参数有多个,在mapper接口类中加上@Param(“名称”)。

    • 例如:

      <!--
      接口中:   List<Users> getLikeNameOrAddress(
                  @Param("columnName")
                  String columnName,
                  @Param("columnValue")
                  String columnValue);
      -->
      
      <!--     List<Users> getLikeNameOrAddress(String columnName,String columnValue);-->
          <select id="getLikeNameOrAddress" resultType="users">
              select id,username,birthday,sex,address
              from users where ${columnName} like concat('%',#{columnValue},'%')
          </select>
      
  • 返回主键的业务需求和代码实现。

    • <insert id="insert" parameterType="users">
      	<selectKey keyProperty="id" resultType="int" order="AFTER">
      		select last_insert_id();
      	</selectKey>
      	insert into users(username,birthday,sex,address)
      	values(#{username},#{birthday},#{sex},#{address});
      </insert>
      
    • 上面的业务功能是往users表中插入除了id以外的字段。
    • selectKey:
      • keyProperty:返回到users类中的id字段
      • resultType:返回字段的类型:Integer
      • order:在insert语句执行前还是执行后返回
  • 分库分表时,如何生成唯一ID?

    • Java:

      UUID uuid = UUID.randomUUID();
      
      //uuid.toString().replace("-","").substring(20);
      
    • mysql:

      select uuid();
      

Sql代码片段封装

  • 封装命令:

    <sql id="allColumns">
            id,username,birthday,sex,address
        </sql>
    
  • 使用封装:

  <include refid="allColumns"></include>

MyBatis动态sql多条件语句

  • 自定义多条件查询:
    • <select id="selectByCondition" parameterType="users">
      	select <include refid="allColumns"></include>
      	from users
      	<where>
      		<if id="id != null and id != ''">
      			and id = #{id}
      		</if>
      		<if test="username != null and username != ''">
                      and username like concat('%',#{username},'%')
      		</if>
                  	<if test="birthday != null">
                      	and birthday = #{birthday}
                  	</if>
                  	<if test="sex != null and sex != '' ">
                  	    and sex like concat('%',#{sex},'%')
                 	 </if>
                	  <if test="address != null and address != '' ">
               	       and address like concat('%',#{address},'%')
             	     </if>
      	</where>
      </select>
      
  • 自定义多条件更新:
    •     <update id="updateByCondition" parameterType="users">
              update users
              <set>
                  <if test="username != null and username != ''">
                      username = #{username},
                  </if>
                  <if test="birthday != null">
                      birthday = #{birthday},
                  </if>
                  <if test="sex != null and sex != ''">
                      sex = #{sex},
                  </if>
                  <if test="address != null and address != ''">
                      address = #{address},
                  </if>
              </set>
                  where id = #{id}
          </update>
      
  • foreach标签遍历
    •     <select id="getByIds" resultType="users">
              select <include refid="allColumns"></include>
              from users where id in (
                  <foreach collection="array" item="id" separator=",">
                      #{id}
                  </foreach>
              )
          </select>
      
    • 入参类型是一个数组,不用写parameterType。
    • foreach标签中,collection有三种:list,map,array。各自对应一种传入的数据类型
    • item是取出的单个元素的变量名
    • separator:分隔符
    • 还有open和close,代表foreach循环的起始符号和结束符号。
  • 批量更新操作
    • 注意:一定要在jdbc的url中添加:
    • &allowMultiQueries=true
      
    • 代码实现:
    •     <update id="updateBatch">
              <foreach collection="list" item="u" separator=";">
                  update users
                  <set>
                      <if test="u.username != null and u.username != ''">
                          username = #{u.username},
                      </if>
                      <if test="u.birthday != null">
                          birthday = #{u.birthday},
                      </if>
                      <if test="u.sex != null and u.sex != ''">
                          sex = #{u.sex},
                      </if>
                      <if test="u.address != null and u.address != ''">
                          address = #{u.address},
                      </if>
                  </set>
                  where id = #{u.id}
              </foreach>
          </update>
      
  • 入参用实体类包不住时(参数超过一个不写)
    •     <select id="queryBirthday" resultType="users">
              select <include refid="allColumns"></include>
              from users where birthday between #{arg0} and #{arg1}
          </select>
      
    • 用#{arg0}和#{arg1}根据参数下标获取值。

Spring框架

Spring详细去看Spring.md文件

SpringMVC

什么是SpringMVC

  • 它是基于MVC开发模式的框架,用来优化控制器,它是Spring家族的一员,也具备IoC和aop。
  • MVC是一种开发模式,是模型视图控制器的简称,所有的web应用都是基于MVC开发。
  • M:Model模型层,包含实体类,业务逻辑层,数据访问层
  • V:视图层,html,JavaScript,vue等都是视图层,用来呈现数据。
  • C:控制器,用来接收客户端的请求并返回响应到客户端的组件,Servlet就是组件。
  • SSM对于各个层级的优化:
  • MyBatis优化M层中的数据访问层
  • SpringMVC优化C层(Controller)
  • Spring用来整合所有的框架

SpringMVC的优点

  1. 轻量级的框架,jar很小,对代码无污染,不依赖特定的接口和类。
  2. 易于上手,功能强大
  3. 具备IOC和AOP
  4. 完全基于注解开发

基于注解的SpringMVC开发步骤

  1. 新建项目,选择webapp模板。
  2. 修改目录,添加缺失的test,java,resources,并修改目录属性
  3. 添加pom.xml文件,添加SpringMVC的依赖,添加Servlet的依赖
  4. 添加Springmvc.xml配置文件,指定包扫描,添加视图解析器
  5. 删除web.xml文件,新建web.xml
  6. 在web.xml中注册SpringMVC框架
  7. 在webapp目录下新建admin目录,在目录下新建main.jsp页面,删除index.jsp页面并新建,发送请求给服务器
  8. 开发控制器,他是一个普通的类
  9. 添加tomcat进行测试功能

web请求执行的流程

index.jsp<--------------->DispatcherServlet<----------->SpringMVC的处理器是一个普通的方法

DispatcherServlet要在web.xml文件中注册才能用。

配置方法:

<servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
<!--        指定拦截什么样的请求-->
<url-pattern>*.action</url-pattern>
    </servlet-mapping>

springmvc.xml配置

首先添加controller包扫描,然后配置jsp页面的前缀后缀

<!--    包扫描-->
<context:component-scan base-package="laptop.controller"></context:component-scan>
<!--    添加视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--        配置前缀和后缀-->
<property name="prefix" value="/admin/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

@RequestMapping

在方法上添加@RequestMapping(“/demo.action”)

//注意:一定要带上.action后缀否则找不到

此注解可以加在类上,相当添加了一个虚拟路径。访问时要加上

@RequestMapping还可以分别处理get请求和post请求

在方法上声明,就表明这个方法是处理post请求的。

@RequestMapping(value = "req.action",method = RequestMethod.POST)

五种数据提交方式的优化

1.单个数据提交

<h2>1.单个数据提交</h2>
<form action="${pageContext.request.contextPath}/one.action">
姓名:<input type="text" name="uname">
年龄:<input type="text" name="uage">
    <input type="submit">
</form>

在one.action中获取:

@RequestMapping("/one.action")
public String one(String uname,int uage){
    System.out.println("uname"+ uname+ "uage" + uage);
    return "main";
}

十分强大,不需要用request获取,只需要形参的名称与提交的name一致即可。

2.对象封装提交数据

提交请求时,保证参数的名称与实体类中成员变量的名称一致,就可以自动创建对象,自动提交数据,自动类型转换,自动封装数据到对象中。

get请求中文乱码问题在Tomcat8以后已经被解决,

3.动态占位符提交

仅限于超链接提交或地址栏提交数据,一杠一值

jsp:

<h2>3.动态占位符提交</h2>
<a href="${pageContext.request.contextPath}/three/张三/22.action">动态提交</a>

controller:

@RequestMapping("/three/{name}/{age}.action")
public String three(
        @PathVariable
String name,
@PathVariable
int age){
    System.out.println("name="+name+"age"+age);
    return "main";
}

4.映射名称不一致

提交请求参数与action方法的形参名称不一致,用@RequestParam

@RequestMapping("/four.action")
public String four(
        @RequestParam("uname")
        String name,
@RequestParam("uage")
        int age){
    System.out.println("name="+name+"age="+age);
    return "main";
}

5.手工提取数据

文艺复兴

@RequestMapping("/five.action")
public String five(HttpServletRequest request){
    String uname = request.getParameter("uname");
    int uage = Integer.parseInt(request.getParameter("uage"));
System.out.println("name="+uname+"age"+uage);
    return "main";
}
<h2>5.手工提取数据</h2>
<form action="${pageContext.request.contextPath}/five.action">
姓名:<input type="text" name="uname">
年龄:<input type="text" name="uage">
    <input type="submit">
</form>

post请求的中文乱码解决

在web.xml中进行配置

<!--    配置中文编码过滤器,解决乱码问题,建议放在所有配置的前面-->
<filter>
        <filter-name>encode</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--    private String encoding;
        private boolean forceRequestEncoding;
        private boolean forceResponseEncoding;-->
<init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encode</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

要记住的:org.springframework.web.filter.CharacterEncodingFilter(filter-class)

配置类里的编码格式为UTF-8:<param-name>encoding </param-name>
<param-value>UTF-8 </param-value>
</init-param>

强制改变request和response的编码格式
<init-param>
<param-name>forceRequestEncoding </param-name>
<param-value>true </param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding </param-name>
<param-value>true </param-value>
</init-param>

action方法的返回值

1)String:客户端资源的地址,自动拼接前缀和后缀,还可以屏蔽自动拼接字符串,可以指定返回的路径。

2)Object:返回json格式的对象,自动将对象或集合转为.json(使用jackson)一般用于ajax请求。

3)void:无返回值,一般用于ajax请求

4)基本数据类型:用于ajax请求

5)ModelAndView:返回数据和视图对象,现在用的很少。

完成ajax请求访问服务器,返回学生集合

步骤:

1)添加jackson依赖

这里用再高的版本就会报错

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.8</version>
</dependency>

2)在webapp目录下新建js目录,添加jQuery函数库

十分简单

3)在index.jsp页面上导入函数库

index.jsp页面:

着重看一下jquery,ajax和javascript中的各种写法,复习

<%--
  Created by IntelliJ IDEA.
  User: litao
  Date: 2022/10/25
  Time: 16:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>AJAX</title>
</head>
<body>
    <br><br><br>
<a href="javascript:showStu()">访问服务器返回学生集合</a>
<div id="mydiv">等待服务器返回数据........</div>

    <script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function showStu(){
        $.ajax({
            url:"${pageContext.request.contextPath}/list.action",
type:"get",
dataType:"json",
success:function (stuList){
                var s = "";
$.each(stuList,function (i,stu){
                    s+=stu.name + "----" + stu.age + "<br>";
})
                $("#mydiv").html(s);
}
        })
    }
</script>
</body>
</html>

4)在action上添加注解@ResponseBody,用来处理ajax请求

先在类上加@Controller,方法上加@RequestMapping(“/list.action”)

@ResponseBody是ajax的注解驱动

package laptop.controller;/*
 *Author:Litao
 *Created in:
 */

import laptop.pojo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
public class StudentListAction {
    @RequestMapping("/list.action")
    @ResponseBody
public List<Student> stuList(){
        List<Student> list = new ArrayList<>();
Student s1 = new Student("张三",20);
Student s2 = new Student("李四",21);
Student s3 = new Student("王五",22);
list.add(s1);
list.add(s2);
list.add(s3);

        return list;
}
}

5)在springmvc.xml文件中添加注解驱动 <mvc:annotationdriven/>,它用来解析@ResponseBody注解

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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--    添加包扫描-->
<context:component-scan base-package="laptop.controller"></context:component-scan>
<!--    不用添加视图解析器,因为处理的是ajax请求
但是要添加注解驱动,专门用来处理ajax请求-->
<mvc:annotation-driven></mvc:annotation-driven>
</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">
<filter>
<!--private String encoding;

   private boolean forceRequestEncoding = false;

   private boolean forceResponseEncoding = false;-->
<filter-name>encode</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>forceRequestEncoding</param-name>
        <param-value>true</param-value>
    </init-param><init-param>
    <param-name>forceResponseEncoding</param-name>
    <param-value>true</param-value>
</init-param>
</filter>
    <filter-mapping>
        <filter-name>encode</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>dispatcher</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>dispatcher</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

转发和重定向的区别

index.jsp-------------->one.action------------>main.jsp

请求转发基于服务器的跳转

index到one.action,one.action到main就是请求转发

地址栏停留的仍然是one.action


重定向是基于客户端的跳转

index到one.action,index再到main.jsp叫重定向

地址栏编程main.jsp

不使用前后缀跳转

前面配置的前缀不用的情况下跳转。

@RequestMapping("/five.action")
public String five(){
    System.out.println("forward跳转到login.jsp.............");
    return "forward:/login/login.jsp";//默认使用视图解析器拼接前缀后缀进行页面跳转
}

转发跳转就forward:/目录/xxx.jsp

重定向就redirect:/目录/xxx.jsp

想跳哪里就跳哪里。

日期的处理

1)如果是单个日期传递,直接在controller中转换好看之后再传递

2)如果是list集合中的实体类中的成员变量,则必须使用JSTL

导入fmt包(golang的味道):

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

传入日期的时候这样处理一下:

<fmt:formatDate value="${stu.birthday}" pattern=
        "yyyy-MM-dd"></fmt:formatDate>

给controller绑定日期刷子

@InitBinder
public void initBinder(WebDataBinder binder){
    binder.registerCustomEditor(Date.class,new CustomDateEditor(sdf,true));
}

拦截器

在servlet中有个filter,但是springmvc中的过滤器执行有三个时机,方法执行前,后和最终处理。

使用权限验证就是在预处理中完成。

拦截器实现的两种方式

1)继承HandlerInterceptor 的父类。

2)实现HandlerInterceptor接口,推荐使用实现接口的方式。

拦截器实现的步骤

1)改造登录方法,在session中存储用户信息,用于进行权限验证

2)开发拦截器的功能,实现HandlerInterceptor接口,重写preHandle()方法

3)在springmvc.xml文件注册拦截器

具体代码

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <mvc:exclude-mapping path="/login"/>
        <mvc:exclude-mapping path="/loginPage"/>
        <bean class="laptop.interceptor.LoginInterceptor"></bean>
    </mvc:interceptor>
</mvc:interceptors>

Interceptor类:

public class LoginInterceptor implements HandlerInterceptor {
    @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpSession session = request.getSession();
        if(session.getAttribute("username")!= null){
            return true;
}else {
            request.setAttribute("msg", "您还没有登录,请先登录");
request.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(request,response);
            return false;
}
    }
}

实现HandlerInterceptor接口,选择实现preHandle或者postHandle,afterCompletion

SSM整合

整合MyBatis,Spring,SpringMVC步骤

0.建库建表
  1. 新建maven项目,选择webapp模板
  2. 修改目录
  3. 修改pom文件(复制粘贴)
  4. 添加jdbc.properties
  5. 添加SqlMapConfig.xml文件(模板)
  6. 添加applicationContext_mapper.xml文件
  7. 添加applicationContext_service.xml文件
  8. 添加springmvc.xml文件
  9. 删除web.xml,新建改名,设置中文编码并注册springmvc的框架并注册spring框架
  10. 新建实体类user
  11. 新建usermapper.java接口
  12. 新建UserMapper.xml实现增删改查
  13. 新建service接口和实现类
  14. 新建测试类,完成所有功能的测试
  15. 新建控制器,完成所有功能
  16. 浏览器测试功能

分页公式

limit (当前页数 - 1) * 每页显示,每页显示

各种设置

做项目的时候再边写在这边复习了

构建Vue项目

cd

npm i element -ui -S

npm install

npm install --save vue-axios
preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HttpSession session = request.getSession();
if(session.getAttribute(“username”)!= null){
return true;
}else {
request.setAttribute(“msg”, “您还没有登录,请先登录”);
request.getRequestDispatcher(“WEB-INF/jsp/login.jsp”).forward(request,response);
return false;
}
}
}


实现HandlerInterceptor接口,选择实现preHandle或者postHandle,afterCompletion

# SSM整合

整合MyBatis,Spring,SpringMVC步骤

    0.建库建表

1. 新建maven项目,选择webapp模板
2. 修改目录
3. 修改pom文件(复制粘贴)
4. 添加jdbc.properties
5. 添加SqlMapConfig.xml文件(模板)
6. 添加applicationContext_mapper.xml文件
7. 添加applicationContext_service.xml文件
8. 添加springmvc.xml文件
9. 删除web.xml,新建改名,设置中文编码并注册springmvc的框架并注册spring框架
10. 新建实体类user
11. 新建usermapper.java接口
12. 新建UserMapper.xml实现增删改查
13. 新建service接口和实现类
14. 新建测试类,完成所有功能的测试
15. 新建控制器,完成所有功能
16. 浏览器测试功能

## 分页公式

limit (当前页数 - 1) * 每页显示,每页显示

## 各种设置

做项目的时候再边写在这边复习了

## 构建Vue项目

cd

npm i element -ui -S

npm install

npm install --save vue-axios
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

房石 陽明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值