SSM框架所有注意细节

SSM框架模板

mapper模板

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

</mapper>

mybatis全局配置文件

<?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>
	
</configuration>

spring常用开头

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

spring框架完整命名空间

    <?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:aop="http://www.springframework.org/schema/aop"
    	xmlns:c="http://www.springframework.org/schema/c"
    	xmlns:cache="http://www.springframework.org/schema/cache"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    	xmlns:jee="http://www.springframework.org/schema/jee"
    	xmlns:lang="http://www.springframework.org/schema/lang"
    	xmlns:mvc="http://www.springframework.org/schema/mvc"
    	xmlns:p="http://www.springframework.org/schema/p"
    	xmlns:task="http://www.springframework.org/schema/task"
    	xmlns:tx="http://www.springframework.org/schema/tx"
    	xmlns:util="http://www.springframework.org/schema/util"
    	xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
    		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
    		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd
    		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
    		http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
    		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
    		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.3.xsd
    		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd ">
     
     
    </beans>

web.xml 3.1

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

  
</web-app>

Spring基础

基础技术

  • java
  • 反射
  • xml
  • xml解析
  • 代理
  • 大量设计模式

基础环境搭建

  1. 添加spring的依赖

    spring core maven导入

  2. 编写一个spring的配置文件

  3. 通过spring的应用程序上下文对象获取对象

默认单例模式

导入maven项目jar包

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>

IOC

IOC/依赖注入

概念

控制翻转

控制:创建对象,彼此之间的权利

控制权是在开发人员在代码中进行掌握,new

夺取控制权反转给Spring容器

  • 声明要什么

  • spring容器进行来控制

值的注入

set方法注入
<property name="springUser" ref="springUser"/>

注意

如果javaBean中没有set方法,那么就没办法使用该方法注入

如果没有无参构造器

构造注入
*第一种
  <bean id="user" class="com.haha.dao.impl.SpringUserDaoImpl">
        <constructor-arg name="springUser" value="哈哈"/>

    </bean>
第二种

使用index 它优先使用了构造器

对于非字面值可以描述的值的注入问题

​ 比如一个bean中还有另一个bean属性可以通过ref指向另外的bean的id名表示

第三种

type:类型相对应

bean属性

abstract

该bean不能被实例化,可以用来被继承,使用parent属性继承

parent

指定它的父bean是谁,将会继承父bean的所有内容,通过id指引

destroy-method

指定bean最后销毁时一定执行的操作,适合执行清理型工作,触发条件是bean确实被销毁才会发生

​ 容器close也会触发

​ refreash也会触发

init-method

​ 指定bean初始化方法,适合准备性工作。

name

设置别名可以通过name获取,可以写多个

scope:

​ 指定范围/默认是单例

​ singleton:单例,Spring上下文中只能有一个实例

​ prototype:原型:要一个就给一个

lazy-init

是否延迟初始化,

flase 默认的是所有的bean是容器初始化完毕就立刻注入

true 就是在实例化以后再初始化

​ 直接初始化话启动会慢,内存消耗大一点 当使用bean的时候会快 一点

​ 延迟初始化:程序启动会快一点,但是使用bean的时候会慢一点

depend-on

依赖的bean,如果一个bean依赖于另一个bean的准备就可以配置depend-on

alias

关于在spring的配置文件中单独定义别名

可以直接使用alias,可以跨xml文件使用

<alias name="dag" alias="dog"/>
待补充

注入方式

注入数组

   <property name="haha">
            <array>
                <value>dgjsha</value>
            </array>

        </property>

注入List

  <property name="dhs">
       <list>
      	<value></value>
      </list>
     </property>

注入map

   <property name="hah">
                <map>
                    <entry key="user1">
                        <bean></bean>
                    </entry>
                    
                </map>
                
            </property>

注入set

提醒

如果是其对应的普通数据直接写就完事,如果是其他类,那么就是使用bean再次注入

自动注入

antowire

byType

是根据类型注入它的属性,在上下文中搜索这个bean属性,找到有且仅有一个的情况下自动注入

