创建一个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: //
Time: :
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: //
Time: :
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-</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));
}
}
}

1.SpringMVC入门的更多相关文章

  1. 【Spring】SpringMVC入门示例讲解

    目录结构: // contents structure [-] SpringMVC是什么 Spring MVC的设计原理 SpringMVC入门示例 1,复制Jar包 2,Web.xml文件 3,My ...

  2. Spring+SpringMVC+MyBatis深入学习及搭建(十二)——SpringMVC入门程序(一)

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/6999743.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十一)——S ...

  3. SpringMVC入门第二天

    SpringMVC第二天 1.   回顾 1.Springmvc介绍? Springmvc是Spring公司 2.Springmvc入门程序 第一步:Web工程 第二步:导Jar包 第三步:web.x ...

  4. 3.2.1 SpringMVC入门

    一. SpringMVC入门 1. MVC介绍 MVC全名 是Model View Controller, 是模型(model) - 视图(view) - 控制器(controller) 的缩写, 它 ...

  5. SpringMVC入门学习(二)

    SpringMVC入门学习(二) ssm框架 springMVC  在上一篇博客中,我简单介绍了一下SpringMVC的环境配置,和简单的使用,今天我们将进一步的学习下Springmvc的操作. mo ...

  6. SpringMVC入门学习(一)

    SpringMVC入门学习(一) ssm框架 spring  SpringMVC是一个Java WEB框架,现在我们知道Spring了,那么,何为MVC呢? MVC是一种设计模式,其分为3个方面 mo ...

  7. springMVC入门(一)

    1.   SpringMVC入门 1.1SpringMVC是什么 Spring web mvc和Struts2都属于表现层的框架,它是Spring框架的一部分,我们可以从Spring的整体结构中看得出 ...

  8. SpringMVC.入门篇《二》form表单

    SpringMVC.入门篇<二>form表单 项目工程结构: 在<springmvc入门篇一.HelloWorld>基础上继续添加代码,新增:FormController.ja ...

  9. SpringMVC.入门篇.一.HelloWorld

    SpringMVC.入门篇<一>HelloWorld 项目包结构如下: HelloController.java 代码 package com.charles.controller; im ...

  10. SpringMVC入门(基于注解方式实现)

    ---------------------siwuxie095                             SpringMVC 入门(基于注解方式实现)         SpringMVC ...

随机推荐

  1. C#使用GET、POST请求获取结果,这里以一个简单的用户登陆为例。

    1. 使用GET请求获取结果 1.1 创建LoginHandler.aspx处理页面 protected void Page_Load(object sender, EventArgs e) { st ...

  2. leetcode279

    动态规划 public class Solution { public int NumSquares(int n) { var list = new List<int>(); list.A ...

  3. .NET MVC 控制器和行为

    行为就是可访问方法(public) 行为返回类型必须是 ActionResult 或者其派生类,基本上返回类型为以下四种之一 View(视图路径) Json(对象或者对象集合) Content(字符串 ...

  4. mvn多环境下的配置

    在应用中,我们经常会遇到本地,测试和生产3种不同的环境,因此需要去配置不同的application. 定义resources: <resources> <resource> & ...

  5. tkinter窗口居中方法

    tkinter窗口居中 from tkinter import * class MyFrm(Frame): def __init__(self, master): self.root=master s ...

  6. Could not find a package,configuration file provided by "G2O" ,G2OConfig.cmake,g2o-config.cmake

    因为项目需要使用到g2o,所以自己从git上面clone下来, git clone https://github.com/RainerKuemmerle/g2o.git 然后: cd g2o mkdi ...

  7. Codeforces Round #437 C. Ordering Pizza

    题意: n个人吃披萨,总共有两种披萨,每种披萨都是有S块,给出每个人要吃的块数,吃第一种披萨能获得的happy值,吃第二种披萨能获得的happy值,问你,在购买的披萨数最少的情况下能获得的最大的总的h ...

  8. Quartz基础知识了解(一)

    一.QuartZ是什么? 二.获取 三.核心接口 Scheduler - 与调度程序交互的主要API. Job - 由希望由调度程序执行的组件实现的接口. JobDetail - 用于定义作业的实例. ...

  9. as3.0 嵌入字体的用法

    var txt:TextField = new TextField();//创建文本 txt.embedFonts=true;//确定嵌入字体 var font:Font=new MyFont();/ ...

  10. hdoj4734(数位dp优化)

    题目链接:https://vjudge.net/problem/HDU-4734 题意:定义一个十进制数AnAn-1...A1的value为An*2n-1+...+A1*20,T组样例(<=1e ...