SpringMVC

1.MVC概念

MVC设计模式的任务是将包含业务数据的模块与显示模块的视图解耦。SpringMVC是在Spring框架的基础上做的

2.SpringMVC和JavaEE的比较

在这里插入图片描述

在这里插入图片描述

3.SpringMVC的核心流程

在这里插入图片描述

4.入门案例1

在这里插入图片描述
pom.xml
引入对应的依赖:
在这里插入图片描述

<?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>gy.com</groupId>
    <artifactId>springmvc</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>6</source>
                    <target>6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>


    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.0-alpha-1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

</project>

HelloController
在这里插入图片描述

//访问/hello请求,能够访问到hello.jsp,并且呈现hello springmvc
@Component("/hello")
public class HelloController implements Controller {
@Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("/WEB-INF/hello.jsp");
    modelAndView.addObject("result","SpringMVC");


    return modelAndView;
    }
}

application.xml

  1. HandlerMapping组件 👉 BeanNameUrlHandlerMapping
  2. HandlerAdapter组件 👉 SimpleControllerHandlerAdapter
  3. handler组件 👉 SimpleController
    在这里插入图片描述
<?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:aop="http://www.springframework.org/schema/aop"

       xsi:schemaLocation="
        http://www.springframework.org/schema/beans https://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/aop https://www.springframework.org/schema/aop/spring-aop.xsd">


    <!-- bean definitions here -->
    <!--扫描该包目录以及所有子包:如果发现了组件注册功能的注解-->
    <context:component-scan base-package="com.controller"/>
    <!--根据组件的id(name)来建立映射关系-->
    <!--HandlerMapping 👉 BeanNameUrlHandlerMapping-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <!--HandlerAdapter 👉 SimpleControllerHandlerAdapter-->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

    <!--handler组件 👉 SimpleController-->



    <!-- bean definitions here -->
    <!--通过bean标签完成组件的注册-->
    <!--
        id:组件在容器中的唯一标识
        name:组件名称,通常省略不写,以id作为name
        class:类的全类名
    -->
    <!--<bean id="xxxx" class="xxxx"/>-->
</beans>

hello.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>hello ${result}</h1>
</body>
</html>

web.xml
通过DispatcherServlet初始化WebApplicationContextSpring容器),需要提供contextConfigLocation的值,提供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">
<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:application.xml</param-value>
</init-param>
</servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <!--除了web资源根路径下的jsp文件,其余所有都经过dispatcherServlet-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

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

5.入门案例2(requestmapping-请求url和方法建立映射关系)

方法Handler组件中的方法(HandlerMethod 👉 handler方法)
在这里插入图片描述
<.mvc:annotation-driven/>

5.1 Handler方法(@RequestMapping)

在这里插入图片描述
pom.xml(不变)

HelloController

//handler组件
@Controller
public class HelloController {

    /*@Autowired
    UserService userService;*/
    //handlerMethod
    @RequestMapping("/hello")
    public ModelAndView hello(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/WEB-INF/hello.jsp");
        modelAndView.addObject("result", "SpringMVC2");
        return modelAndView;
    }

    @Autowired
    ApplicationContext applicationContext;

    @RequestMapping("login")
    public ModelAndView login(){
        ModelAndView modelAndView = new ModelAndView("/WEB-INF/hello.jsp");
        modelAndView.addObject("result", "景甜,登录成功");
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
//        System.out.println(Arrays.asList(beanDefinitionNames));
        for (String beanDefinitionName : beanDefinitionNames) {
            System.out.println(beanDefinitionName);
        }
        return modelAndView;
    }
}

application.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:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans https://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
        http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- bean definitions here -->
    <context:component-scan base-package="com.cskaoyan"/>
    <!--RequestMappingHandlerMapping-->
    <!--RequestMappingHandlerAdapter-->
    <!--该标签也帮我们注册了HandlerMapping和HandlerAdapter-->
    <mvc:annotation-driven/>

    <!--缺少包含handlerMethod的handler组件-->

