Springmvc入门

在这里插入代码片@toc

1.什么是springMVC?

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

2.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.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

导入依赖

<!--  替换掉tentcont -->
<dependency>
   <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
</dependency>

<!-- <tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version> 添加版本号   -->
 <dependency>
    <groupId>org.apache.tomcat</groupId>
     <artifactId>tomcat-jsp-api</artifactId>
     <version>${tomcat-jsp-api.version}</version>
 </dependency>


<!-- 添加分页标签 -->
 <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>



修改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>

    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>

    <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和web项目集成end -->

    <!-- 防止Spring内存溢出监听器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>



    <!-- 中文乱码处理 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!--web.xml 3.0的新特性,是否支持异步-->
        <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>

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

在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" 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.hu"/>

    <!--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="/WEB-INF/"/>-->
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

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

</beans>


SpringMVC关于结果集的五种处理

package com.yinyi.controller;

import com.yinyi.model.Book;
import com.yinyi.service.BookService;
import org.apache.commons.io.FileUtils;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author殷熠
 * @site
 * @company
 * @create  2019-09-28 11:10
 *
 * 关于结果集处理分为五种情况
 * 1.转发到页面(webapp下)
 * 2.转发到action请求
 * 3.重定向到页面webapp下)
 * 4.重定向到action
 * 5.转发到web—inf下的页面
 *
 */
@Controller
public class HelloController {

    @Autowired
    private BookService bookService;


//转发
    @RequestMapping("hello")
    public String hello(HttpServletRequest request){
        request.setAttribute("msg","转发到页面的方式");
        return "hello";
    }

//    重定向到action中
    @RequestMapping("hello2")
    public String redirectPage(HttpServletRequest request){
        request.setAttribute("msg","重定向到页面的方式");
        return "redirect:hello";
    }
    @RequestMapping("hello3")
    public String redirectPage2(HttpServletRequest request){
        Object msg = request.getAttribute("msg");
        return "redirect:/hello.jsp";
    }

    @RequestMapping("hello4")
    public String forwardAction(HttpServletRequest request){
        request.setAttribute("msg","重定向到页面的方式");
        return "forward:hello3";
    }

    @RequestMapping("hello5")
    public String forwardAction2(HttpServletRequest request){
        request.setAttribute("msg","转发到安全界面");
        return "forward:abc";
    }

想要转发到安全目录需要在spring-mvc.xml添加

 <property name="prefix" value="/WEB-INF/"/><!--这是访问安全目录的操作-->

想要访问到项目里面的静态资源文件的话需要spring-mvc.xml里面添加

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

SpringMVC增删改查案例

package com.yinyi.controller;

        import com.yinyi.model.Book;
        import com.yinyi.service.BookService;
        import com.yinyi.util.PageBean;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Controller;
        import org.springframework.web.bind.annotation.GetMapping;
        import org.springframework.web.bind.annotation.PathVariable;
        import org.springframework.web.bind.annotation.PostMapping;
        import org.springframework.web.bind.annotation.RequestMapping;

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

/**
 * @author殷熠
 * @site
 * @company
 * @create  2019-09-28 20:57
 *
 */
@Controller
@RequestMapping("/book")
public class BookConTroller {
    @Autowired
    private BookService bookService;
    /**
     * postman
     * swgger2
     *
     */

    @RequestMapping("/list")
    public  String list(Book book, HttpServletRequest request){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        List<Map> list = this.bookService.listPager(book,pageBean);
        request.setAttribute("bookList",list);
        request.setAttribute("pageBean",pageBean);

        return  "bookList";
    }

    @RequestMapping("/preSave")
    public  String preSave(Book book, HttpServletRequest request){
        if(book.getBid() != null){
            Book b = this.bookService.selectByPrimaryKey(book.getBid());
            request.setAttribute("b",b);
        }
        return  "bookEdit";
    }

    @RequestMapping("/add")
    public  String add(Book book, HttpServletRequest request){
        this.bookService.insert(book);
        return  "redirect:/book/list";
    }

    @RequestMapping("/del/{bid}")
    public  String del(@PathVariable(value = "bid") Integer bid, HttpServletRequest request){
        this.bookService.deleteByPrimaryKey(bid);
        return  "redirect:/book/list";
    }

    @RequestMapping("/edit")
    public  String edit(Book book, HttpServletRequest request){
        this.bookService.updateByPrimaryKeySelective(book);
        return  "redirect:/book/list";
    }
}

前端代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
     <%--<%@ taglib uri="/zking" prefix="z" %>--%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	function add(){
		// window.location.href = "bookEdit.jsp";
		window.location.href="${pageContext.request.contextPath}/book/preSave";
	}
	
	function update(bid){
		window.location.href = "${pageContext.request.contextPath}/book/preSave?bid="+bid;
	}
	
	function del(bid){
		window.location.href = "${pageContext.request.contextPath}/book/del/="+bid;
	}
</script>
</head>
<body>
	<form action="${pageContext.request.contextPath}/book/list"
		method="post">
		书名:<input type="text" name="bname"> <input type="submit"
			value="确定">
	</form>
	<button onclick="add();">新增</button>
	<table border="1" width="100%">
		<tr>
			<td>编号</td>
			<td>名称</td>
			<td>价格</td>
			<td>操作</td>
		</tr>
		<c:forEach items="${bookList }" var="b">
			<tr>
				<td>${b.bid }</td>
				<td>${b.bname }</td>
				<td>${b.price }</td>
				<td>
					<button onclick="update(${b.bid });">修改</button>&nbsp;&nbsp;&nbsp;
					<button onclick="del(${b.bid });">删除</button>
				</td>
			</tr>
		</c:forEach>
	</table>
	<%--<z:page pageBean="${pageBean }"></z:page>--%>
</body>
</html>

自定标签

<?xml version="1.0" encoding="UTF-8" ?>

<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">
    
  <description>zking 1.1 core library</description>
  <display-name>zking core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>z</short-name>
  <uri>/zking</uri>

 <tag>
    <name>page</name>
    <tag-class>com.yinyi.util.PageTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>pageBean</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  
</taglib>

本次的分享就到此结束,感谢您的观看。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值