1. 创建POJO
    1.  package org.entity;
      
       public class User {
      private int id;
      private String userName;
      private String email;
      private Address address;
      public User(int id, String userName, String email, Address address) {
      super();
      this.id = id;
      this.userName = userName;
      this.email = email;
      this.address = address;
      }
      @Override
      public String toString() {
      return "User [id=" + id + ", userName=" + userName + ", email=" + email + ", address=" + address + "]";
      }
      public User(int id, String userName, String email) {
      super();
      this.id = id;
      this.userName = userName;
      this.email = email;
      }
      public Address getAddress() {
      return address;
      }
      public void setAddress(Address address) {
      this.address = address;
      }
      public int getId() {
      return id;
      }
      public void setId(int id) {
      this.id = id;
      }
      public String getUserName() {
      return userName;
      }
      public void setUserName(String userName) {
      this.userName = userName;
      }
      public String getEmail() {
      return email;
      }
      public void setEmail(String email) {
      this.email = email;
      }
      public User() {
      }
      }
    2.  package org.entity;
      
       public class Address {
      private String provience;
      private String city;
      public String getProvience() {
      return provience;
      }
      public void setProvience(String provience) {
      this.provience = provience;
      }
      public String getCity() {
      return city;
      }
      public void setCity(String city) {
      this.city = city;
      }
      @Override
      public String toString() {
      return "Address [provience=" + provience + ", city=" + city + "]";
      }
      }
  2. 配置web.xml
    1.  <?xml version="1.0" encoding="UTF-8"?>
      <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns="http://xmlns.jcp.org/xml/ns/javaee"
      xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
      id="WebApp_ID" version="3.1">
      <!--配置DispatcherServlet -->
      <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
      <servlet>
      <servlet-name>springDispatcherServlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <!-- 配置DiapacherServlet初始化参数 -->
      <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
      </init-param>
      <!-- -->
      <load-on-startup>1</load-on-startup>
      </servlet> <!-- Map all requests to the DispatcherServlet for handling -->
      <servlet-mapping>
      <servlet-name>springDispatcherServlet</servlet-name>
      <url-pattern>/</url-pattern>
      </servlet-mapping>
      </web-app>
  3. 配置SpringMVC.xml
    1.  <?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"
      xmlns:task="http://www.springframework.org/schema/task"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
      http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
      http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
      http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
      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/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
      http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
      <!-- 配置自定义扫描得包 -->
      <context:component-scan base-package="org.handler"></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"/>
      </bean>
      <!-- 自定义图 视图解析器 使用视图的名字来解析视图-->
      <!-- 通过order属性来定义视图优先级 order值越小优先级越高-->
      <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
      <property name="order" value="100"></property>
      </bean>
      <!-- 配置直接转发的页面 -->
      <mvc:view-controller path="/success" view-name="success"/>
      <!-- 在实际开发中需要配置mvc:annotation-driven标签 -->
      <mvc:annotation-driven></mvc:annotation-driven>
      <!-- 配置国际化资源文件 -->
      <bean id="messageSource"
      class="org.springframework.context.support.ResourceBundleMessageSource">
      <property name="basename" value="i18n"></property>
      </bean> </beans>
  4. 编写jsp
    1.   index.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>
      <a href="helloword">Hello Word</a>
      <br>
      <form action="testUser">
      id:<input type="text" name="id"/>
      <br>
      userName:<input type="text" name="userName"/>
      <br>
      email:<input type="text" name="email"/>
      <br>
      provience:<input type="text" name="address.provience"/>
      <br>
      city:<input type="text" name="address.city"/>
      <input type="submit" value="提交"/>
      </form>
      <br/>
      <a href="testServletAPI">testServletAPI</a>
      <br>
      <a href="testModelAndView">testModelAndView</a>
      <br>
      <a href="testMap">test Map</a>
      <br>
      <a href="testSessionAttributes">testSessionAttributes</a> <br><br>
      <!--
      模拟修改操作
      1.原始数据为 1 tom @tom.com
      2.名字不能被修改
      3.表单回显,模拟操作直接在表单填写对应的属性值
      -->
      <form action="testModelAttribute">
      <input type="hidden" name = "id" value="1"/>
      email:<input type="text" name ="email" value="@tom.com"/>
      <input type="submit" value="提交"/>
      </form>
      <br><br> <a href="testViewSourceAndViewResolver">testViewSourceAndViewResolver</a> <br><br>
      国际化:
      <br>
      <fmt:message key="i18n.username"></fmt:message>
      <br>
      <fmt:message key="i18n.password"></fmt:message> <br><br>
      <a href="testView">testView</a>
      <br><br>
      <a href=testRedirect>testRedirect</a>
      </body>
      </html>
    2.   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>
    hello SpringMVC
    <br>
    time: ${requestScope.time}
    <br>
    name: ${requestScope.names}
    <br><br>
    request user: ${requestScope.user}
    <br>
    session user: ${sessionScope.user}
    <br><br>
    request email: ${requestScope.email}
    <br>
    session email: ${sessionScope.email}
    <br>
    <br><br>
    国际化:
    <br>
    <fmt:message key="i18n.username"></fmt:message>
    <br>
    <fmt:message key="i18n.password"></fmt:message>
    </body>
    </html>
  5. 编写Handler
    1.  package org.handler;
      
       import java.io.IOException;
      import java.io.Writer;
      import java.util.Arrays;
      import java.util.Date;
      import java.util.HashMap;
      import java.util.Map; import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import javax.xml.ws.soap.MTOM; import org.apache.catalina.startup.Tomcat;
      import org.apache.taglibs.standard.lang.jstl.test.beans.PublicInterface2;
      import org.entity.User;
      import org.omg.PortableInterceptor.SUCCESSFUL;
      import org.springframework.stereotype.Controller;
      import org.springframework.validation.Errors;
      import org.springframework.web.bind.annotation.ModelAttribute;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RequestParam;
      import org.springframework.web.bind.annotation.SessionAttributes;
      import org.springframework.web.servlet.ModelAndView;
      import com.sun.net.httpserver.Authenticator.Success;
      import com.sun.org.apache.bcel.internal.generic.NEW;
      import com.sun.org.apache.regexp.internal.recompile;
      //@SessionAttributes(value={"user"},types={String.class})
      @Controller
      public class SpringMVC {
      public static String SUCCESS = "success";
      /**
      * 使用@RequestMapping注解来映射请求的URL
      * @return
      */
      @RequestMapping("/helloword")
      public String testhello() {
      System.out.println("helloword");
      return "success";
      }
      /**
      * 支持提交pojo 会根据name与pojo属性进行匹配 支持级联属性
      * @param user
      * @return
      */
      @RequestMapping("/testUser")
      public String testUser(User user) {
      System.out.println("User:"+user.toString());
      return "success";
      }
      /**
      * 支持使用servlet原生api
      * HttpServletReqyest
      * HttpServletResponse
      * HttpSession
      * java.security.Prinipal
      * Locale
      * InputStream
      * OutputStream
      * Reader
      * Writer
      * @throws IOException
      */
      @RequestMapping("testServletAPI")
      public String testServletAPI(HttpServletRequest request,
      HttpServletResponse response,
      Writer out) throws IOException { System.out.println("testServletAPI:"+request+"\n"+response+"\n"+out);
      out.write("hello writer");
      out.write(1111);
      return "success";
      }
      /**
      * ModelAndView
      * Map及Model
      * @sessionAttributes
      * @ModelAttribute
      * 目标方法的返回值可以是ModelAndView类型其中包含视图和模型信息
      */
      @RequestMapping("testModelAndView")
      public ModelAndView testModelAndView() {
      String viewName="success";
      ModelAndView modelAndView = new ModelAndView(viewName);
      modelAndView.addObject("time",new Date());
      return modelAndView;
      }
      /**
      * 目标方法可以添加map(也可以是Model类型或ModelMap类型)类型参数
      * @param map
      * @return
      */
      @RequestMapping("testMap")
      public String testMap(Map<String,Object> map) {
      map.put("names",Arrays.asList("tom","jerry","mike"));
      return "success";
      }
      /**
      * map 默认在request域里不会装进Session域
      * 用sessionAttributes在controller类上做注解使属性值进入session域
      * 其括号内可放键、值 如上设置
      * @SessionAttributes(value={"user"},types={String.class})
      * 表示将 键 为"user" 或 值为String类型的 键值对放入session域
      * 注意 :该注解只能放在类上
      */ @RequestMapping("testSessionAttributes")
      public String testSessionAttributes(Map<String, Object> map) {
      User user = new User(121,"tom","@qwqx.com");
      map.put("user", user);
      map.put("email", "@myemail.com");
      return SUCCESS;
      }
      /**@RequestMapping("testModelAttribute")
      * 如果数据库中的数据进行修改操作,默认的表单提交会new一个对象传回后台
      * 如果规定某些属性无法修改,在表单里我们是不需要列出来的,而表单里我们不对属性进行赋值,
      * 会造成对象属性为null,在写入数据库时造成麻烦,
      * 当然我们可以用hidden赋值,但如果是私密属性又会有麻烦
      * 在这里我们可以选择先从数据库插叙获取到对象,传送到页面,表单提交只是对属性值作出更改,而不是新建对象
      */
      @RequestMapping("testModelAttribute")
      public String testModelAttribute(@ModelAttribute("user")User user) {
      System.out.println("修改:"+user);
      return SUCCESS;
      }
      /**
      * 由@ModelAttribute标记的方法会在每个目标方法执行之前被SpringMVC调用
      * 在ModelAttribute修饰的方法中,放入到Map时的键需要和目标方法参数类型的第一个字母小写的字符串一致
      * 可以在目标方法的参数上用@ModelAttribute("user") 用于指定获取对象时需要查找的键
      * testModelAttribute(@ModelAttribute("user")User user)
      */
      @ModelAttribute
      public void getUser(@RequestParam(value="id",required=false) Integer id,
      Map<String, Object> map) {
      if(id!=null) {
      // 假设user为数据库查询出来的对象
      User user = new User(2,"Tom", "@tom.com");
      System.out.println("数据库查询出来的对象:"+user.toString());
      map.put("user",user);
      }
      }
      @RequestMapping("testViewSourceAndViewResolver")
      public String testViewSourceAndViewResolver() { return SUCCESS;
      }
      @RequestMapping("testView")
      public String testView() {
      System.out.println("testView");
      return "helloView";
      }
      @RequestMapping("testRedirect")
      public String testRedirect() {
      System.out.println("testRedirect");
      return "redirect:/index.jsp";
      }
      }