peimary 默认值为true

如果有多个bean的class一样,那么primary只能有一个为true

byName

根据名字注入,通过查询pojo中的属性值

Constructor

按照优先匹配类型,没有类型就按照名字相匹配

注入外部文件

context:property-placeholder

首先引入完整的spring框架的命名空间

通过标签引入jdbc.properties文件

 <!--资源引入-->
    <!---->
<context:property-placeholder location="classpath:jdbc.properties"/>

直接使用bean注入

  <bean class="com.haha.pojo.Age" id="age">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>
import

可以将其他的配置文件引入

<import resource="classpath:spring-*.xml"/>

AOP

简介

面向切面编程,编程的关注点是一个横切面

概念

Aop是基于代理完成的,

1,所以要激活自动代理

配置

添加依赖

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.1</version>
</dependency>

配置文件

<!--激活自动代理-->
<aop:aspectj-autoproxy/>
  <bean class="com.haha.dao.impl.UserDao" id="userDao">
    </bean>
    <bean class="com.haha.pojo.UserG" id="userG">
    </bean>
    <!--配置切入点信息-->
    <aop:config>
        <aop:aspect id="userAsepct" ref="userDao">
            <!--1,before是用来表明是前置通知
					after后置
				

                2,method 指明是用来那种方法来切的
                3,pointcut切入点 意思就是要切什么包下面的什么类下面的什么方法
                * com.haha.pojo.*.*(..))
            -->
            <aop:before method="set" pointcut="execution(void com.haha.pojo.UserG.add())"></aop:before>
        </aop:aspect>

    </aop:config>

</beans>
	after-returning 在返回值之后执行,要比后置通知先执行  
returning获取返回值传递给切点方法,名称必须一致
 <aop:after-returning method="set" pointcut="execution(* com.haha.pojo.*.*(..))" returning="returning"></aop:after-returning>

 
public void set(String returning){
        System.out.println("在方法之前执行"+returning);
    }

 处理异常 after-throwing
<aop:after-throwing method="ExceptionAdvice" pointcut="execution(* com.haha.pojo.*.*(..))"/>

   public void Exe(){
        System.out.println("执行exe");
        throw new RuntimeException("hahhaahh");
    }

环绕执行

  <aop:around method="ExceptionAdvice" pointcut="execution(* com.haha.pojo.*.*(..))"></aop:around>
设置返回值之后可以获取返回值  
public Object ExceptionAdvice(ProceedingJoinPoint proceedingJoinPoint){
        try {
            Object pro = proceedingJoinPoint.proceed();
            return pro;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return null;
        }
    }

使用注解模式test

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);

注解

要求

激活注解需要首先引入完整的spring框架的命名空间

然后使用 扫描哪些包

扫描的包包括该包和其所有的子包

<context:component-scan base-package="包名"/>

也可以使用 不扫描该子包

<context:component-scan base-package="com.haha.pojo">    <context:exclude-filter type="annotation" expression="com.haha.pojo"/>    
</context:component-scan>

@Component

标记它为一个组件,相当于在xml中注册一个bean

@Aspect

标记为一个切面

@before

   @Before("execution(* com.haha.pojo.*.*(..))")等同于xml中的<aop:before/>

@Order()

定义执行顺序、、只能定义类之间的顺序,不能定义方法

@Order(数字)1最开始执行

在切点中获取

String name = joinPoint.getSignature().getName();//获取要切入的类名

@after

相当于<aop:after />

@AfterReturning

获取返回值

value设置要切的方法

@AfterReturning(value = "",returning = "")

@AfterThrowing

@AfterThrowing(value = "",throwing = "")

@Configuration

表明一个类为配置类,然后程序启动的时候扫描这个类,就可以清楚所有配置规则

@ComponentScan

组件扫描

@Autowired

用于自动注入组件,和在xml中配置的是一样的

@bean

用于在Spring容器中注册一个Bean

@service(业务层)

@repository(dao层)

MyBatis

动态sql

if