</beans>

hello.jsp不变)

web.xml(不变)

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

6.入门案例3(requestmapping-usage)

在这里插入图片描述
pom.xml(不变)
application.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:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans https://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
        http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:component-scan base-package="com.cskaoyan"/>
    <mvc:annotation-driven/>
</beans>

6.1 url路径映射,多个url映射到一个handler方法上

建立请求url和handler方法之间的映射关系
//value属性:String[] 👉 多个url映射到一个handler方法上
HelloController

@Controller
public class HelloController {

    //value属性:String[] 👉 多个url映射到一个handler方法上
    @RequestMapping({"hello1","hello2","hello3"})
    public ModelAndView hello1(){
        ModelAndView modelAndView = new ModelAndView("/WEB-INF/hello.jsp");
        modelAndView.addObject("result", "SpringMVC3");
        return modelAndView;
    }

    @RequestMapping({"goodbye*","goodbye/*"})
    public ModelAndView goodBye(){
        return new ModelAndView("/WEB-INF/goodbye.jsp");
    }
}

hello

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>hello ${result}</h1>
</body>
</html>

goodbye

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

<h1>拜拜啦啦</h1>
</body>
</html>

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

6.2 请求参数限定

//请求参数限定
@Controller
@RequestMapping("parameter")
public class ParameterLimitController {

    //localhost:8080/parameter/login?username=jingtian&password=niupi
    //@RequestMapping(value = "login",params = "username")//限定请求参数一定要携带username
    //@RequestMapping(value = "login",params = "password")//限定请求参数一定要携带password
    //@RequestMapping(value = "login",params = {"username","password"})//限定请求参数一定要携带username and password
    @RequestMapping(value = "login",params = {"username!=jingtian","password"})//限定请求参数一定要携带username and password,并且username不能是jingtian
    public ModelAndView login(){
        return new ModelAndView("/WEB-INF/parameter.jsp");
    }
}

parameter

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>请求参数限定</h1>
</body>
</html>

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

6.3 求头限定RequestHeader

consumes 👉 ContentType(请求头)
produces 👉 Accept(请求头)

accept和contentType对应的值的类型是 xxx/xxx
在这里插入图片描述

RequestHeaderLimitController

@Controller
@RequestMapping("header")
public class RequestHeaderLimitController {

    @RequestMapping(value = "limit",headers = {"abc","def"})//and
    public ModelAndView headerLimit(){
        return new ModelAndView("/WEB-INF/header.jsp");
    }

    //accept和contentType对应的值的类型是  xxx/xxx
    @RequestMapping(value = "accept",produces = "application/abc")
    public ModelAndView acceptLimit(){
        return new ModelAndView("/WEB-INF/header.jsp");
    }
    @RequestMapping(value = "contenttype",consumes = "application/def")
    public ModelAndView contenttypeLimit(){
        return new ModelAndView("/WEB-INF/header.jsp");
    }
}

header.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>请求头限定</h1>
</body>
</html>

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

6.4 窄化请求

  1. 把请求url从handler方法上的@RequestMapping注解的value属性值中提取出去
  2. 提取到类上 @RequestMapping
  3. Handler方法映射的url = 类上的RequestMapping的value属性值 + 方法上的ReqestuMapping的value属性值
  4. 原格式/user/login
    /user/register
    /user/logout

注意:
方法上的@RequestMapping注解的value属性值,最左边的”/”可以省略,SpringMVC会自行拼接

UserController

@Controller
@RequestMapping("user")
public class UserController {
    @RequestMapping("login")
    public ModelAndView login(){
        return new ModelAndView("/WEB-INF/login.jsp");
    }
    @RequestMapping("register")
    public ModelAndView register(){
        return new ModelAndView("/WEB-INF/register.jsp");
    }
    @RequestMapping("logout")
    public ModelAndView logout(){
        return new ModelAndView("/WEB-INF/logout.jsp");
    }