自定义视图测试:

    

 package org.views;

 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, ?> arg0, HttpServletRequest arg1, HttpServletResponse arg2) throws Exception {
arg2.getWriter().print("hello view .time"+new Date());
} }

SprigMVC基础测试的更多相关文章

  1. myBatis 基础测试 表关联关系配置 集合 测试

    myBatis 基础测试 表关联关系配置 集合 测试 测试myelipse项目源码 sql 下载 http://download.csdn.net/detail/liangrui1988/599388 ...

  2. mysql基础测试

    mysql基础测试 测试原因   为什么需要做性能测试 模拟比当前系统更高的负载,找出性能瓶颈 重现线上异常 测试不同硬件软件配置 规划未来的业务增长   测试分类   性能测试的分类 设备层的测试 ...

  3. 基础测试jmeter5.0+badboy(从小白到入门)

    1]测试工具jmeter环境安装 1.1]安装jdk环境 1:必须安装jdk8.0(我尝试安装最新版本不行,好像当时没有配置好.之后安装8.0遍可以正常运行)下载地址:单击此段 配置jdk环境:鼠标右 ...

  4. 性能测试基础---测试流程,LR安装

    ·性能测试流程详解: 一般来说,性能测试通常可以分为以下过程: ·前期分析.测试计划.测试方案.测试环境的搭建.测试数据的准备.测试脚本的开发.测试场景的设计.测试场景的实现和执行.资源的监控.分析结 ...

  5. Kubeasz部署K8s基础测试环境简介

    下面介绍使用Kubeasz部署K8s集群环境. https://github.com/easzlab/kubeasz在需要使用kubeeasz项目安装的k8s时,需要将所有需要它来部署的节点上,都安装 ...

  6. weed-fs 基础测试

    =================== 启动 master 端口:9333 =================== sunsl@test-server:~$ weed master I0102 15: ...

  7. Linux基础测试--11道题

    000.创建一个目录/data mkdir /data 001.在/data 下面创建一个文件oldboy.txt touch /data/oldboy.txt 002.为oldboy.txt 增加内 ...

  8. Hive基础测试操作

    一.Hive测试 1.查看数据库 show databases; 2.使用某个数据库,如默认数据库 user default; 3.创建表 create table if not exist itst ...

  9. Python基础测试有关联的接口

    test_guanlian.py放在case文件夹下 test_guanlian.pyimport unittest import requestsfrom urllib.parse import u ...

