SprigMVC基础测试
- 创建POJO
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() {
}
}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 + "]";
}
}
- 配置web.xml
<?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>
- 配置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"
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>
- 编写jsp
- 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> - 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> - index.jsp
- 编写Handler
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基础测试的更多相关文章
- myBatis 基础测试 表关联关系配置 集合 测试
myBatis 基础测试 表关联关系配置 集合 测试 测试myelipse项目源码 sql 下载 http://download.csdn.net/detail/liangrui1988/599388 ...
- mysql基础测试
mysql基础测试 测试原因 为什么需要做性能测试 模拟比当前系统更高的负载,找出性能瓶颈 重现线上异常 测试不同硬件软件配置 规划未来的业务增长 测试分类 性能测试的分类 设备层的测试 ...
- 基础测试jmeter5.0+badboy(从小白到入门)
1]测试工具jmeter环境安装 1.1]安装jdk环境 1:必须安装jdk8.0(我尝试安装最新版本不行,好像当时没有配置好.之后安装8.0遍可以正常运行)下载地址:单击此段 配置jdk环境:鼠标右 ...
- 性能测试基础---测试流程,LR安装
·性能测试流程详解: 一般来说,性能测试通常可以分为以下过程: ·前期分析.测试计划.测试方案.测试环境的搭建.测试数据的准备.测试脚本的开发.测试场景的设计.测试场景的实现和执行.资源的监控.分析结 ...
- Kubeasz部署K8s基础测试环境简介
下面介绍使用Kubeasz部署K8s集群环境. https://github.com/easzlab/kubeasz在需要使用kubeeasz项目安装的k8s时,需要将所有需要它来部署的节点上,都安装 ...
- weed-fs 基础测试
=================== 启动 master 端口:9333 =================== sunsl@test-server:~$ weed master I0102 15: ...
- Linux基础测试--11道题
000.创建一个目录/data mkdir /data 001.在/data 下面创建一个文件oldboy.txt touch /data/oldboy.txt 002.为oldboy.txt 增加内 ...
- Hive基础测试操作
一.Hive测试 1.查看数据库 show databases; 2.使用某个数据库,如默认数据库 user default; 3.创建表 create table if not exist itst ...
- Python基础测试有关联的接口
test_guanlian.py放在case文件夹下 test_guanlian.pyimport unittest import requestsfrom urllib.parse import u ...
随机推荐
- python-001 第一个Python3.x程序 hello world
我们可以使用以下命令来查看我们使用的Python版本: (d:\ProgramData\Anaconda3) C:\Users\Administrator.2016-20160920ET>pyt ...
- Android弹幕编程设计实现的解决方案(一)
Android弹幕编程设计实现的解决方案(一) 在现在的一些视频类网站.视频类直播网站,比如A站和B站,当视频在播放的时候,会在屏幕上出现一些滚动的字幕,这些字幕是UGC,通常是用户的评论,称之 ...
- 【思维】2017多校训练七 HDU6121 Build a tree
http://acm.hdu.edu.cn/showproblem.php?pid=6121 [题意] 询问n个结点的完全k叉树,所有子树结点个数的异或和是多少 [思路] 一棵完全K叉树,对于树的每一 ...
- 关于系统中使用多个PropertyPlaceholderConfigurer的配置
多数的鲜为人知方法都是因为有着罕见的应用,就比如说Spring中PropertyPlaceholderConfigurer这个类,它是用来解析Java Properties属性文件值,并提供在spri ...
- react.js 渲染一个列表的实例
//引入模块 import React,{Component} from 'react'; import ReactDOM from 'react-dom'; //定义一个要渲染的数组 let use ...
- ztree2.6给菜单增加title提示信息[转]
自定义数据格式的情况下(isSimpleData: true) 在setting中自定义一个属性如 remark:"remark", callback中调用函数 nodeCreat ...
- 银河英雄传说(codevs 1540)
题目描述 Description 公元五八○一年,地球居民迁移至金牛座α第二行星,在那里发表银河联邦创立宣言,同年改元为宇宙历元年,并开始向银河系深处拓展. 宇宙历七九九年,银河系的两大军事集团在巴米 ...
- apache + DSO -动态共享对象(DSO)
http://www.jinbuguo.com/apache/menu22/dso.html
- msp430项目编程07
msp430中项目---简单计算器 1.扫描键盘工作原理 2.电路原理说明 3.代码(显示部分) 4.代码(功能实现) 5.项目总结 msp430项目编程 msp430入门学习
- dpr——设备像素比(device pixel ratio)
设备像素比 = 物理像素 / 逻辑像素 1.物理像素 显示器上最小的物理显示单元(像素颗粒),在操作系统的调度下,每一个设备像素都有自己的颜色值和亮度值. 例如:手机大小固定,物理像素越高,画面越清晰 ...