• springmvc入门


    目标
    1、Springmvc简介及配置
    2、Springmvc之helloword实现
    3、Springmvc常用注解及返回值处理
    4、Springmvc静态资源处理

    Springmvc简介及配置
    什么是springMVC?
    Spring Web MVC是一种基于Java的实现了MVC设计模式的、请求驱动类型的、轻量级Web框架。

    SpringMVC处理请求的流程
    2.1 首先用户发送请求–>DispatherServlet
    2.2 DispatcherServlet–>HandlerMapping
    2.3 DispatcherServlet–>HandlerAdapter
    2.4 HandlerAdapter–>处理器功能处理方法的调用
    2.5 ModelAndView的逻辑视图名–>ViewRecolver
    2.6 View–>渲染
    2.7 返回控制权给DispatcherServlet,由DispatcherServlet返回呼应给用户,流程结束

    SpringMVC核心开发步骤
    3.1 DispatcherServlet在web.xml中的部署描述,从而拦截请求到springMVC
    3.2 HandlerMapping的配置,从而将请求映射到处理器
    3.3 HandlerAdapter的配置,从而支持多种类型的处理器
    3.4 处理器(页面控制器)的配置,从而刊行功能处理
    3.5 ViewResolver的配置,从而将逻辑视图名解析为具体的视图技术

    SpringMVC的组件
    4.1 前端控制器(DispatcherServlet)
    4.2 请求到处理器映射(HandlerMapping)
    4.3 处理器适配器(HandlerAdapter)
    4.4 视图解析器(ViewResolver)
    4.5 处理器或页面控制器(Controller)
    4.6 验证器(Validator)
    4.6 命令对象(Command 请求参数绑定到的对象就叫命令对象)
    4.7 表单对象(Form Object提供给表单展示和提交到的对象就叫表单对象)

    如何在项目中添加springmvc
    5.1 添加相关依赖

     <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
          </dependency>

    <!-- ********************** JSTL依赖 ********************** -->
    <!-- 缺少下面的这两个jar包会报java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config-->
    <!-- 原因:org.springframework.web.servlet.view.JstlView在视图解析时需要这二个jar包-->

    <dependency>
              <groupId>jstl</groupId>
              <artifactId>jstl</artifactId>
              <version>1.2</version>
          </dependency>
          <dependency>
              <groupId>taglibs</groupId>
              <artifactId>standard</artifactId>
              <version>1.1.2</version>
          </dependency>

    5.2 在WEB-INF下添加spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!-- 通过context:component-scan元素扫描指定包下的控制器-->
        <!--1) 扫描com.hmc.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
        <context:component-scan base-package="com.hmc.ssm" use-default-filters="false">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    
    
        <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
        <!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,-->
        <!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)-->
        <mvc:annotation-driven/>
    
    
        <!--3) ViewResolver -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
            <property name="viewClass"
                      value="org.springframework.web.servlet.view.JstlView"></property>
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
        <!--4) 单独处理图片、样式、js等资源 -->
         <!--<mvc:resources location="/css/" mapping="/css/**"/>
         <mvc:resources location="/js/" mapping="/js/**"/>-->
         <mvc:resources location="/WEB-INF/images/" mapping="/images/**"/>
    </beans>

    5.3 修改web.xml

    <!-- 修改web.xml由2.3至3.0 -->
    <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_3_0.xsd"
             id="WebApp_ID" version="3.0">
    
    
    
    
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
      </context-param>
    
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
    
      <!--防止spring内存溢出的监听器-->
      <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
      </listener>
      <!--  2) 中文乱码过滤器-->
      <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
    <!--  3) 配置SpringMVC核心控制器DispatcherServlet-->
      <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--此参数可以不配置,默认值/WEB-INF/springmvc-servlet.xml-->
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <!--web.xml 3.0新特性,是否支持异步-->
        <async-supported>true</async-supported>
      </servlet>
      <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
    
    
    </web-app>

    Springmvc之helloword实现

    @Controller
    public class HelloController {
        @ResponseBody
        @RequestMapping("/hello1")
        public String hello1(){
            System.out.println("hello1 springmvc ");
            return "hello springmvc ";
       
    
        @RequestMapping("/hello2")
        public String hello2(){
            System.out.println("hello2 springmvc ")
            return  "hello";
        }
        @ResponseBody
        @RequestMapping("/hello3")
        public Map hello3(){
            System.out.println("hello3 springmvc")
            Map map = new HashMap();
            map.put("total",12);
            map.put("rows","一串的数据");
            return  map;
        }
        }

    Springmvc常用注解及返回值处理

    Controller
    Requestmapping
    Requestparam

    @Controller
    @RequestMapping("/book")
    public class BookController {
        @Autowired
        private BookService bookService;
    
        @RequestMapping("/list")
        public String list(Book book,HttpServletRequest req){
            PageBean pageBean = new PageBean();
            pageBean.setRequest(req);
            List<Book> books = this.bookService.listPager(book, pageBean);
            req.setAttribute("bookList",books);
            req.setAttribute("pageBean",pageBean);
            return "bookList";
        }
        @RequestMapping("/preSave")
        public String preSave(Book book,HttpServletRequest req){
        if(book != null &&book.getBid()!=null && book.getBid()!=0){
            Book b = this.bookService.selectByPrimaryKey(book.getBid());
            req.setAttribute("book2",b);
        }
            return "bookEdit";
        }
        @RequestMapping("/add")
        public String add(Book book,HttpServletRequest req){
            this.bookService.insert(book);
            return "redirect:/book/list";
        }
        @RequestMapping("/del/{bid}")
        public String del(@PathVariable("bid") Integer bid, HttpServletRequest req){
            this.bookService.deleteByPrimaryKey(bid);
            return "redirect:/book/list";
        }
        @RequestMapping("/edit")
        public String edit(Book book,HttpServletRequest req){
            this.bookService.updateByPrimaryKeySelective(book);
            return "redirect:/book/list";
        }
        @RequestMapping("/del/{typeid}/{bid}")
        public String xxx(@PathVariable("typeid") Integer typeid,@PathVariable("bid") Integer bid, HttpServletRequest req){
            this.bookService.deleteByPrimaryKey(bid);
            return "redirect:/book/list";
        }
    }


    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
        <%--<%@page isELIgnored="false" %>--%>
        <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <h2>小说目录</h2>
        <br>
    
        <form action="${pageContext.request.contextPath}/book/list"
            method="post">
            书名:<input type="text" name="bookname"> <input type="submit"
                value="确定">
                
        </form>
        <a href="${pageContext.request.contextPath}/book.action?menthodName=preSave">新增</a>
        
        <table border="1" width="100%">
            <tr>
                <td>编号</td>
                <td>名称</td>
                <td>价格</td>
                <td>操作</td>
            </tr>
            <c:forEach items="${bookList }" var="b">
                <tr>
                    <td>${b.id }</td>
                    <td>${b.bookname }</td>
                    <td>${b.price }</td>
                    <td>
                        <a href="${pageContext.request.contextPath}/book/preSave?bid=${b.id}">修改</a>
                    <a href="${pageContext.request.contextPath}/book/del?bid=${b.id}">删除</a>
                    </td>
                </tr>
            </c:forEach>
        </table>
    
    
        
    </body>
    </html>

  • 相关阅读:
    欧拉函数模板
    Django Views Decorator
    Anaconda3 安装报错 bunzip2: command not found
    Windows 错误 0x80070570
    GitHub报错error: bad signature
    failed to push some refs to 'git@github.com:RocsSun/mytest.git
    更新GitHub的仓库
    Git连接GitHub
    Git的初始化设置
    Git的选项参数
  • 原文地址:https://www.cnblogs.com/xmf3628/p/11739061.html
Copyright © 2020-2023  润新知