java框架——springMVC

目录

一、入门案例

1、 用maven创建WEB工程,引入开发的jar包

pom.xml具体配置文件如下:
主要导入的包有:
spring-context
spring-web
spring-webmvc
servlet-api
jsp-api

<?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.H</groupId>
    <artifactId>springmvc_1</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 版本锁定,下面导入的spring的包的版本都是5.0.2 -->
    <properties>
        <spring.version>5.0.2.RELEASE</spring.version>
    </properties>
    
    <dependencies>
        <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>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>
    </dependencies>

</project>

2、配置核心的控制器(配置DispatcherServlet)

在web.xml配置文件中核心控制器DispatcherServlet

<!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 Configuration ========================================== -->

  <!--
    - Servlet that dispatches requests to the Spring managed block servlets
    -->
  <!--配置前端控制器-->
  <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>

  <!-- URL space mappings ============================================= -->

  <!--
    - Cocoon handles all the URL space assigned to the webapp using its sitemap.
    - It is recommended to leave it unchanged. Under some circumstances though
    - (like integration with proprietary webapps or servlets) you might have
    - to change this parameter.
    -->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

3、 编写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">

    <!-- 配置spring创建容器时要扫描的包 -->
    <context:component-scan base-package="com.H"></context:component-scan>

    <!-- 配置视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 配置spring开启注解mvc的支持 -->
    <mvc:annotation-driven/>

</beans>

4、编写index.jsp和HelloController控制器类

1、index.jsp

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

2、HelloController控制器类

package com.H.controller;

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

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

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

}

5、在WEB-INF目录下创建pages文件夹,编写success.jsp的成功页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>成功运行</h3>
</body>
</html>

6、 启动Tomcat服务器,进行测试

7、入门案例的执行过程分析

1、入门案例的执行流程

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

  • 当启动Tomcat服务器的时候,因为在web.xml文件中配置了load-on-startup标签,所以会创建DispatcherServlet对象,就会加载springmvc.xml配置文件
  • 开启了注解扫描(spring的IOC功能),那么HelloController对象就会被创建
  • 从index.jsp发送请求,请求会先到达DispatcherServlet核心控制器,根据配@RequestMapping注解找到执行的具体方法

