SpringMVC基于模型-视图-控制器(MVC)模式实现,可以构建松耦合的web应用程序。

1、SpringMVC的请求过程

1)请求离开浏览器,并携带用户所请求的内容

2)DispatcherServlet角色为调度员(前端控制器)。查询一个或多个处理器映射确定处理请求的控制器

3)将请求发给选中的控制器业务处理

4)控制器处理完成后,将业务数据封装为模型,并指定一个逻辑视图名,一起返回给DispatcherServlet

5)DispatcherServlet将逻辑视图名匹配一个特定视图实现

6)使用模型数据渲染出指定的视图

7)返给前端展示

2、springMVC工程配置

web.xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <!--<context-param>-->
<!--<param-name>contextConfigLocation</param-name>-->
<!--<param-value>classpath:applicationContext.xml</param-value>-->
<!--</context-param>-->
<!--<listener>-->
<!--<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>-->
<!--</listener>--> <servlet>
<servlet-name>appServlet</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>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> </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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 扫描控制器 -->
<context:component-scan base-package="com.cn.controller"></context:component-scan>
<!-- 处理器映射 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean> </beans>

3、控制器

 接受参数的方式

  • 查询参数
  • 表单参数
  • 路径变量

控制器

package com.cn.controller;

import com.cn.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import javax.validation.Valid; @Controller
public class HelloController { @RequestMapping("/home")
public String home(){
System.out.println("执行home");
return "home"; //返回一个字符串,即逻辑视图名
} @RequestMapping("/home2")
public String home2(){
System.out.println("执行home2");
return "redirect:home3"; //含有redirect的字符串,表示重定向到另一个处理器;
//如果含有forward的字符串,表示转向到另一个处理器
} @RequestMapping("/home3")
public String home3(){
System.out.println("输出home");
return "home3";
} @RequestMapping("/show3") //表单参数,,@Valid注解与添加了校验注解的User配合使用
public String showPerson3(@Valid User user, Errors errors){//Errors参数必须紧跟@Valid的参数
if (errors.hasErrors()){//校验是否有校验未通过的参数
System.out.println("表单元素校验不通过");
return "fail";
}
System.out.println("用户信息:"+user);
return "success";
} @RequestMapping("/{name}/{age}") //路径参数 http://localhost:8080/tt/123 输出:名称:tt 年龄:123;;
public String showPerson2(@PathVariable(value = "name") String name,
@PathVariable(value = "age") String age){
System.out.println("名称:"+name+" 年龄:"+age);
return "success";
} @RequestMapping("/show") //查询参数 http://localhost:8080/show?name=pp&age=99 输出:名称:pp 年龄:99;;
public String showPerson(@RequestParam(value = "name", defaultValue = "laowang") String name,
@RequestParam(value = "age", defaultValue = "100") String age){
System.out.println("名称:"+name+" 年龄:"+age);
return "success";
} }

POJO

package com.cn.pojo;

import com.sun.istack.internal.NotNull;

import javax.validation.constraints.Size;

public class User {
  //表单参数校验
@NotNull
@Size(min = 6,max = 10)
private String firstName;
@NotNull
@Size(min = 6,max = 10)
private String lastName;
@NotNull
@Size(min = 6,max = 10)
private String name;
@NotNull
@Size(min = 6,max = 10)
private String passwd; public String getFirstName() {
return firstName;
} public void setFirstName(String firstName) {
this.firstName = firstName;
} public String getLastName() { return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getPasswd() {
return passwd;
} public void setPasswd(String passwd) {
this.passwd = passwd;
} @Override
public String toString() {
return "User{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", name='" + name + '\'' +
", passwd='" + passwd + '\'' +
'}';
}
}

4、视图解析器

  • 在控制器中返回的字符串(不包含redirect、forward)表示逻辑视图名,而不会调用具体的视图实现。spring的视图解析器能够决定使用哪种视图实现去渲染模型。SpringMvc定义了一个ViewResolver 接口,返回为View对象
public interface ViewResolver {
View resolveViewName(String var1, Locale var2) throws Exception;
}

View接口定义,其中render方法接受模型、request、response参数,并将模型数据渲染到response中

public interface View {
String RESPONSE_STATUS_ATTRIBUTE = View.class.getName() + ".responseStatus";
String PATH_VARIABLES = View.class.getName() + ".pathVariables";
String SELECTED_CONTENT_TYPE = View.class.getName() + ".selectedContentType"; String getContentType(); void render(Map<String, ?> var1, HttpServletRequest var2, HttpServletResponse var3) throws Exception;
}
  • 视图解析器的实现

Spring提供了ViewResolver 多个内置的实现,比如InternalResourceViewResolver、TilesViewResolver...其中InternalResourceViewResolver(最简单、最常用的视图解析器)将视图解析为Web应用的内部资源(一般为jsp)

  • 创建JSP视图

Spring支持两种JSP视图的方式---使用InternalResourceViewResolver

方式1:在页面中使用JSP标准标签库(JSTL),InternalResourceViewResolver能够将视图名解析为JstlView形式的JSP文件

方式2:使用Spring提供的JSP标签库(两个:一个用于表单到模型的绑定;另一个提供了通用工具类特性)

a、配置适用于JSP的视图解析器

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

