springMVC笔记整理

springMVC简介

配置文件方式搭建环境

运行过程源码跟踪

注解方式搭建环境

基本数据类型和对象类型作为参数

复杂数参数和restfu风格参数

跳转方式

@ResponseBody

jsp9大内置对象和4个作用域

作用域传值的四个方式

文件的上传和下载

带有头像的注册

自定义拦截器

练习登录

springMVC运行原理

springMVC简介:

SpringMVC重要组件:

DispatcherServlet:前段控制器,接受所有请求,过滤jsp;【必须进行配置使得xml文件生效】

HandlerMapping:解析请求格式,判断希望调用那个方法;【必须进行配置】

HandlerAdapter:负责调用具体的方法;【走默认,不必在xml中进行配置】

进行页面跳转

  req.getRequestDispatcher("index.jsp").forward(req, resp);

ViewResovler:视图解析器,解析结果,准备跳转到具体的物理视图。

 

使用纯配置文件搭建springMVC环境:

Web.xml无法打包的jar包。即使打包到jar包中也无效。Tomcat在加载项目的时候必须到web-info中查找web.xml,其他任何路径无效,jar包中的东西都在隐藏的classes文件中,所以必须自己配置。

  1. 导入jar包

 

  1. 配置web.xml

 

视图解析器:

 

<?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_3_0.xsd" version="3.0">

  <display-name>springmvc01</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  <servlet>

    <servlet-name>springmvc</servlet-name>

    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

   

   

    <init-param><!-- 必须放在startup上边,否则报错 -->

       <param-name>contextConfigLocation</param-name>

       <param-value>classpath:springmvc.xml</param-value>

    </init-param>

   

    <load-on-startup>1</load-on-startup><!-- 自启动,tomcat在启动时就加载,否则在访问时加载 -->

   

  </servlet>

  <servlet-mapping>

    <servlet-name>springmvc</servlet-name>

    <url-pattern>/</url-pattern><!-- 拦截除了jsp以外,其它所有的请求 -->

  </servlet-mapping>

</web-app>

 

 

package com.pshdhx.test;

 

import org.springframework.context.ApplicationContext;

import org.springframework.web.servlet.HandlerAdapter;

import org.springframework.web.servlet.HandlerMapping;

import org.springframework.web.servlet.ViewResolver;

 

public class Test {

    public static void main(String[] args) {

       ApplicationContext ac = null;   //加载dispatcherServlet就创建了ApplicationContext的接口-ConfigurableApplicationContext的容器。加载xml文件

       HandlerMapping hm = null;   //urlMapping

       HandlerAdapter ha = null;   //走方法中的语句

       ViewResolver rs = null;     //走解析路径

      

    }

}

 

package com.pshdhx.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 DemoController implements Controller {

 

    @Override

    public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {

       System.out.println("执行了控制器DemoController"); //走默认适配器

       ModelAndView mv = new ModelAndView("main");   //走默认视图解析器

       return mv;

    }

 

}

 

<?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"

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

    <bean id="demo123" class="com.pshdhx.controller.DemoController"></bean>

    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

       <!-- 源码中是map方法,所以使用property,的map子标签 -->

       <property name="urlMap">

           <map>

              <!-- 用来解析控制器逻辑名 -->

              <entry key="demo" value-ref="demo123"></entry>

           </map>

       </property>

    </bean>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

       <property name="prefix" value="/"></property>    <!-- name为源码中的前缀 -->

       <property name="suffix" value=".jsp"></property> <!-- name为源码中的后缀,这样就省去了controller ModelAndView跳转路径的全路径或全名 -->

    </bean>   

</beans>

springMVC运行过程源码跟踪:

父类的父类往上找:

 

WebApplication是spring容器

说明了springspringmvc是父子容器

  Springmvc能够调用spring容器中的方法。

 

 

因为service是在spring容器中,所以在controller中允许注入service方法

