MVC:简介

M-Model 模型 模型(Model)的职责就是负责业务逻辑,包含两层:业务数据和业务处理逻辑。比如实体类、DAO、Service都属于模型层。
V-View 视图 视图(View)的职责就是负责显示界面和用户交互(收集用户信息)。属于视图层组件的是不包含业务逻辑和控制逻辑的JSP。
C-Controller 控制器 控制器(Controller)的职责是模型层M和视图层V之间的桥梁,用于控制流程,比如:在Servlet项目中的单一控制器ActionServlet。

SpringWebMvc是Spring框架一个非常重要的功能模块,实现了MVC结构,便于简单快速开发MVC结构的web程序,提供了API封装了web开发中常用的功能,简化了web过程
SpringWebMVC核心组件:
DispatcherServlet(控制器,请求入口)
HandlerMapping(控制器,请求派发)
Controller(控制器,请求处理流程)
ModelAndView(模型,封装业务处理结果和视图
) ViewResolver(视图,视图显示处理器)
https://blog.csdn.net/weixin_40001125/article/details/88663468

  1. 问:什么时候使用转发,什么时候使用重定向?
    如果要保留请求域中的数据,使用转发,否则使用重定向。
    以后访问数据库,增删改使用重定向(防止表单重复提交),查询使用转发。
  2. 问:转发或重定向后续的代码是否还会运行?
    无论转发或重定向后续的代码都会执行

SpringMvc、接受参数 - 图1

SpringMvc、接受参数 - 图2

在配置web和spring-mvc.xml过程中常用的架包关键字:
web.xml
1.控制器的请求入口接受请求:DispatcherServlet
2.解决请求响应的编码解码格式的问题:CharacterEncodingFilter

spring-mvc.xml:原本的文件就有许多链接与pom.xml里面的相对应,因为不知道使用哪个,便全部都写进来
写进来,然后在里面配置许多bean

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  6. xmlns:jee="http://www.springframework.org/schema/jee"
  7. xmlns:tx="http://www.springframework.org/schema/tx"
  8. xmlns:aop="http://www.springframework.org/schema/aop"
  9. xmlns:mvc="http://www.springframework.org/schema/mvc"
  10. xmlns:util="http://www.springframework.org/schema/util"
  11. xmlns:jpa="http://www.springframework.org/schema/data/jpa"
  12. xsi:schemaLocation="
  13. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  14. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
  15. http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
  16. http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
  17. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
  18. http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
  19. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
  20. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  21. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
  22. </beans>

3.控制器的派发:SimpleUrlHandlerMapping 后来我们使用注解开发利用使用扫描器和mvc扫描器就可以代替这个
4.封装视图:InternalResourceViewResolver

//web.xml
<servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring-mvc.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>



//Spring-mvc.xml
<!-- 定义请求处理 -->
        <bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <!--指定请求和controller对应关系  -->
        <property name="mappings">
            <props>
                <prop key="/demo/hello.do">helloController</prop>
            </props>
        </property>
        </bean>

        <!--声明Controller  -->
        <bean id="helloController" class="com.zhiyou100.controller.HelloController"/>
        <!--定义视图解析器ViewResovler  -->
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
        </bean>


//HelloController
package com.zhiyou100.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class HelloController implements Controller{

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("hello,Controller");
        return new ModelAndView("jsp/hello");
    }


}

二、几种接收参数的方法

步骤:首先我们还是得现配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>Spring03</display-name>
  <welcome-file-list>
    <welcome-file>/WEB-INF/login1.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring-*.xml</param-value>
      </init-param>
  </servlet>
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

通过配置的spring.xml分配请求

//这里的注解扫描是扫描所有com.zhiyou100包路径下的所有java文件
<!-- 开启注解扫描 -->
    <context:component-scan base-package="com.zhiyou100"/>
    <!--开启mvc注解扫描  -->
    <mvc:annotation-driven/>    
    <!--定义试图解析器  -->
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>

接着进行接受从jsp.xml中获取的参数

<h1>测试表单</h1>
    <form action="demo/test11.do" post="post">
    账号:<input type="text" name="userName"/><br>
    密码:<input type="password" name="password"/><br>
    <input type="submit" value="提交">
    </form>

总结:

接收对象:

1.使用httpservletrequest的请求获取页面form表单的元素

2.使用@requestParam注解的方式直接获取form表单的提交元素

3.使用对象参数,此时需要封装一个user类,此时适用于页面元素很多的情况下

传出数据:
1.通过视图控制器ModelAndView传出数据
2.使用ModelMap传出数据
3.使用@ModelAttribute传出bean属性
4.使用Session
5.返回String:试图信息:逻辑视图解析器

@Controller
@RequestMapping("/demo")
public class ManagerController {
    //1.使用request接受参数
    @RequestMapping("/test1.do")
    public ModelAndView test1(HttpServletRequest request){
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        System.out.println(userName);
        return new ModelAndView("hello/hello");

    }

    //2.使用方法参数直接接受参数
    @RequestMapping("/test2.do")
    public ModelAndView test2(@RequestParam("userName") String userName,
            @RequestParam("password")String pwd){
        System.out.println(userName);
        System.out.println(pwd);
        return new ModelAndView("hello/hello");

    }

    //3.使用对象接受参数
    @RequestMapping("/test3.do")
    public ModelAndView test3(User user){
        System.out.println(user.getUserName());
        System.out.println(user.getPassword());
        System.out.println("+++");
        return new ModelAndView("hello/hello");

    }

    //传出数据
    //1.使用ModelAndView传出数据
    @RequestMapping("/test4.do")
    public ModelAndView test4(){
        Map<String,Object>data=new HashMap<String,Object>();
        data.put("success", "true");
        data.put("message", "操作成功");
        return new ModelAndView("hello/hello",data);
    }

    //2.使用ModelMap传出数据
    @RequestMapping("/test5.do")
    public ModelAndView test5(ModelMap model){
        model.addAttribute("success",false);
        model.addAttribute("message","操作失败");
        return new ModelAndView("hello/hello");
    }

    //3.使用@ModelAttribute传出bean属性
    @ModelAttribute("age")
    public int getAge(){
        return 18;

    }

    //4.使用@ModelAttribute传出参数值
    @RequestMapping("test6.do")
    public ModelAndView test6(@ModelAttribute("userName") String userName,
            @ModelAttribute("password") String password){

        return new ModelAndView("hello/hello");
    }
    //5.使用Session
        @RequestMapping("test7.do")
        public ModelAndView test7(HttpServletRequest request,User user){
            HttpSession session = request.getSession();
            session.setAttribute("langs", "bigdata");
            return new ModelAndView("hello/hello");
        }


        //6.返回String:试图信息:逻辑视图解析器
        @RequestMapping("test8.do")
        public String test8(User user,ModelMap model){
        model.addAttribute("user",user);
        return "hello/hello";
        }

        //7.系统错误页面
        @RequestMapping("test9.do")
        public String test9(){

            return "hello/error";
        }

        /*
         * 以上都是转发
         */
        //8.重定向使用RedirctView
        @RequestMapping("/test10.do")
        public ModelAndView test10(User user){
            if(user.getUserName().equals("zhangsan")){
                return new ModelAndView("hello/hello");
            }else{
                return new ModelAndView(new RedirectView("test9.do"));
            }    
        }


        //9.使用redirect重定向
        @RequestMapping("/test11.do")
        public String test11(User user){
            if("zhangsan".equals(user.getUserName())){
                return "hello/hello";
            }else{
                return "redirect:test9.do";
            }
        }



}