动态 SQL 通常要做的事情是根据条件包含 where 子句的一部分。比如:

  <update id="updateUser" >
            UPDATE user_tb
        <set>
        <if test="password!=null">password=#{password}</if>
        </set>
    where id=#{id}
    </update>
   @Test
    public void test1(){
        SqlSession sqlSession = DBFactory.getSqlSession();
        UserDaoBiz biz = sqlSession.getMapper(UserDaoBiz.class);
        User user = new User();
        user.setId("2");
        user.setPassword("1234");
        int i = biz.updateUser(user);
        sqlSession.commit();
        System.out.println(i);

        sqlSession.close();
    }

choose

有时我们不想应用到所有的条件语句,而只想从中择其一项。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>

trim

where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。

如果 where 元素没有按正常套路出牌,我们可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

foreach

动态 SQL 的另外一个常用的操作需求是对一个集合进行遍历,通常是在构建 IN 条件语句的时候。比如:

 <foreach collection="uids" item="uid" open="(" close=")" separator=",">
            #{uid}
        </foreach>

foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及在迭代结果之间放置分隔符。这个元素是很智能的,因此它不会偶然地附加多余的分隔符。

 @Test
    public void test3(){
        SqlSession sqlSession = DBFactory.getSqlSession();
        UserDaoBiz biz = sqlSession.getMapper(UserDaoBiz.class);
        int[] uids ={1,2,4};
        int i = biz.deleteAll(uids);
        //提交事务
        sqlSession.commit();
        System.out.println(i);
        sqlSession.close();
    }

bind

元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文。比如:

<select id="selectBlogsLike" resultType="Blog">
  <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
  SELECT * FROM BLOG
  WHERE title LIKE #{pattern}
</select>

也可以使用

<sql></sql>

缓存

 <!--开启二级缓存   通常直接引用官方文档-->
    <!--eviction="FIFO"  先进先出原则处理缓存-->
    <cache
            eviction="FIFO"
            flushInterval="60000"
            size="512"
            readOnly="true"/>


eviction

  • LRU – 最近最少使用:移除最长时间不被使用的对象。
  • FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
  • SOFT – 软引用:基于垃圾回收器状态和软引用规则移除对象。
  • WEAK – 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。

默认的清除策略是 LRU。

​ flushInterval(刷新间隔)属性可以被设置为任意的正整数,设置的值应该是一个以毫秒为单位的合理时间量。 默认情况是不设置,也就是没有刷新间隔,缓存仅仅会在调用语句时刷新。

​ size(引用数目)属性可以被设置为任意正整数,要注意欲缓存对象的大小和运行环境中可用的内存资源。默认值是 1024。

​ readOnly(只读)属性可以被设置为 true 或 false。只读的缓存会给所有调用者返回缓存对象的相同实例。 因此这些对象不能被修改。这就提供了可观的性能提升。而可读写的缓存会(通过序列化)返回缓存对象的拷贝。 速度上会慢一些,但是更安全,因此默认值是 false。

​ 提示 二级缓存是事务性的。这意味着,当 SqlSession 完成并提交时,或是完成并回滚,但没有执行 flushCache=true 的 insert/delete/update 语句时,缓存会获得更新

在mybatis-conf.xml中配置

<setting name="cacheEnabled " value="true"/>

一对一映射

第一种设置方法

描述

表格与表格之间存在一对一关系

  • 建立一个共同的实体类,可以使用继承

    public class UserAll extends User {   
        private UserG userG;  
        public UserG getUserG() 
        {        return userG;    }   
        public void setUserG(UserG userG) {       	 this.userG = userG;    }  
        @Override   
        public String toString() {        return "UserAll{" +                "userG=" + userG +                '}';    }}
    
    

两个实体类相关联建议使用oop方式

xml设置