请求方法,放行请求

 

 

 

 

 

springMVC注解方式环境搭建:

  1. 扫描注解
  2. 用到mvc命名空间,并且注解驱动
  3. 写控制器类

 

<?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 base-package="com.pshdhx.controller"></context:component-scan>

       <!-- 注解驱动 -->

    <mvc:annotation-driven></mvc:annotation-driven>

       <!-- 静态资源 css js image -->

    <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>    <!-- location是左边工作目录下 mapping是浏览器逻辑名字 -->

</beans>

package com.pshdhx.controller;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

 

@Controller   //把这个类交给容器去管理

public class DemoController {

    @RequestMapping("demo")  //使用注解  ==控制器逻辑名

    public String demo(){

       System.out.println("执行demo");

       return "main.jsp";

    }

}

 

 

基本数据类型和对象类型作为参数:

  1. 复制的web项目改名修改后也不能运行,得修改.setting,之间建立项目较好
  2. 在web.xml修改编码

 

  <!-- 字符编码过滤器 -->

    <filter>

       <filter-name>encoding</filter-name>

       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

       <init-param>

           <param-name>encoding</param-name>

           <param-value>UTF8</param-value>

       </init-param>

    </filter>

    <filter-mapping>

       <filter-name>encoding</filter-name>

       <url-pattern>/*</url-pattern>

    </filter-mapping>

  1. 控制传递值

 

package com.pshdhx.controller;

 

import javax.servlet.http.HttpServletRequest;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

 

@Controller

public class DemoController03 {

    @RequestMapping("demo03")

    public String controller(String username,int age,HttpServletRequest req){

       System.out.println("执行demo03");

       System.out.println(""+username+"***"+age+"通过action的value到控制器方法的参数,控制jsp页面传值到控制器");

       req.setAttribute("demo03", "测试从java控制器传值到jsp页面");

       return "main.jsp";

    }

}

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

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

</head>

<body>

main.jsp

${demo03 }

</body>

</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

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

</head>

<body>

    <form action="demo03" method="post">

       <input type="text" name="username"><br>

       <input type="text" name="age"><br>

       <input type="submit" value="提交"><br>

    </form>

</body>

</html>

 

  1. demo默认是单例的single,线程不安全
  2. 使用别名。

如果没有参数,报错500,不能正常跳转

但是如果int变为Integer,则能够正常跳转

Int默认值:

 

 

 

 

复杂参数和restfu风格参数:

 

 

跳转方式:

  1. 默认的方式是请求转发
  2. 重定向

  添加redirect路径:

  添加forward路径:

 

 

 

自定义视图解析器:

表示前边的demo中不需要/了

Redirect和forward表示直接跳转到文件,而不是在某个路径下的文件。

不加forward:表示查找demo11的jsp页面 404

加上forward:可以找到demo11的控制器 success

 

 

@ResponseBody:

 

 

加上responseBody后,不管返回值是什么,恒不跳转。在页面输出返回值。

responseBody以jackson形式底层实现,需要引入上面三个包。

设置响应头contentType的形式。

能力提升-树形菜单的显示-jquery:

  1. 导入jar包
  2. 配置web.xml
  1. 上下文参数spring
  2. 监听器:
  3. 前端控制器servlet
  4. 字符编码过滤器

 

 

能打开就打开,打不开就下载

 

 

 

Jsp9大内置对象和4个作用域:

Classpath:被编译到了这里

 

 

 

作用域传值的4个方式;

package com.pshdhx.controller;

import javax.servlet.ServletContext;

/**

 * 测试内置对象作用域

 */

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

 

@Controller

public class DemoController {

    @RequestMapping("demo1")

