SpringMVC 常用知识点复习详解

文章目录

    • 1 springmvc入门案例
      • 1.1 springmvc入门程序hello springmvc的步骤
      • 1.2 springmvc组件
      • 1.3 @RequestMapping注解
      • 1.4 解决中文乱码问题
      • 1.5 请求参数绑定
      • 1.6 自定义类型转换器
      • 1.7 springmvc中使用servlet原生的api
      • 1.8 常用注解
    • 2 springmvc中的响应
      • 2.1 返回值是 String 类型
      • 2.2 返回值是 void 类型
      • 2.3 返回值是 ModelAndView 对象
      • 2.4 转发和重定向
      • 2.5 ResponseBody 响应 json 数据
    • 3 Springmvc 实现文件上传

1 springmvc入门案例

1.1 springmvc入门程序hello springmvc的步骤

1 启动服务器,加载配置文件

  • dispatcherServlet 对象创建
  • springmvc.xml配置文件加载
  • HelloController创建成对象

2 发送请求,后台处理请求
SpringMVC 常用知识点复习详解_第1张图片

SpringMVC 常用知识点复习详解_第2张图片

web.xml配置文件:



<web-app>
  <display-name>Archetype Created Web Applicationdisplay-name>
  
  
  <servlet>
    <servlet-name>dispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServletservlet-name>
    <url-pattern>/url-pattern>  
  servlet-mapping>
web-app>

配置springmvc.xml配置文件


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    
    <context:component-scan base-package="com.xiaoxi">context:component-scan>

    
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/pages/">property>
        
        <property name="suffix" value=".jsp">property>
    bean>

    
    <mvc:annotation-driven>mvc:annotation-driven>
beans>

index.jsp 页面,一个超链接,发送请求到hello

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


    Title



    

入门程序

入门程序的链接

新建HelloController控制器类

/**
 * 控制器类
 */
@Controller("helloController")
public class HelloController {
     

    @RequestMapping(path = "/hello")
    public String returnHello() {
     
        System.out.println("hello springmvc");
        return "success";
    }
}

新建success.jsp

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


    Title


    

成功了的页面

第一个页面成功了!

1.2 springmvc组件

  • DispatcherServlet 前端控制器
  • HandlerMapping 处理器映射器
  • Handler 处理器
  • HandlerAdpter 处理器适配器
  • View Resolver 视图解析器
  • View 视图

1.3 @RequestMapping注解

RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

value: 定义处理方法的请求的 URL 地址。

method: 指定请求的method类型, GET、POST、PUT、DELETE等;

params: 定义请求的 URL 中必须包含的参数。或者不包含某些参数。

headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

1.4 解决中文乱码问题

  • post请求解决中文乱码问题:

在web.xml中配置过滤器解决中文乱码问题


<filter>
  <filter-name>characterEncodingFilterfilter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
  <init-param>
    <param-name>encodingparam-name>
    <param-value>UTF-8param-value>
  init-param>
filter>
<filter-mapping>
  <filter-name>characterEncodingFilterfilter-name>
  <url-pattern>/*url-pattern>
filter-mapping>
  • get请求解决中文乱码问题:

    tomacat对GET和POST请求处理方式是不同的,GET请求的编码问题,要改tomcat的server.xml配置文件,如下:

    <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
    

    改为:

    <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" useBodyEncodingForURI="true"/>
    

    如果遇到ajax请求仍然乱码,请把:

    useBodyEncodingForURI="true" 
    

    改为

     URIEncoding="UTF-8"
    

    即可。

1.5 请求参数绑定

请求参数可以绑定的类型有:

  • 基本类型和String类型
  • PoJo类型,或者它的关联对象
  • 集合类型

SpringMVC绑定请求参数是自动实现的,但是要想使用,必须遵循使用要求。

使用要求:

  • 如果是基本类型或者string类型:
    要求我们的参数名称必须和控制器中方法的形参名称保持一致。(严格区分大小写)

  • 如果是PoJo类型,或者它的关联对象:

    要求表单中参数名称和POJo类的属性名称保持一致。并且控制器方法的参数类型是PoJo类型。

  • 如果是集合类型,有两种方式:

    第一种:
    给 List 集合中的元素赋值,使用下标。
    给 Map 集合中的元素赋值,使用键值对。
    第二种:
    接收的请求参数是 json 格式数据。需要借助一个注解实现。
    要求集合类型的请求参数必须在 POJO 中。在表单中请求参数名称要和 POJO 中集合属性名称相同。

绑定的方式示例如下:

<form action="param/testParam" method="post">
    账户名:<input type="text" name="accountName" /><br/>
    密码:<input type="text" name="password" /><br/>
    金额:<input type="text" name="money" /><br/>
    用户名:<input type="text" name="user.username" /><br/>
    年龄:<input type="text" name="user.age" /><br/>
    
    List类型用户1的用户名:<input type="text" name="List[0].username" /><br/>
    年龄:<input type="text" name="List[0].age" /><br/>
    
   	Map类型用户2的用户名:<br/>
    年龄:<br/>
    <input type="submit" value="提交" />
form>

1.6 自定义类型转换器

springmvc会自动帮忙把类型进行转换,比如把String类型转换成Integer类型,但是某些类型比如Date类型,

yy/mm/dd 这种的类型springmvc可以自动转换成Date类型

yy-mm-dd 这种的springmvc就无法自动转换成Date类型

这时需要自定义类型转换器

  • 第一步:定义一个类,实现Converter接口,该接口有两个泛型

    public class StringToDateConverter implements Converter<String, Date> {
           
        @Override
        public Date convert(String s) {
           
            DateFormat dateFormat = null;
            try {
           
                if(StringUtils.isEmpty(s)){
           
                    throw new NullPointerException("请输入要转换的日期");
                }
                dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                Date date = dateFormat.parse(s);
                return date;
            } catch (Exception e) {
           
                throw new RuntimeException(e);
            }
        }
    }
    
  • 第二步:在spring配置文件中配置类型转换器

    首先配置类型转换器工厂 ConversionServiceFactoryBean

    然后给工厂注入一个放在Set集合的新的类型转换器,并配置自定义类型转换器

    
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        
        <property name="converters">
            <set>
                
                <bean id="converter" class="com.xiaoxi.util.StringToDateConverter">bean>
            set>
        property>
    bean>
    
  • 第三步:在annotation - driven 标签中引用配置的类型转换服务

    
    <mvc:annotation-driven conversion-service="conversionService">mvc:annotation-driven>
    

1.7 springmvc中使用servlet原生的api

支持原始的servletAPI的对象有:

HttpServletRequest

HttpServletResponse

HttpSession

Locale

InputStream

OutputStream

Reader

Writer

可以直接写在方法的参数中使用

@RequestMapping( "/testservletAPI")
public string testservletAPI(HttpServletRequest request,HttpservletResponse response,Httpsession session) {
     
    system.out.println(request);
    system.out.println(response) ;
    system.out.println(session);
    return "success";
}

1.8 常用注解

@RequestParam

作用:如果请求中的参数和控制器中的形参名称不一样使用@RequestParam注解,

属性:value, 要请求的参数名称

​ required, 是否必须有请求体,默认值是true,表示必须提供,如果不提供将报错

jsp中的代码:


<mvc:resources location="/css/" mapping="/css/**" >mvc:resources>
<mvc:resources location="/images/" mapping="/images/**" >mvc:resources>
<mvc:resources location="/js/" mapping="/js/**" >mvc:resources>

3 Springmvc 实现文件上传

你可能感兴趣的:(Java开发,ssm,springmvc,响应,文件上传)