查询返回的数据使用resultMap接收,并且自定义封装resultMap

 <resultMap id="userall" type="com.haha.pojo.UserAll">
        <id property="id" column="id"/>
        <result property="password" column="password"/>

        <association property="userG" javaType="com.haha.pojo.UserG">
            <id property="gId" column="g_id"/>
            <result property="age" column="age"/>
        </association>
    </resultMap>
   <select id="selectUserAll" resultMap="userall">
       SELECT u1.`id` as id,u1.`password`,u2.`age`,u2.`g_id` as g_id
       FROM user_tb u1,user_g u2
       <where>
           u1.id=u2.u_id AND u1.id=#{id}
       </where>

    </select>

test函数

   @Test
        public void t1(){
        SqlSession sqlSession = DBFactory.getSqlSession();
        UserDaoBiz userDaoBiz = sqlSession.getMapper(UserDaoBiz.class);
        UserAll userAll = userDaoBiz.selectUserAll("1");
        System.out.println(userAll.getUserG().getAge());
        sqlSession.close();
    }

第二种设置方法

[外链图片转存失败(img-yMfwBcoo-1565258165670)(G:\Pictures\Saved Pictures\1564625843365.png)]

第三种设置方法(分布式)

使用继承的方式可以简化xml的代码

    <resultMap id="user" type="com.haha.pojo.User">
        <id property="id" column="id"/>
        <result property="password" column="password"/>
    </resultMap>
    
        
    <resultMap id="userall" extends="user" type="com.haha.pojo.UserAll">
        <association property="userG" javaType="com.haha.pojo.UserG">
            <id property="gId" column="g_id"/>
            <result property="age" column="age"/>
        </association>
    </resultMap>

分布式

xml只需要先查询单表,然后使用association+继承的方式查询另一个连接的数据库,返回值为该数据库所对应的javaBean

 <resultMap id="user" type="com.haha.pojo.UserAll">
        <id property="id" column="id"/>
        <result property="password" column="password"/>
    </resultMap>

    <resultMap id="userall" extends="user" type="com.haha.pojo.UserAll">

        <association property="userG" select="com.haha.dao.UserAllBiz.userGid" column="id">

        </association>
    </resultMap>

    <select id="selectUserAll" resultMap="userall">
       SELECT id ,password
       FROM user_tb
       <where>
          id=#{id}
       </where>

    </select>

另一个xml文件

    <select id="userGid" resultType="com.haha.pojo.UserG" >

    select * from user_g where u_id=#{id}

    </select>

提示

有出现错误

Mapped Statements collection does not contain value for com.haha.dao.UserAllBiz.userGid

找不到该映射文件

原因为需要在mybatis-config.xml文件中导入

<mapper resource="com/haha.dao/UserAll.xml"/>

一对多映射

xml文件设置

使用resultMap的继承

还有collection

    <resultMap id="user" type="com.haha.pojo.UserAll">
        <id property="id" column="utId"/>
        <result property="password" column="password"/>
    </resultMap>
    
    <resultMap id="userall" extends="user" type="com.haha.pojo.UserAll">
        <collection property="userGList" ofType="com.haha.pojo.UserG">
            <id property="gId" column="ugGid"/>
            <collection property="ages" ofType="com.haha.pojo.Age">
                <id property="age" column="agAge"/>
                <result property="ageName" column="ageName"/>
            </collection>
        </collection>
    </resultMap>
    <select id="selectUserAll" resultMap="userall">
        SELECT
        ut.id as utId,
        ut.password,
        ug.g_id as ugGid,
        ag.age as agAge,
        ag.age_name as ageName
        FROM
        user_tb ut,
        user_g ug,
        age ag
        <where>
            ut.id = ug.u_id
            AND ug.age=ag.age
            AND ut.id =#{id}
        </where>


    </select>

使用多个javaBean调用

Spring MVC

简介

springMVC是一个web层的mvc框架

model 模型

view 视图

controller 控制器

这是一种设计模式,将责任进行拆分,不同的组件负责不同的事情

好处:

  • 结构清晰
  • 更好的维护(大量使用jsp的年代)

坏处:

  • 更加的复杂

入门体验

首先导入maven支持

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>

web.xml

注册前端控制器,目的在于,我们希望springmvc去处理所有的请求

