创建一个web工程

 

导入jar

 

配置web.xml

在web.xml配置前端控制器:DispatcherServlet

<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 默认加载方式
               默认加载必须规范:
               * 文件命名:servlet-name-servlet.xml====springmvc-servlet.xml
               * 路径规范:必须在WEB-INF目录下面
         -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <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>
</web-app>

配置springmvc.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

    <!-- 配置处理器映射器,springmvc默认的处理器映射器
        BeanNameUrlHandlerMapping:根据bean(自定义Controler)的name属性的url去寻找hanler(Action:Controller)
         -->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>

    <!-- 配置处理器适配器执行Controlelr ,springmvc默认的
         SimpleControllerHandlerAdapter:执行Controller
         -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>


    <!--配置自定义Controller
    访问url:http://localhost:8080/hello.do
    -->
    <bean name="/hello.do" class="cn.itcast.controller.MyController"></bean>

    <!-- 配置sprigmvc视图解析器:解析逻辑试图
              后台返回逻辑试图:index
             视图解析器解析出真正物理视图:前缀+逻辑试图+后缀====/WEB-INF/jsps/index.jsp
         -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsps/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>


</beans>

自定义Controller

package cn.itcast.controller;


import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by weihu1 on 2018/8/21 10:39
 */
public class MyController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        // 接受请求,接受参数,验证参数
        //封装参数,调用业务方法
        //返回视图
        ModelAndView mv = new ModelAndView();
        //设置页面回显数据
        mv.addObject("hello", "欢迎学习springmvc!");

        //指定跳转的视图
        //返回物理视图
        //mv.setViewName("/WEB-INF/jsps/index.jsp");
        //返回逻辑视图
        mv.setViewName("index");

        return mv;
    }
}

定义视图页面

根据视图解析路径:WEB-INF/jsps/index.jsp

<%--
  Created by IntelliJ IDEA.
  User: weihu1
  Date: 2018/8/21
  Time: 10:33
  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>
  <h1>${hello}</h1>
  </body>
</html>

 

 

处理器适配器

SimpleControllerHandlerAdapter

功能:执行controller

           调用controller里面方法,返回modelAndView。

<!-- 配置处理器映射器,springmvc默认的处理器映射器
        BeanNameUrlHandlerMapping:根据bean(自定义Controler)的name属性的url去寻找hanler(Action:Controller)
         -->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>

HttpRequestHandlerAdapter

功能:执行controller

    <!--HttpRequestHandlerAdapter负责实现接口HttpRequestHandler的后端
    控制器
    -->
    <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"></bean>

2个处理器适配器能共存?

可以共存

命令控制器

Springmvc通过命令设计模式接受页面参数。

 

自定义命令控制器

package cn.itcast.controller;

import cn.itcast.domain.User;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by weihu1 on 2018/8/21 16:09
 */
public class CommandController extends AbstractCommandController {

    //指定参数绑定到那个javaBean
    public CommandController(){
        this.setCommandClass(User.class);
    }
    @Override
    protected ModelAndView handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, BindException e) throws Exception {
        //把命令对象强转成User对象
        User user=(User)o;
        ModelAndView mv=new ModelAndView();
        mv.addObject("user",user);
        mv.setViewName("index");
        return mv;
    }

    /**
     * Create by hu.wei on 2018/8/21 17:01
     * @Description: 这个方法会先自动执行
     */
    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        super.initBinder(request, binder);

        String str=request.getParameter("birthday");
        if(str.contains("/")){
            binder.registerCustomEditor(Date.class,
                    new CustomDateEditor(new SimpleDateFormat("yyyy/MM/dd"),true));
        }else {
            binder.registerCustomEditor(Date.class,
                    new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
        }
    }
}

 

定义javaBean

package cn.itcast.domain;

import java.util.Date;

/**
 * Created by weihu1 on 2018/8/21 16:10
 */
public class User {

    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

 

 

封装参数页面

add.jsp

<%--
  Created by IntelliJ IDEA.
  User: weihu1
  Date: 2018/8/21
  Time: 10:33
  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>

  <form action="/command.do" method="post">
    姓名:<input type="text" name="username" id="username">
    生日:<input type="text" name="birthday" id="birthday">
    姓别:<input type="text" name="sex" id="sex">
    地址:<input type="text" name="address" id="address">
    <input type="submit" value="提交">

  </form>
  </body>
</html>

跳转到add页面

由于add页面在WEB-INF下面不能直接访问,需要通过Controller来访问。

package cn.itcast.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by weihu1 on 2018/8/21 16:20
 */
public class ToAddController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //跳转到add添加页面视图
        ModelAndView mv=new ModelAndView();
        mv.setViewName("add");
        return mv;
    }
}

在springmvc配置bean

 <bean name="/command.do" class="cn.itcast.controller.CommandController"></bean>
    <bean name="/toAdd.do" class="cn.itcast.controller.ToAddController"></bean>

中文乱码解决

get请求

 

Post乱码

Spring编码过滤器:在web.xml配置

<!--解决post请求乱码问题-->
    <filter>
        <filter-name>characterEncoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>characterEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

时间类型转换

package cn.itcast.controller;

import cn.itcast.domain.User;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by weihu1 on 2018/8/21 16:09
 */
public class CommandController extends AbstractCommandController {

    //指定参数绑定到那个javaBean
    public CommandController(){
        this.setCommandClass(User.class);
    }
    @Override
    protected ModelAndView handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, BindException e) throws Exception {
        //把命令对象强转成User对象
        User user=(User)o;
        ModelAndView mv=new ModelAndView();
        mv.addObject("user",user);
        mv.setViewName("index");
        return mv;
    }

    /**
     * Create by hu.wei on 2018/8/21 17:01
     * @Description: 这个方法会先自动执行
     */
    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        super.initBinder(request, binder);

        String str=request.getParameter("birthday");
        if(str.contains("/")){
            binder.registerCustomEditor(Date.class,
                    new CustomDateEditor(new SimpleDateFormat("yyyy/MM/dd"),true));
        }else {
            binder.registerCustomEditor(Date.class,
                    new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
        }
    }
}