springmvc入门

目录

一、Springmvc简介及配置

1. 什么是springMVC?

2. SpringMVC处理请求的流程 

3. SpringMVC核心开发步骤 

4. SpringMVC的组件 

5. 如何在项目中添加springmvc

二、Springmvc之helloword实现

1、HelloController

2、hello.jsp

三、CRUD之常用注解及返回值

1、BookController

 2、index.jsp

3、hello.jsp


一、Springmvc简介及配置

1. 什么是springMVC?

Spring Web MVC是一种基于Java的实现了MVC设计模式的、请求驱动类型的、轻量级Web框架。

2. 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返回呼应给用户,流程结束

3. SpringMVC核心开发步骤 

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

4. 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提供给表单展示和提交到的对象就叫表单对象)

5. 如何在项目中添加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下添加springmvc-servlet.xml(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" xmlns:aop="http://www.springframework.org/schema/aop"
       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-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 通过context:component-scan元素扫描指定包下的控制器-->
    <!--1) 扫描com.javaxl.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    <aop:aspectj-autoproxy/>
    <context:component-scan base-package="com.liaoxin.ssm"/>

    <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
    <!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,-->
    <!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)-->
    <mvc:annotation-driven></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="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--4) 单独处理图片、样式、js等资源 -->
    <!--<mvc:resources location="/css/" mapping="/css/**"/>-->
    <!--<mvc:resources location="/images/" mapping="/images/**"/>-->
    <!--<mvc:resources location="/js/" mapping="/js/**"/>-->


</beans>


5.3 修改web.xml

<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_3_1.xsd"
         version="3.1">
  <display-name>Archetype Created Web Application</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- 读取Spring上下文的监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- Spring MVC servlet -->
  <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/springmvc-servlet.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>


5.4、applicationContext.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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--随着后续学习,框架越学越多,不能将所有的框架配置,放到同一个配置间,否则不便于管理-->
    <import resource="applicationContext-mybatis.xml"></import>
</beans>


二、Springmvc之helloword实现

1、HelloController

package com.liaoxin.ssm.controller;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 被controller标记的类 会交给 spring 进行管理
 * @Controller
 * @Service
 * @Repository
 * @Component
 * 以上四个都代表 当前类 交给Spring容器进行管理
 */

@Controller
public class HelloController {

//    自定义mvc:浏览器发送请求 http://localhost:8080/hello.action?methodName=hello
//    springmvc:浏览器发送请求 http://localhost:8080/helloReq
//    此处是下面的简写版
    @RequestMapping("/helloReq")
    public String hello(){
        System.out.println("hello springmvc...");
//        /hello.jsp
        return "hello";
    }

    @RequestMapping("/hello2")
    public ModelAndView hello2(HttpServletRequest req){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("hello");
        mv.addObject("msg","success");
        return mv;
    }
}

2、hello.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/16
  Time: 17:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
SpringMVC 你好
${msg}
</body>
</html>

运行效果:

 

 方法hello2运行效果:

三、CRUD之常用注解及返回值

1、BookController

 

package com.liaoxin.ssm.controller;

import com.liaoxin.ssm.biz.BookBiz;
import com.liaoxin.ssm.model.Book;
import com.liaoxin.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @RequestMapping 加在 类上面,称窄化路径,其实相当于包的概念
 */
@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookBiz bookBiz;

//    http://localhost:8080/book/list
    @RequestMapping("/add")
    public String add(Book book){
        this.bookBiz.insertSelective(book);
        return "redirect:/book/list";
    }


//    @GetMapping=@RequestMapping(value = "/list",method = RequestMethod.GET)
//    @PostMapping
//    @DeleteMapping
//    @PutMapping
    @RequestMapping("/list")
    public String hello(HttpServletRequest req){
        System.out.println("hello springmvc...");
        PageBean pageBean=new PageBean();
        pageBean.setRequest(req);
        Map map=new HashMap();
        String bname = req.getParameter("bname");
        map.put("bname",bname);
        List<Map> maps = this.bookBiz.listPager(map, pageBean);
        req.setAttribute("lst",maps);
        return "hello";
    }

    @RequestMapping("/edit")
    public String edit(Book book){
        this.bookBiz.updateByPrimaryKey(book);
        return "redirect:/book/list";
    }

    @RequestMapping("/del/{bid}")
    public String del(@PathVariable("bid") Integer bid){
        this.bookBiz.deleteByPrimaryKey(bid);
        return "redirect:/book/list";
    }

    @RequestMapping("/ck/{bid}")
    public String ck(@PathVariable("bid") Integer bid){
        this.bookBiz.selectByPrimaryKey(bid);
        return "toEdit";
    }
}

 2、index.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/16
  Time: 21:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="${pageContext.request.contextPath}/book/list?bname=圣墟">查询所有</a>
    <a href="${pageContext.request.contextPath}/book/add?bid=2&bname=sb&price=9.9">增加</a>
    <a href="${pageContext.request.contextPath}/book/edit?bid=2&bname=suibian&price=9.8">修改</a>
    <a href="${pageContext.request.contextPath}/book/del/2">删除</a>
</body>
</html>

3、hello.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/16
  Time: 17:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
SpringMVC 你好
${msg}
<hr>
${lst}
<c:forEach items="${lst}" var="l">
    ${l.bid}:${l.bname}<hr>
</c:forEach>
</body>
</html>

查询所有:

新增:

 

修改:

 

删除:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值