通过


<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>/</url-pattern>
</servlet-mapping>

确实是处理所有的请求

的写法问题

  • /

    处理所有的请求,但是和/*不一样,他处理完之后要出去的时候不会再去将这个jsp页面当做一个新的请求,将这个渲染的结构直接返回给浏览器

  • /*(永远不要这样写) 原因

  • *.do 这种方式,是有的团队习惯将请求的行为加个小尾巴用来区别

Springmvc配置文件名字问题

默认情况下是用dispatcherServlet的姓名当做命名空间

[namespace]-servlet.xml(WEB-INF)之下寻找

配置文件

推荐使用

    <!--他会去web-inf下面去找Springmvc-servlet.xml文件-->
    <servlet-name>springmvc</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>-->
    <!--可以重新声明配置文件的名字-->
    <init-param>
        <param-name>namespace</param-name>
        <param-value>mvc</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

视图解析器

Spring支持多种视图模式

  • jsp
  • freemaker(模板技术)

内部视图资源解析器

  • 视图前缀(是请求响应资源的路径)

    <property name="prefix" value="/jsp/"/>
    
  • 后缀

<property name="suffix" value=".jsp"/>

逻辑视图

  • perfix
  • logicViewName
  • suffix

由逻辑视图转化为物理视图的公式

p View = perfix + logicViewName+suffix;

控制器的解释

是一种比较传统的实现接口的方式完成的Controller

 @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception 
 <bean class="com.haha.controller.HelloController" name="/helloController"/>取一个名字相当于充当这个请求的url

注解

@Controller

标记了为一个spring的控制器组件

不需要实现任何接口和继承任何类

@RequestMapping("/bye")

  • value 可以设置一个数组意思就是可以有多个别名,可以匹配不到多个路径

  • path 是value的别名,所以二者任选其一

  • method=RequestMethod.Post之类的 限定请求数据类型,比如get,Post也可以写成数组形式

  • params 可以指定参数,你还可以去限定这个参数的特征,必须等于某个值或者不等于

    用params描述了,我需要什么参数

    @RequestMapping(value = {"/m1","/m2"},params = {“girl”,“boy”})

开发步骤

  • headers 能能影响浏览器的行为

  • consumers 消费者 媒体类型,可以限定必须为application/json;charset=utf-8

  • produces 生产者 产生响应的类型

  • 记得配置一下基础扫描的包,这样配置文件才会生效

  • 在指定的类上面添加@Controller注解

  • 添加RequestMapping类似于前面的controller的那个名字

//不需要实现任何接口和继承任何类
@Controller
@RequestMapping("/haha")//推荐使用这种分层的RequestMapping
public class ByeController {
    @RequestMapping("/bye")
    public String bye(Model model){
        //这里return的就是我们的那个ViewName
        //此时去的是/jsp/bye.jsp页面
        model.addAttribute("hahah","sajk");

        return "bye";
    }
}

@Getmappring

相当于将RequestMapping中的method设置成get请求

@Postmappring

同上

@requestbody

使用这个可以直接返回数据而不用返回页面

一班情况下返回的是json格式

对于非get post

首先要增加一个过滤器

 <!--注册一个支持所有http请求类型的过滤器-->
    <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>

表单提交里面还要添加一个隐藏的参数

<input name="_method" value="DELETE"/>

@ModelAttribute

使用方法一:

如果某些对象在请求中一直存在,就适合这样使用

    //在任意controller里面的任意一个具体方法之前都会执行
     @ModelAttribute
    public void init(){

        User user = new User();
        user.setPassword("123");
    }
使用方法二
    @ModelAttribute("user")
    public void init(Model model){

        User user = new User();
        user.setPassword("123");
        model.addAttribute("user",user);

    }

使用方法三

这个方式会直接去我们的模型去找,如果没有传递模型过来, @ModelAttribute(“user”)会自动提供

  @RequestMapping("/zhangyu")
    public String login(@ModelAttribute User user){
        
        return "bye";
    }

@SessionAttributes(“user”)

用在类上面将模型自动填充到会话中去

@SessionAttribute

要求当前这次访问当中的会话里面必须有某个对象(用在方法上)

  public String set(@SessionAttribute User user){
        System.out.println("//"+user.getName()+"//");

        return "bye";

    }

配置静态资源文件

配置需要的css文件以及js文件

解决方式1:在springmvc.xml中设置

    <!--默认的servlet处理者-->
    <mvc:default-servlet-handler/>
    <!--只加上他一个的话相当于全部把他处理了-->
    <mvc:annotation-driven/>

转发与重定向

  • 转发到页面

    默认到选项

  • 重定向到页面

    return “redirect:Path”

  • 转发到另一个控制器

    ​ return forword:path

关于Sringmvc访问web元素

Webrequest 相当于request但是是模拟

session

application

可以通过模拟对象完成操作也可以通过原生的servletAPI完成操作

关于请求路径问题

springmvc支持ant风格

  • ?@RequestMapping(path = {“m1?”}) 任意一个字符,斜杠除外
  • 任意0-n的字符都可以 ,但是不能是斜杠 *@RequestMapping(path = {“m1星”})
  • ** 支持任意层路径@RequestMapping(path = {“m1/**”})

关于乱码问题

只需要添加一个过滤器即可,在springmvc中有一个

<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>forceRequestEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
    <!--指定字符编码-->
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

form表单提交方式

方式一:通过属性名绑定

通过属性名进行绑定,可以完成数据传递,

页面当中的name值要和后台的形参保持一致

方式二 使用@RequestParm
方式三:直接使用pojo
  @ResponseBody
    public String update(User user){
        user.getName()
        System.out.println(name);
        System.out.println(password);
        return "haha";
    }
日期

使用日期格式需要先创建格式

<form action="${ctx}/haha/update">
    <input type="text" name="name"><br>
    <input type="password" name="password"><br>
    <input type="date" name="date"/><br>
    <input type="submit" value="提交">
    
</form>

    @InitBinder
    public void init(WebDataBinder webDataBinder){

        SimpleDateFormat simpleFormatter = new SimpleDateFormat("yyyy-MM-dd");
        simpleFormatter.setLenient(false);
        webDataBinder.registerCustomEditor(Date.class,new CustomDateEditor(simpleFormatter,false));

    }
    @RequestMapping("/update")
    //需要额外的json包的支持
    @ResponseBody
    public String update(User user){

        System.out.println(user.getName());
        System.out.println(user.getPassword());
        System.out.println(user.getDate());
        return "haha";
    }

注解但是只能使用java.util.Date包

@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date;

JSON

导入json包

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.58</version>
    </dependency>

SSM整合

简介

Spring和SpringMVC是天然继承的,所以只需要解决mybatis和Spring整合的问题,中间项目mybatis-spring项目进行整合

重点整合Spring和MyBatis

  • 由spring容器管理mybatis的mapper
  • 由spring利用声明式事务(AOP)进行事务的管理

action="${ctx}/haha/update">






```

    @InitBinder
    public void init(WebDataBinder webDataBinder){

        SimpleDateFormat simpleFormatter = new SimpleDateFormat("yyyy-MM-dd");
        simpleFormatter.setLenient(false);
        webDataBinder.registerCustomEditor(Date.class,new CustomDateEditor(simpleFormatter,false));

    }
    @RequestMapping("/update")
    //需要额外的json包的支持
    @ResponseBody
    public String update(User user){

        System.out.println(user.getName());
        System.out.println(user.getPassword());
        System.out.println(user.getDate());
        return "haha";
    }

注解但是只能使用java.util.Date包

@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date;

JSON

导入json包

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.58</version>
    </dependency>

SSM整合

简介

Spring和SpringMVC是天然继承的,所以只需要解决mybatis和Spring整合的问题,中间项目mybatis-spring项目进行整合

重点整合Spring和MyBatis

  • 由spring容器管理mybatis的mapper
  • 由spring利用声明式事务(AOP)进行事务的管理
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值