springMVC-1

springMVC入门


一、三层架构和MVC

系统标准的三层架构包括:表现层、业务层、持久层。
      表现层:也就是我们常说的web层。它负责接收客户端请求,向客户端响应结果,通常客户端使用http协议请求web 层,web 需要接收 http 请求,完成 http 响应。
      业务层:也就是我们常说的 service 层。它负责业务逻辑处理,和我们开发项目的需求息息相关。
      持久层:也就是我们是常说的 dao 层。负责数据持久化,包括数据层即数据库和数据访问层。通俗的讲,持久层就是和数据库交互,对数据库表进行曾删改查的。

MVC 模型:MVC 全名是 Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,是一种用于设计创建 Web 应用程序表现层的模式。
      Model(模型):通常指的就是我们的数据模型。作用一般情况下用于封装数据。
      View(视图):通常指的就是我们的 jsp 或者 html。作用一般就是展示数据的。
      Controller(控制器):是应用程序中处理用户交互的部分。作用一般就是处理程序逻辑的。

二、SpringMVC 是什么

SpringMVC是为最优秀的 MVC 框架。它通过一套注解,让一个简单的 Java 类成为处理请求的控制器,而无须实现任何接口。同时它还支持RESTful 编程风格的请求。

SpringMVC 在三层架构的位置,如下图示:
在这里插入图片描述

SpringMVC 的入门案例

创建项目时加上配置参数,可以提高创建速度。

archetypeCatalog
internal

在这里插入图片描述

1.在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>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

2.加载springmvc.xml的配置文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启注解扫描-->
    <context:component-scan base-package="com.fjut"></context:component-scan>
    
    <!--视图解析器对象-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
    <!--开启springMVC框架注解的支持-->
    <mvc:annotation-driven/>
</beans>

3.编写执行方法。

package com.fjut.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 控制器类
 */
@Controller
public class HelloController {

    @RequestMapping(path = "/hello")
    public String out(){
        System.out.println("Hello StringMVC");
        return "success";
    }
}

4.请求跳转界面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门程序</h3>
    <a href="hello">请求后台执行</a>
</body>
</html>

编写跳转的界面.jsp。
入门程序完成。

三、请求参数的绑定。

1.普通参数应用

<a href="param/testParam?username=hehe&password=123">请求参数绑定</a>
@RequestMapping("testParam")
    public String testParam(String username, String password){
        System.out.println(username);
        System.out.println(password);
        return "success";

2.绑定实体类内有其他实体类型数据

<form action="param/saveAccount" method="post">
		姓名:<input type="text" name="username">
        密码:<input type="text" name="password">
        金额:<input type="text" name="money">
        用户姓名:<input type="text" name="user.uname"><br/>
        用户年龄:<input type="text" name="user.age"><br/>
        <input type="submit" value="提交">
    </form>
@RequestMapping("saveAccount")
    public String saveAccount(Account account){
        System.out.println(account);
        return "success";
    }

3.绑定集合类型(实体类内有集合)

	<form action="param/saveAccount" method="post">
		姓名:<input type="text" name="username">
        密码:<input type="text" name="password">
        金额:<input type="text" name="money">
        <%--list集合--%>
        用户姓名:<input type="text" name="list[0].uname"><br/>
        用户年龄:<input type="text" name="list[0].age"><br/>
        <%--map集合--%>
        用户姓名:<input type="text" name="map['one'].uname"><br/>
        用户年龄:<input type="text" name="map['one'].age"><br/>
        <input type="submit" value="提交">
    </form>
@RequestMapping("saveAccount")
    public String saveAccount(Account account){
        System.out.println(account);
        return "success";
    }

四、解决中文乱码的配置

配置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>

  <!--配置解决中文乱码的过滤器-->
  <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>

  <!--配置前端控制器-->
  <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>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

注意:拦截器<filter>比控制器<servlet>的优先级高。所以拦截器在web.xml文件中,过滤器的配置位置要在控制器配置之前,否则<web-app>会报错。

五、自定义类型转换器

解决springmvc帮忙解决的类型转换的指定格式的类型转换。如:springmvc可以自动转换日期为2020/11/11的格式,不能转换2020-11-11的日期格式。因此可以自定义一个类型转换器来转换日期格式。


自定义步骤分两步,步骤如下:
      第一步:创建一个工具类,实现Converter<S ,T>接口,S是指界面传入的数据(小知识点,界面传入的type=“text”的数据,到后台都是字符串的类型。)T是指想要转换成的数据类型。类型转换工具类代码如下:

package com.fjut.utils;

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * String转换为Date数据的工具类。(能识别并转换的格式为"yyyy-MM-dd")
 */
public class StringToDateConverter implements Converter<String,Date>{
    @Override
    public Date convert(String s) {
        //健壮性判断
        if(s == null){
            throw new RuntimeException("请您传入数据");
        }

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return format.parse(s);
        } catch (Exception e) {
            throw new RuntimeException("数据类型转换出现错误");
        }
    }
}

      第二步:写好工具类后,要想生效,需要配置springmvc.xml。需要配置的代码如下:

<!--配置自定义类型转换器-->
    <bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <!--注册自定义的转换器(即注册StringToDateConverter)-->
        <property name="converters">
            <set>
                <bean class="com.fjut.utils.StringToDateConverter"></bean>
            </set>
        </property>
    </bean>

    <!--开启springMVC框架注解的支持-->
    <mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>