  控制器中返回的字符串与该配置中的前后缀拼接成完成的文件路径,控制器中返回的字符串如果包含了斜线,则可以区分出了不同的目录。该配置会将逻辑视图名解析为InternalResourceView实例。

如过JSP中使用JSTL标签来处理内容,则希望视图解析器将视图解析为JstlView实例。仅仅添加一行配置文件即可:

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

b、Spring的JSP的标签库

...

spring-构建mvc工程的更多相关文章

  1. Spring Boot——2分钟构建spring web mvc REST风格HelloWorld

    之前有一篇<5分钟构建spring web mvc REST风格HelloWorld>介绍了普通方式开发spring web mvc web service.接下来看看使用spring b ...

  2. 使用 Spring 3 MVC HttpMessageConverter 功能构建 RESTful web 服务

    原文地址:http://www.ibm.com/developerworks/cn/web/wa-restful/ 简介: Spring,构建 Java™ 平台和 Enterprise Edition ...

  3. [转]Spring Boot——2分钟构建spring web mvc REST风格HelloWorld

    Spring Boot——2分钟构建spring web mvc REST风格HelloWorld http://projects.spring.io/spring-boot/ http://spri ...

  4. 使用Intellij中的Spring Initializr来快速构建Spring Boot/Cloud工程(十五)

    在之前的所有Spring Boot和Spring Cloud相关博文中,都会涉及Spring Boot工程的创建.而创建的方式多种多样,我们可以通过Maven来手工构建或是通过脚手架等方式快速搭建,也 ...

  5. 使用方法拦截机制在不修改原逻辑基础上为 spring MVC 工程添加 Redis 缓存

    首先,相关文件:链接: https://pan.baidu.com/s/1H-D2M4RfXWnKzNLmsbqiQQ 密码: 5dzk 文件说明: redis-2.4.5-win32-win64.z ...

  6. 使用Intellij中的Spring Initializr来快速构建Spring Boot/Cloud工程

    在之前的所有Spring Boot和Spring Cloud相关博文中,都会涉及Spring Boot工程的创建.而创建的方式多种多样,我们可以通过Maven来手工构建或是通过脚手架等方式快速搭建,也 ...

  7. Spring Boot教程(十五)使用Intellij中的Spring Initializr来快速构建Spring Boot/Cloud工程

    在之前的所有Spring Boot和Spring Cloud相关博文中,都会涉及Spring Boot工程的创建.而创建的方式多种多样,我们可以通过Maven来手工构建或是通过脚手架等方式快速搭建,也 ...

  8. Spring 4 MVC+Hibernate 4+MySQL+Maven使用注解集成实例

    Spring 4 MVC+Hibernate 4+MySQL+Maven使用注解集成实例 转自:通过注解的方式集成Spring 4 MVC+Hibernate 4+MySQL+Maven,开发项目样例 ...

  9. Spring Framework------>version4.3.5.RELAESE----->Reference Documentation学习心得----->Spring Framework中的spring web MVC模块

    spring framework中的spring web MVC模块 1.概述 spring web mvc是spring框架中的一个模块 spring web mvc实现了web的MVC架构模式,可 ...

  10. 使用XFire+Spring构建Web Service(一)——helloWorld篇

    转自:http://www.blogjava.net/amigoxie/archive/2007/09/26/148207.html原文出处:http://tech.it168.com/j/2007- ...

随机推荐

  1. QLocalServer和QLocalSocket单进程和进程通信

    QLocalServer 继承自QObject. QLocalServer提供了一个基于本地套接字(socket)的服务端(server).QLocalServer可以接受来自本地socket的连接. ...

  2. create-react-native-app

    create-react-native-app官网介绍链接,github文档,可以看看了解一下,总之是一个5分钟快速搭建react native项目并能看到效果的方法. 假设你已经安装了Node,你可 ...

  3. 根据viewport的size自动调整fontsize大小

    现在的网站必须要考虑mobile上访问的友好性,bootstrap作为mobile first的前端框架得到很多应用,它通过默认就使用.col-xs-xx定义的width,同时加上@media(min ...

  4. mysql安装错误之->ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

    有时候,当我们使用“mysql”.“mysqladmin”.“mysqldump”等命令管理数据库时,服务器抛出类似如下错误: 一.错误现场还原:下面我们通过三种方式来连接,然后观察提示的错误信息: ...

  5. QT的键值对应关系 看完开发节省时间 哈哈

    http://blog.csdn.net/wangjieest/article/details/8283656

  6. July 02nd 2017 Week 27th Sunday

    No safe wading in an unknown water. 未知水深浅,涉水有危险. Is this the theory that has been the guideline for ...

  7. 1874 football game(三分法and method to compute the area of trianngle)

    FInd the max area. 1. 三分法 2. NAN (not comparable with number) http://acm.timus.ru/problem.aspx?space ...

  8. c++11 实现RAII特性

    参考文章https://blog.csdn.net/pongba/article/details/7911997 什么是RAII 技术?(参见百度百科相关条目) RAII(Resource Acqui ...

  9. ADF系列-2.EO的高级属性

    在上一篇博客 ADF系列-1.EO的各个属性初探 中介绍了EO的一些常用简单属性.本次将介绍EO中一些比较常用的一些高级属性 一.基于Sequence创建EO,一下介绍三种方式(以HR用户的Emplo ...

  10. im2rec打包图片

    https://mxnet.incubator.apache.org/faq/finetune.html python ~/mxnet/tools/im2rec.py --list --recursi ...