spring-构建mvc工程

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的标签库

...

猜你喜欢

转载自www.cnblogs.com/shixiemayi/p/9568454.html
今日推荐