    //@RequestMapping("modify")
    //@RequestMapping("delete")
}

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>登录</h1>
</body>
</html>

logout.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>退出</h1>
</body>
</html>

register.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>注册</h1>
</body>
</html>

在这里插入图片描述

6.5 请求方法限定

6.5.1注解说明

@GetMapping
@PostMapping

其实就是限定了请求方法的RequestMapping
在这里插入图片描述

RequestMethodLimitController

@Controller
@RequestMapping("method") //窄化请求
public class RequestMethodLimitController {

    //@RequestMapping(value = "get",method= RequestMethod.GET)//url = method/get
    @GetMapping("get")
    public ModelAndView methodGet(){
        ModelAndView modelAndView = new ModelAndView("/WEB-INF/method.jsp");
        modelAndView.addObject("method", "GET");
        return modelAndView;
    }

    //@RequestMapping(value = "post",method = RequestMethod.POST)//url = method/post
    @PostMapping("post")
    public ModelAndView methodPost(){
        ModelAndView modelAndView = new ModelAndView("/WEB-INF/method.jsp");
        modelAndView.addObject("method", "POST");
        return modelAndView;
    }

    //请求方法之间的关系是 or
    @RequestMapping(value = "double",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView methodDouble(){
        ModelAndView modelAndView = new ModelAndView("/WEB-INF/method.jsp");
        modelAndView.addObject("method", "GET or POST");
        return modelAndView;
    }
}

method.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>请求方法限定了:${method}</h1>
</body>
</html>

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

7.入门案例4(return-value)

在这里插入图片描述

pom.xml

<?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>gy.com</groupId>
    <artifactId>springmvc</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>6</source>
                    <target>6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>


    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.0-alpha-1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.3</version>
        </dependency>
    </dependencies>
</project>

application.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:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans https://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
        http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:component-scan base-package="com.controller"/>
    <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">
<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:application.xml</param-value>
</init-param>
</servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <!--除了web资源根路径下的jsp文件,其余所有都经过dispatcherServlet-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

7.1返回值和ModelAndView相关

ModelAndViewRelationController

//返回值和ModelAndView相关
@Controller
public class ModelAndViewRelationController {

    @RequestMapping("hello")
    public String hello(Model model){
        model.addAttribute("result","string");
        return "/WEB-INF/hello.jsp";
    }
}

hello.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>hello ${result}</h1>
</body>
</html>

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

7.2返回值字符串作为ViewName

BaseRespVo

public class BaseRespVo<T> {

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public long getErrno() {
        return errno;
    }

    public void setErrno(long errno) {
        this.errno = errno;
    }

    T data;
    String message;
    long errno;
}

JsonController

//@Controller
//@ResponseBody
@RestController// = @Controller + @ResponseBody
public class JsonController {
    @RequestMapping("login")
    @ResponseBody
    public BaseRespVo login() {
        BaseRespVo baseRespVo = new BaseRespVo();
        baseRespVo.setData("大王");
        baseRespVo.setMessage("登录成功");
        baseRespVo.setErrno(0);
        return baseRespVo;
    }
}

结果;
在这里插入图片描述

7.3请求转发和重定向

返回值为字符串
转发和重定向的是请求
ForwardRirectController

//转发和重定向
    @Controller
public class ForwardRirectController {
@RequestMapping("destination")
    public String destination(){
    return "/WEB-INF/destination.jsp";
}

@RequestMapping("aaa/forward")//aaa/forward 👉 aaa/destination
    public String forward(){
    System.out.println("forward");
    return "forward:/destination";
}

@RequestMapping("aaa/bbb/redirect")//aaa/bbb/redirect 👉 aaa/bbb/destination
public String redirect(){
    System.out.println("redirect");
    return "redirect:/destination";
}
}

destinnation.jsp

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

<h1>转发和重定向</h1>
</body>
</html>

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

相对路径
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值