随机推荐

  1. LeetCode(16)3Sum Closest

    题目 Given an array S of n integers, find three integers in S such that the sum is closest to a given ...

  2. 【HIHOCODER 1163】 博弈游戏·Nim游戏

    描述 今天我们要认识一对新朋友,Alice与Bob. Alice与Bob总是在进行各种各样的比试,今天他们在玩一个取石子的游戏. 在这个游戏中,Alice和Bob放置了N堆不同的石子,编号1..N,第 ...

  3. luogu3415 祭坛

    先二分答案转化成判定问题. 考虑拿一根扫描线从 \(x=0\) 扫到 \(x=n\),每次移动扫描线更新每个位置它上面的点数和下面的点数,这样可以确定在当前的扫描线上哪些位置对于 \(y\) 轴方向是 ...

  4. URL 路由

    一般情况下,一个 URL 字符串和它对应的控制器中类和方法是一一对应的关系. URL 中的每一段通常遵循下面的规则: example.com/class/function/id/ 但是有时候,你可能想 ...

  5. JavaEE JDBC 了解数据库连接池

    了解数据库连接池 @author ixenos 数据库连接是有限的资源,如果用户需要离开应用一段时间,那么他占用的连接就不应该保持开放状态: 另一方面,每次查询都获取连接并在随后关闭它的代价也很高. ...

  6. bzoj3142[Hnoi2013]数列 组合

    Description 小 T最近在学着买股票,他得到内部消息:F公司的股票将会疯涨.股票每天的价格已知是正整数,并且由于客观上的原因,最多只能为N.在疯涨的K天中小T观察 到:除第一天外每天的股价都 ...

  7. [NOIP2001] 提高组 洛谷P1024 一元三次方程求解

    题目描述 有形如:ax3+bx2+cx+d=0 这样的一个一元三次方程.给出该方程中各项的系数(a,b,c,d 均为实数),并约定该方程存在三个不同实根(根的范围在-100至100之间),且根与根之差 ...

  8. CDQ分治模板

    #include<cstdio> #include<algorithm> #include<cstring> #include<cmath> #defi ...

  9. BZOJ1733: [Usaco2005 feb]Secret Milking Machine 神秘的挤奶机

    n<=200个点m<=40000条边无向图,求   t次走不经过同条边的路径从1到n的经过的边的最大值   的最小值. 最大值最小--二分,t次不重边路径--边权1的最大流. #inclu ...

  10. php桥接模式

    php桥接模式 桥接模式是将抽象部分与它的实现部分分离,使它们都可以独立地变化. 示例:当一个信息时根据发送渠道分为:QQ消息.email消息.短信消息等根据消息类型分为:普通.警告.危急等每种消息都 ...