zoukankan      html  css  js  c++  java
  • SpringMVC框架的基础知识;

    首先 在javaEE环境下,建立一个动态的web工程;

    导入架包。。。。

    建立一对多映射关系的封装类,这儿只写属性,getter和setter方法就不写了;

    1:

    private String province;
    private String city;

    n:

    private Integer id;
    private String username;
    private String password;
    private String email;
    private int age;
    
    private Address address;

    web.xml中的配置

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    id="WebApp_ID" version="2.5">
          
          <!--/*:过滤所有请求
        配置 org.springframework.web.filter.HiddenHttpMethodFilter: 可以把 POST 请求转为 DELETE 或 POST 请求 
        -->
        <filter>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
        </filter>
          
          <filter-mapping>
              <filter-name>HiddenHttpMethodFilter</filter-name>
              <url-pattern>/*</url-pattern>
          </filter-mapping>
          
          <!-- 配置 DispatcherServlet -->
          <servlet>
            <servlet-name>springDispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            
            <!-- 配置 DispatcherServlet 的一个初始化参数: 配置 SpringMVC 配置文件的位置和名称 -->
            <!-- 
                实际上也可以不通过 contextConfigLocation 来配置 SpringMVC 的配置文件, 而使用默认的.
                默认的配置文件为: /WEB-INF/<servlet-name>-servlet.xml
            -->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc.xml</param-value>
            </init-param>
            
            <!-- 当前web应用被加载的时候就被创建 -->
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>springDispatcherServlet</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
      
    </web-app>

    在src目录下建立spring的bean配置文件: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: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-4.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
        
        <!-- 配置自动扫描的包 -->
        <context:component-scan base-package="com.atguigu.springmvc"></context:component-scan>
        
        <!-- 配置视图解析器:如何把handler方法返回值解析为实际的物理视图 
            将逻辑视图转换为物理视图,其视图优先级的值默认为最大,但是值越大,优先级越低-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
        
        <!-- 配置视图  BeanNameViewResolver 解析器: 使用视图的名字来解析视图 -->
        <!-- 通过 order 属性来定义视图解析器的优先级, order 值越小优先级越高 
        (建立一个视图类的时候,使用这个视图解析器)-->
        <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
            <property name="order" value="100"></property>
        </bean>
        
        <!-- 配置国际化资源文件 -->
        <bean id="messageSource" 
            class="org.springframework.context.support.ResourceBundleMessageSource">
            <property name="basename" value="i18n"></property>
        </bean>
        
        <!-- 配置直接转发的页面 -->
        <!-- 可以直接相应转发的页面, 而无需再经过 ... 的方法.  -->
        <mvc:view-controller path="/success" view-name="success"/>
        
        <!-- 在实际开发中通常都需配置 mvc:annotation-driven 标签,
            因为上面标签可实现直接转发到一个页面,而需要通过方法转发到某个页面的请求不能实现,会出现404异常,
            所以使用这个标签 ,会避免异常的发生-->
        <mvc:annotation-driven></mvc:annotation-driven>
    </beans>

    视图类:可以通过类名被视图解析器捕获;

    package com.atguigu.springmvc.view;
    
    import java.util.Date;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.View;
    
    @Component
    public class HelloView implements View{
    
        @Override
        public String getContentType() {
            return "text/html";
        }
    
        @Override
        public void render(Map<String, ?> model, HttpServletRequest request,
                HttpServletResponse response) throws Exception {
            response.getWriter().print("Hello view Time:"+new Date());
        }
        
    }

    建立几个国际化时候使用的file文件:

    i18n_en_US.properties:

    i18n.username=Username
    i18n.password=Password

    i18n_zh_CN.properties:

    i18n.username=u7528u6237u540D
    i18n.password=u5BC6u7801

    i18n.properties:

    i18n.username=Username
    i18n.password=Password

    测试类:

    package com.atguigu.springmvc.handlers;
    
    import java.io.IOException;
    import java.io.Writer;
    import java.util.Arrays;
    import java.util.Date;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.CookieValue;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestHeader;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.SessionAttributes;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.atguigu.springmvc.entities.User;
    
    @SessionAttributes(value={"user"},types={String.class})
    @RequestMapping("/springmvc")
    @Controller
    public class SpringMVCTest {
        
        public static final String success="success";
        
        /*
         * 如果返回的字符串中带有redirect:或forward:前缀时,SpringMVC会对他们进行特殊处理:
         * 将redirect:和forward:当成指示符,其后的字符串当做URL处理
         * redirect:/index.jsp:会完成一个到 index.jsp 的重定向操作;
         * forward:/index.jsp:会完成一个到 index.jsp 的转发操作;
         * */
        @RequestMapping("/testRedirect")
        public String testRedirect(){
            System.out.println("testRedirect");
            return "forward:/index.jsp";
        }
        
        //实现:首先要在springmvc.xml中配置视图  BeanNameViewResolver 解析器: 使用视图的名字来解析视图 
        //在建立一个类名为:HelloView的类,再return "helloView";,返回的字符串为类名首字母小写的类名
        @RequestMapping("/testView")
        public String testView(){
            System.out.println("helloView");
            return "helloView";
        }
        
        /**
         * 1. 有 @ModelAttribute 标记的方法, 会在每个目标方法执行之前被 SpringMVC 调用! 
         * 2. @ModelAttribute 注解也可以来修饰目标方法 POJO 类型的入参, 其 value 属性值有如下的作用:
         * 1). SpringMVC 会使用 value 属性值在 implicitModel 中查找对应的对象, 若存在则会直接传入到目标方法的入参中.
         * 2). SpringMVC 会一 value 为 key, POJO 类型的对象为 value, 存入到 request 中. 
         */
        @ModelAttribute
        public void getUser(@RequestParam(value="id",required=false) Integer id, 
                Map<String, Object> map){
            System.out.println("modelAttribute method");
            if(id != null){
                //模拟从数据库中获取对象
                User user = new User(1, "Tom", "123456", "tom@atguigu.com", 12);
                System.out.println("从数据库中获取一个对象: " + user);
                
                map.put("user", user);
            }
        }
        
        /**
         * 运行流程:
         * 1. 执行 @ModelAttribute 注解修饰的方法: 从数据库中取出对象, 把对象放入到了 Map 中. 键为: user
         * 2. SpringMVC 从 Map 中取出 User 对象, 并把表单的请求参数赋给该 User 对象的对应属性.
         * 3. SpringMVC 把上述对象传入目标方法的参数. 
         * 
         * 注意: 在 @ModelAttribute 修饰的方法中, 放入到 Map 时的键需要和目标方法入参类型的第一个字母小写的字符串一致!
         * 
         * SpringMVC 确定目标方法 POJO 类型入参的过程
         * 1. 确定一个 key:
         * 1). 若目标方法的 POJO 类型的参数木有使用 @ModelAttribute 作为修饰, 则 key 为 POJO 类名第一个字母的小写
         * 2). 若使用了  @ModelAttribute 来修饰, 则 key 为 @ModelAttribute 注解的 value 属性值. 
         * 2. 在 implicitModel 中查找 key 对应的对象, 若存在, 则作为入参传入
         * 1). 若在 @ModelAttribute 标记的方法中在 Map 中保存过, 且 key 和 1 确定的 key 一致, 则会获取到. 
         * 3. 若 implicitModel 中不存在 key 对应的对象, 则检查当前的 Handler 是否使用 @SessionAttributes 注解修饰, 
         * 若使用了该注解, 且 @SessionAttributes 注解的 value 属性值中包含了 key, 则会从 HttpSession 中来获取 key 所
         * 对应的 value 值, 若存在则直接传入到目标方法的入参中. 若不存在则将抛出异常. 
         * 4. 若 Handler 没有标识 @SessionAttributes 注解或 @SessionAttributes 注解的 value 值中不包含 key, 则
         * 会通过反射来创建 POJO 类型的参数, 传入为目标方法的参数
         * 5. SpringMVC 会把 key 和 POJO 类型的对象保存到 implicitModel 中, 进而会保存到 request 中. 
         * 
         * 源代码分析的流程
         * 1. 调用 @ModelAttribute 注解修饰的方法. 实际上把 @ModelAttribute 方法中 Map 中的数据放在了 implicitModel 中.
         * 2. 解析请求处理器的目标参数, 实际上该目标参数来自于 WebDataBinder 对象的 target 属性
         * 1). 创建 WebDataBinder 对象:
         * ①. 确定 objectName 属性: 若传入的 attrName 属性值为 "", 则 objectName 为类名第一个字母小写. 
         * *注意: attrName. 若目标方法的 POJO 属性使用了 @ModelAttribute 来修饰, 则 attrName 值即为 @ModelAttribute 
         * 的 value 属性值 
         * 
         * ②. 确定 target 属性:
         *     > 在 implicitModel 中查找 attrName 对应的属性值. 若存在, ok
         *     > *若不存在: 则验证当前 Handler 是否使用了 @SessionAttributes 进行修饰, 若使用了, 则尝试从 Session 中
         * 获取 attrName 所对应的属性值. 若 session 中没有对应的属性值, 则抛出了异常. 
         *     > 若 Handler 没有使用 @SessionAttributes 进行修饰, 或 @SessionAttributes 中没有使用 value 值指定的 key
         * 和 attrName 相匹配, 则通过反射创建了 POJO 对象
         * 
         * 2). SpringMVC 把表单的请求参数赋给了 WebDataBinder 的 target 对应的属性. 
         * 3). *SpringMVC 会把 WebDataBinder 的 attrName 和 target 给到 implicitModel. 
         * 近而传到 request 域对象中. 
         * 4). 把 WebDataBinder 的 target 作为参数传递给目标方法的入参. 
         */
        @RequestMapping("/testModelAttribute")
        public String testModelAttribute(User user){
            System.out.println("修改: " + user);
            return success;
        }
        
        
        /**
         * @SessionAttributes 除了可以通过属性名指定需要放到会话中的属性外(实际上使用的是 value 属性值),
         * 还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中(实际上使用的是 types 属性值)
         * 
         * 注意: 该注解只能放在类的上面. 而不能修饰放方法. 
         */
        @RequestMapping("/testSessionAttributes")
        public String testSessionAttributes(Map<String, Object> map){
            User user=new User(2,"username","password","email",89);
            map.put("user", user);
            map.put("school", "school");
            return success;
        }
        
         // 目标方法可以添加 Map 类型(实际上也可以是 Model 类型或 ModelMap 类型)的参数. 
        @RequestMapping("/testMap")
        public String testMap(Map<String, Object> map){
            System.out.println(map.getClass().getName());
            map.put("names", Arrays.asList("Tom","Jerry","Panpan"));
            return success;
        }
        
        /**
         * 目标方法的返回值可以是 ModelAndView 类型。 
         * 其中可以包含视图和模型信息
         * SpringMVC 会把 ModelAndView 的 model 中数据放入到 request 域对象中. 
         */
        @RequestMapping("/testModelAndView")
        public ModelAndView testModelAndView(){
            String viewName=success;
            
            ModelAndView modelAndView=new ModelAndView(viewName);
            
            //添加模型数据到 ModelAndView 中.
            modelAndView.addObject("time", new Date());
            return modelAndView;
        } 
        
        /**
         * 可以使用 Serlvet 原生的 API 作为目标方法的参数 具体支持以下类型
         * 
         * HttpServletRequest 
         * HttpServletResponse 
         * HttpSession
         * java.security.Principal 
         * Locale InputStream 
         * OutputStream 
         * Reader 
         * Writer
         * @throws IOException 
         */
        @RequestMapping("/testServletAPI")
        public void testServletAPI(HttpServletRequest request,
                HttpServletResponse response, Writer out) throws IOException {
            System.out.println("testServletAPI, " + request + ", " + response);
            out.write("hello springmvc");
    //        return SUCCESS;
        }
        
        //Spring MVC 会按请求参数名和 POJO 属性名进行自动匹配, 自动为该对象填充属性值。支持级联属性。
        //如:dept.deptId、dept.address.tel 等
        
        @RequestMapping("/testPojo")
        public String testPojo(User user){
            System.out.println("testPojo:"+user);
            return success;
        }
        
        
        // @CookieValue: 映射一个 Cookie 值. 属性同 @RequestParam
        @RequestMapping("/testCookieValue")
        public String testCookieValue(@CookieValue("JSESSIONID") String sessionId){
            System.out.println("testCookieValue:"+sessionId);
            return success;
        }
        
        //了解: 映射请求头信息 用法同 @RequestParam
        @RequestMapping("/testRequestHeader")
        public String testRequestHeader(@RequestHeader(value = "Accept-Language") String al) {
            System.out.println("testRequestHeader, Accept-Language: " + al);
            return success;
        }
    
        
        //@RequestParam 来映射请求参数. 
        //value 值即请求参数的参数名  required 该参数是否必须,默认为 true 
        //defaultValue 请求参数的默认值
        @RequestMapping(value="requestParam")
        public String testRequestParam(@RequestParam(value="username") String un,
                @RequestParam(value="age",required=false,defaultValue="0") int age){
            System.out.println("testRequestParam:un"+un+"testRequestParam:age"+age);
            return success;
        }
        
        /**
         * Rest 风格的 URL. 
         * 以 CRUD 为例: 
         * 新增: /order POST             以前:
         * 修改: /order/1 PUT         update?id=1
         * 获取:/order/1 GET          get?id=1 
         * 删除: /order/1 DELETE      delete?id=1
         * 
         * 如何发送 PUT 请求和 DELETE 请求呢 ? 
         * 1. 需要配置 HiddenHttpMethodFilter 
         * 2. 需要发送 POST 请求
         * 3. 需要在发送 POST 请求时携带一个 name="_method" 的隐藏域, 值为 DELETE 或 PUT
         * 
         * 在 SpringMVC 的目标方法中如何得到 id 呢? 使用 @PathVariable 注解
         * 
         */
        
        @RequestMapping(value="/testRest/{id}", method=RequestMethod.PUT)
        public String testRestPut(@PathVariable Integer id){
            System.out.println("testRest PUT:"+id);
            return success;
        }
        
        @RequestMapping(value="/testRest/{id}", method=RequestMethod.DELETE)
        public String testRestDelect(@PathVariable Integer id){
            System.out.println("testRest DELETE:" + id);
            return success;
        }
        
        //在post请求方法中 没有@PathVariable 获取请求参数,即不能获取到占位符的值
        @RequestMapping(value="/testRest",method=RequestMethod.POST)
        public String testRest(){
            System.out.println("testRest POST");
            return success;
        }
        
        @RequestMapping(value="/testRest/{id}", method=RequestMethod.GET)
        public String testRest(@PathVariable Integer id){
            System.out.println("testRest GET:"+id);
            return success;
        }
        
        
        //@PathVariable 可以来映射 URL 中的占位符到目标方法的参数中,在index.jsp 中
        //<a href="springmvc/testPathVariable/1">Test PathVariable</a>
        //可以在此方法中获取url中 1 的值
        @RequestMapping("/testPathVariable/{id}")
        public String testPathVariable(@PathVariable("id") Integer id){
            System.out.println("PathVariable:"+id);
            return success;
        }
        
        //@RequestMapping映射请求支持通配符
        @RequestMapping("/testAntPath/*/abc")
        public String testAntPath(){
            System.out.println("testAntPath");
            return success;
        }
        
        //params可为一个或多个参数
        // 可以使用 params 和 headers 来更加精确的映射请求. params 和 headers 支持简单的表达式.
        //其实即使在地址栏中添加后缀,获取其值和设置值的取值
        @RequestMapping(value="/testParamsAndHeader",params={"username","age!=10"})
        public String testParamsAndHeader(){
            System.out.println("testParamsAndHeader");
            return success;
        }
        
        //method为请求方式,可取为POST,GET
        //value是请求的URL
        @RequestMapping(value="/testMethod",method=RequestMethod.POST)
        public String testMethod(){
            System.out.println("testMethod");
            return success;
        }
        
        /**
         * 1. @RequestMapping 除了修饰方法, 还可来修饰类 
         * 2. 
         * 1). 类定义处: 提供初步的请求映射信息。相对于 WEB 应用的根目录
         * 2). 方法处: 提供进一步的细分映射信息。 相对于类定义处的 URL。若类定义处未标注 @RequestMapping,则方法处标记的 URL
         * 相对于 WEB 应用的根目录
         */
        @RequestMapping("/testRequestMapping")
        public String testRequestMapping(){
            System.out.println("testRequestMapping");
            return success;
        }
        
    }

    jsp页面:

    在WebContent/index目录下:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
        
        <a href="springmvc/testRedirect">Test Redirect</a>
        <br><br>
        
        <a href="springmvc/testView">Test View</a>
        <br><br>
        
        <!--  
            模拟修改操作
            1. 原始数据为: 1, Tom, 123456,tom@atguigu.com,12
            2. 密码不能被修改.
            3. 表单回显, 模拟操作直接在表单填写对应的属性值
        -->
        <form action="springmvc/testModelAttribute" method="Post">
            <input type="hidden" name="id" value="1"/>
            username: <input type="text" name="username" value="Tom"/>
            <br>
            email: <input type="text" name="email" value="tom@atguigu.com"/>
            <br>
            age: <input type="text" name="age" value="12"/>
            <br>
            <input type="submit" value="Submit"/>
        </form>
        <br><br>
        
        <a href="springmvc/testSessionAttributes">Test SessionAttributes</a>
        <br><br>
        
        <a href="springmvc/testMap">Test Map</a>
        <br><br>
        
        <a href="springmvc/testModelAndView">Test ModelAndView</a>
        <br><br>
        
        <a href="springmvc/testServletAPI">Test ServletAPI</a>
        <br><br>
        
        <form action="springmvc/testPojo" method="post">
            id:<input type="text" name="id"/><br>
            username:<input type="text" name="username"/><br>
            password:<input type="password" name="password"/><br>
            email:<input type="text" name="email"/><br>
            age:<input type="text" name="age"/><br>
            city:<input type="text" name="address.city"/><br>
            province<input type="text" name="address.province"/><br>
            <input type="submit" value="Submit"/><br>
        </form>
        <br><br>
        
        <a href="springmvc/testCookieValue">Test RequestHeader</a>
        <br><br>
        
        <a href="springmvc/testRequestHeader">Test RequestHeader</a>
        <br><br>
        
        <a href="springmvc/requestParam?username=panpan&age=789">Test RequestParam</a>
        <br><br>
        
        <form action="springmvc/testRest/1" method="post">
            <input type="hidden" name="_method" value="PUT"/>
            <input type="submit" value="TestRest PUT"/>
        </form>
        <br><br>
        
        <form action="springmvc/testRest/1" method="post">
            <input type="hidden" name="_method" value="DELETE"/>
            <input type="submit" value="TestRest DELECT"/>
        </form>
        <br><br>
        
        <form action="springmvc/testRest" method="post">
            <input type="submit" value="testRest POST"/>
        </form>
        <br><br>
        
        <a href="springmvc/testRest/1">Test Rest</a>
        <br><br>
        
        <a href="springmvc/testPathVariable/1">Test PathVariable</a>
        <br><br>
        
        <a href="springmvc/testAntPath/mnxyz/abc">Test AntPath</a>
        <br><br>
        
        <a href="springmvc/testParamsAndHeader?username=panpan&age=11">Test ParamsAndHeader</a>
        <br><br>
        
        <form action="springmvc/testMethod" method="post">
            <input type="submit" value="Submit"/>
        </form>
        
        <br><br>
        <!-- 因为它是GET提交方式,所以,与类中的请求不符,所以在上面,建立一个表单,提交方式为POST -->
        <a href="springmvc/testMethod">Test Method</a>
        <br><br>
        
        <a href="springmvc/testRequestMapping">Hello World</a>
        
        <br><br>
        <a href="hello">HelloWorld</a>
        
    </body>
    </html>

    WebContent/WEB-INF/views/success.jsp:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
        
        <h3>success</h3>
    
        <br><br>
        time: ${requestScope.time }
        
        <br><br>
        names: ${requestScope.names }
        
        <br><br>
        requestScope User: ${requestScope.user }
        
        <br><br>
        sessionScope User: ${sessionScope.user }
        
        <br><br>
        requestScope school:${requestScope.school }
        
        <br><br>
        sessionScope school: ${sessionScope.school }
        
        <br><br>
         user: ${requestScope.user }
        
        <br><br>
        <fmt:message key="i18n.username"></fmt:message>
        
        <br><br>
        <fmt:message key="i18n.password"></fmt:message>
    </body>
    </html>
  • 相关阅读:
    C++ STL中vector应用
    cocos2dx绘制直线
    [ios] 获得ios设备具体型号
    如何制作 iTunesArtwork
    Ios AppIcon 去掉默认半弧形白色遮罩
    App运行内存打印
    C++ 文件操作
    objc 笔记
    (转)c++ oc字符操作
    cocos2dx 文本 优化
  • 原文地址:https://www.cnblogs.com/lxnlxn/p/5931317.html
Copyright © 2011-2022 走看看