六、常用注解

@RequestParam

作用:
      把请求中指定名称的参数给控制器中的形参赋值。
属性:
      value:请求参数中的名称。
      required:请求参数中是否必须提供此参数。默认值:true。表示必须提供,如果不提供将报错。
使用的位置:方法的参数前。

 @RequestMapping("testRequestParam")
    public String testRequestParam(@RequestParam("name") String username, String password){
        System.out.println(username);
        System.out.println(password);
        return "success";
    }

注意:界面传递的属性名称必须有name。用与不用的区别:用了之后可以根据界面的属性名称为参数赋值。不用的话参数名称必须和界面传递的属性值一样。

@RequestBody

小知识点:只有post请求有请求体,get请求的属性内容都显示在地址栏了。
作用:
      用于获取请求体内容。直接使用得到是 key=value&key=value…结构的数据。
      get 请求方式不适用。请求结果为null。
属性:
      required:是否必须有请求体。默认值是:true。当取值为 true 时,get 请求方式会报错。如果取值为 false,get 请求得到是 null。
使用位置:方法的参数前。

@RequestMapping("testRequestBody")
    public String testRequestBody(@RequestBody String body){
        System.out.println(body);
        return "success";
    }

结果:username=xxx&password=123&age=12

@PathVaribale

作用:
      用于绑定 url 中的占位符。例如:请求 url 中 /delete/{id},这个{id}就是 url 占位符。
      url 支持占位符是 spring3.0 之后加入的。是 springmvc 支持 rest 风格 URL 的一个重要标志。
属性:
      value:用于指定 url 中占位符名称。
      required:是否必须提供占位符。
使用位置:方法的参数前。

<a href="param/usePathVariable/100">pathVariable 注解</a>
@RequestMapping("usePathVariable/{id}")
	public String usePathVariable(@PathVariable("id") Integer id){
		System.out.println(id);
		return "success"; 
	}

@RequestHeader

作用:
      用于获取请求消息头的值。
属性:
      value:提供消息头名称
      required:是否必须有此消息头
注:
      在实际开发中一般不怎么用

@CookieValue

作用:
      用于把指定 cookie 名称的值传入控制器方法参数,即:获取到cookie的值。
属性:
      value:指定 cookie 的名称。
      required:是否必须有此 cookie。
使用:

public String useCookieValue(@CookieValue(value="JSESSIONID") String cookieValue){...}

@ModelAttribute

作用:
      该注解是 SpringMVC4.3 版本以后新加入的。它可以用于修饰方法和参数。
      出现在方法上,表示当前方法会在控制器的方法执行之前,先执行。它可以修饰没有返回值的方法,也可以修饰有具体返回值的方法。
      出现在参数上,获取指定的数据给参数赋值。
属性:
      value:用于获取数据的 key。key 可以是 POJO 的属性名称,也可以是 map 结构的 key。
应用场景:
      当表单提交数据不是完整的实体类数据时,保证没有提交数据的字段使用数据库对象原来的数据。
例如:
      我们在编辑一个用户时,用户有一个创建信息字段,该字段的值是不允许被修改的。在提交表单数据是肯定没有此字段的内容,一旦更新会把该字段内容置为 null,此时就可以使用此注解解决问题。

@SessionAttribute(方法间参数共享)

作用:
      用于多次执行控制器方法间的参数共享。
属性:
      value:用于指定存入的属性名称
      type:用于指定存入的数据类型。

使用示例:

/*
jsp 中的代码:
<!-- SessionAttribute 注解的使用 --> <a href="springmvc/testPut">存入 SessionAttribute</a> <hr/>
<a href="springmvc/testGet">取出 SessionAttribute</a> <hr/>
<a href="springmvc/testClean">清除 SessionAttribute</a>
*/

/*
.xml界面获取值:${requestScope.username} =等同于= ${username}
*/

//控制器中的代码:
/**
* SessionAttribute 注解的使用
*/
@Controller("sessionAttributeController")
@RequestMapping("/springmvc")
@SessionAttributes(value ={"username","password"},types={Integer.class}) 
public class SessionAttributeController {
/**
* 把数据存入 SessionAttribute
* @param model
* @return
* Model 是 spring 提供的一个接口,该接口有一个实现类 ExtendedModelMap
* 该类继承了 ModelMap,而 ModelMap 就是 LinkedHashMap 子类
*/
@RequestMapping("/testPut") 
public String testPut(Model model){ 
	 model.addAttribute("username", "泰斯特"); 
	 model.addAttribute("password","123456"); 
	 model.addAttribute("age", 31); 
	 //跳转之前将数据保存到 username、password 和 age 中,因为注解@SessionAttribute 中有这几个参数 
	 return "success"; 
 } 
 
 @RequestMapping("/testGet") 
 public String testGet(ModelMap model){ 
	System.out.println(model.get("username")+";"+model.get("password")+";"+model.get("age")); 
 	return "success"; 
 } 
 
 @RequestMapping("/testClean") 
 public String complete(SessionStatus sessionStatus){ 
	 sessionStatus.setComplete(); 
	 return "success"; 
 } 
}

七、Restful风格

Restful风格:路径都是同一个,根据请求方式和占位符来判断执行哪个方法(不同的请求方式来执行不同的方法)。
特点:缓存少,易管理。
在这里插入图片描述


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值