注意:因为web.xml中servlet中的拦截(访问)地址是 / 即所有地址(/ 斜杠在服务器解析的时候,表示地址为:http://ip:port/工程路径),所以所有地址都会被拦截,然后去找到并执行DispatcherServlet这个类,然后根据配@RequestMapping注解找到执行的具体方法

如果使用servlet去处理请求并打印结果,就需要创建一个类去继承Servlet类,啊然后实现他的service方法去处理请求。
在这里插入图片描述

  • 根据执行方法的返回值,再根据配置的视图解析器,去指定的目录下查找指定名称的JSP文件
  • Tomcat服务器渲染页面,做出响应

2、入门案例中的组件分析

在这里插入图片描述

(1) 前端控制器(DispatcherServlet)
用户请求到达前端控制器,它就相当于 mvc 模式中的 c,dispatcherServlet 是整个流程控制的中心,由它调用其它组件处理用户的请求,dispatcherServlet 的存在降低了组件之间的耦合性。

(2)处理器映射器(HandlerMapping)
HandlerMapping 负责根据用户请求找到 Handler 即处理器,SpringMVC 提供了不同的映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。

(3)处理器(Handler)
它就是我们开发中要编写的具体业务控制器。由 DispatcherServlet 把用户请求转发到 Handler。由Handler 对具体的用户请求进行处理。

(4)处理器适配器(HandlAdapter)
通过 HandlerAdapter 对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行。

(5)视图解析器(View Resolver)
View Resolver 负责将处理结果生成 View 视图,View Resolver 首先根据逻辑视图名解析成物理视图名即具体的页面地址,再生成 View 视图对象,最后对 View 进行渲染将处理结果通过页面展示给用户。

(6)视图(View)
SpringMVC 框架提供了很多的 View 视图类型的支持,包括:jstlView、freemarkerView、pdfView等。我们最常用的视图就是 jsp。
一般情况下需要通过页面标签或页面模版技术将模型数据通过页面展示给用户,需要由程序员根据业务需求开发具体的页面。

(7)< mvc:annotation-driven >说明
在 SpringMVC 的各个组件中,处理器映射器、处理器适配器、视图解析器称为 SpringMVC 的三大组件。使 用 < mvc:annotation-driven >自动加载 RequestMappingHandlerMapping (处理映射器) 和
RequestMappingHandlerAdapter( 处 理 适 配 器 ),可 用 在 SpringMVC.xml 配 置 文 件 中 使 用< mvc:annotation-driven >替代注解处理器和适配器的配置。

8、RequestMapping 注解

作用:

用于建立请求 URL 和处理请求方法之间的对应关系。

出现位置:
类上:
请求 URL 的第一级访问目录。此处不写的话,就相当于应用的根目录。写的话需要以 / 开头。
它出现的目的是为了使我们的 URL 可以按照模块化管理:
例如:
账户模块:
/account/add
/account/update
/account/delete

订单模块:
/order/add
/order/update
/order/delete
红色的部分就是把 RequsetMappding 写在类上,使我们的 URL 更加精细。

方法上:
请求 URL 的第二级访问目录。

// 控制器类
@Controller
@RequestMapping(path="/user")
public class HelloController {
   

    /**
     * 入门案例
     * @return
     */
    @RequestMapping(path="/hello")
    public String sayHello(){
   
        System.out.println("Hello StringMVC");
        return "success";
    }

    /**
     * RequestMapping注解
     * @return
     */
    @RequestMapping(value="/testRequestMapping")
    public String testRequestMapping(){
   
        System.out.println("测试RequestMapping注解...");
        return "success";
    }
}

   <a href="user/testRequestMapping">RequestMapping注解</a>

属性:
value: 用于指定请求的 URL。它和 path 属性的作用是一样的。

@RequestMapping(value="/testRequestMapping")
    public String testRequestMapping(){
   
        System.out.println("测试RequestMapping注解...");
        return "success";
    }

method: 用于指定请求的方式。

public enum RequestMethod {
   

	GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE

}

@RequestMapping(value="/testRequestMapping", method = {
   RequestMethod.GET})
    public String testRequestMapping(){
   
        System.out.println("测试RequestMapping注解...");
        return "success";
    }

params: 用于指定限制请求参数的条件。它支持简单的表达式。要求请求参数的 key 和 value 必须和配置的一模一样。

   @RequestMapping(value="/testRequestMapping",method = {
   RequestMethod.GET}, params = {
   "username=heihei"},headers = {
   "Accept"})
    public String testRequestMapping(){
   
        System.out.println("测试RequestMapping注解...");
        return "success";
    }
 <a href="user/testRequestMapping?username=heihei">RequestMapping注解</a>

例如:
params = {“accountName”},表示请求参数必须有 accountName
params = {“moeny!100”},表示请求参数中 money 不能是 100。
headers:用于指定限制请求消息头的条件。

注意:
以上四个属性只要出现 2 个或以上时,他们的关系是与的关系。

二、请求参数的绑定

1、绑定说明

1、绑定的机制

我们都知道,表单中请求参数都是基于 key=value 的。
SpringMVC 绑定请求参数的过程是通过把表单提交请求参数,作为控制器中方法参数进行绑定的。

<a href="account/findAccount?accountId=10">查询账户</a>

中请求参数是: accountId=10

/**
* 查询账户
* @return
*/
@RequestMapping("/findAccount")
public String findAccount(Integer accountId) {
   
System.out.println("查询了账户。。。。"+accountId);
return "success"; 
}

2、支持的数据类型

基本类型参数:
包括基本类型String 类型

jsp 代码:

<!-- 基本类型示例 --> 
<a href="account/findAccount?accountId=10&accountName=zhangsan">查询账户</a>

控制器代码:

/**
* 查询账户
* @return
*/
@RequestMapping("/findAccount")
public String findAccount(Integer accountId,String accountName) {
   
	System
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值