    public String demo1(HttpServletRequest req,HttpSession sessionParam){

       //测试request的作用域

       req.setAttribute("req", "req的值");

      

       //测试sessionsessionParam

       HttpSession session = req.getSession();

       session.setAttribute("session", "session的值");

       sessionParam.setAttribute("sessionParam", "sessionParam的值");

      

      

       //application 但是直接定义servletcontext的参数不行:是一个接口,不允许实例化和注入。

       ServletContext application = req.getServletContext();

       application.setAttribute("application", "application的值");

      

       return "/index.jsp";

    }

}

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

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

</head>

<body>

request:${requestScope.req }<br>

session:${sessionScope.session }<br>

sessionParam:${sessionScope.sessionParam }<br>

application:${applicationScope.application }

 

</body>

</html>

<?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_3_0.xsd" version="3.0">

  <display-name>springmvc01</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.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:springmvc.xml</param-value>

    </init-param>

    <load-on-startup>1</load-on-startup>

  </servlet>

  <servlet-mapping>

    <servlet-name>springmvc</servlet-name>

    <url-pattern>/</url-pattern>

  </servlet-mapping>

  <!-- 字符编码过滤器  启动加载不是访问加载-->

    <filter>

       <filter-name>encoding</filter-name>

       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

       <init-param>

           <param-name>encoding</param-name>

           <param-value>UTF8</param-value>

       </init-param>

    </filter>

    <filter-mapping>

       <filter-name>encoding</filter-name>

       <url-pattern>/*</url-pattern>

    </filter-mapping>

</web-app>

<?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 base-package="com.pshdhx.controller"></context:component-scan>

       <!-- 注解驱动 -->

    <mvc:annotation-driven></mvc:annotation-driven>

       <!-- 静态资源 css js image -->

    <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>    <!-- location是左边工作目录下 mapping是浏览器逻辑名字 -->

</beans>

 

 

文件下载:

若果是rar的话,直接下载,但是txt是直接打开。

 

 

文件上传:

 

 

 

 

package com.pshdhx.controller;

 

import java.io.File;

import java.io.IOException;

import java.util.UUID;

 

import org.apache.commons.io.FileUtils;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.multipart.MultipartFile;

 

/**

 * 测试文件上传需要引入commoms-fileload和commons-io两个jar包

 * 并且form标签中要 :enctype="multipart/form-data" type="file"

 * @author Administrator

 *

 */

@Controller

public class DemoController {

         @RequestMapping("upload")

         public String upload(MultipartFile file,String name) throws IOException{

                  String fileName = file.getOriginalFilename();

                  String suffix = fileName.substring(fileName.lastIndexOf("."));

                  //判断上传文件类型

                  if(suffix.equalsIgnoreCase(".png")){

                          String uuid = UUID.randomUUID().toString();

                          FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:/"+uuid+suffix));

                          return "/index.jsp";

                  }else{

                          return "error.jsp";

                  }

         }

}

 

<?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 base-package="com.pshdhx.controller"></context:component-scan>

       <!-- 注解驱动 -->

    <mvc:annotation-driven></mvc:annotation-driven>

       <!-- 静态资源 css js image -->

    <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>   <!-- location是左边工作目录下 mapping是浏览器逻辑名字 -->

    <mvc:resources location="/file/" mapping="/file/**"></mvc:resources>

   

    <!-- MultipartResovler解析器 -->

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

       <property name="maxUploadSize" value="50"></property>

    </bean>

    <!-- 异常解析器 -->

    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">

       <property name="exceptionMappings">

           <props>

              <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/error.jsp</prop>

           </props>

       </property>

    </bean>

</beans>

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

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

</head>

<body>

<form action="upload" enctype="multipart/form-data" method="post">

    姓名:<input type="text" name="name"><br>

    文件:<input type="file" name="file"><br>

    <input type="submit" value="上传">

</form>

</body>

</html>

 

能力提升-带有头像的注册:

过程截图:

 

 

 

 

 

能力提升-下载:

 

 

 

自定义拦截器:

 

 

 

拦截器栈:

 

 

练习-登录验证:

 

Spingmvc运行原理:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值