- 创建POJO
-
1 package org.entity; 2 3 4 public class User { 5 private int id; 6 private String userName; 7 private String email; 8 private Address address; 9 public User(int id, String userName, String email, Address address) { 10 super(); 11 this.id = id; 12 this.userName = userName; 13 this.email = email; 14 this.address = address; 15 } 16 @Override 17 public String toString() { 18 return "User [id=" + id + ", userName=" + userName + ", email=" + email + ", address=" + address + "]"; 19 } 20 public User(int id, String userName, String email) { 21 super(); 22 this.id = id; 23 this.userName = userName; 24 this.email = email; 25 } 26 public Address getAddress() { 27 return address; 28 } 29 public void setAddress(Address address) { 30 this.address = address; 31 } 32 public int getId() { 33 return id; 34 } 35 public void setId(int id) { 36 this.id = id; 37 } 38 public String getUserName() { 39 return userName; 40 } 41 public void setUserName(String userName) { 42 this.userName = userName; 43 } 44 public String getEmail() { 45 return email; 46 } 47 public void setEmail(String email) { 48 this.email = email; 49 } 50 public User() { 51 } 52 }
-
1 package org.entity; 2 3 public class Address { 4 private String provience; 5 private String city; 6 public String getProvience() { 7 return provience; 8 } 9 public void setProvience(String provience) { 10 this.provience = provience; 11 } 12 public String getCity() { 13 return city; 14 } 15 public void setCity(String city) { 16 this.city = city; 17 } 18 @Override 19 public String toString() { 20 return "Address [provience=" + provience + ", city=" + city + "]"; 21 } 22 }
-
- 配置web.xml
-
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://xmlns.jcp.org/xml/ns/javaee" 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 5 id="WebApp_ID" version="3.1"> 6 <!--配置DispatcherServlet --> 7 <!-- The front controller of this Spring Web application, responsible for handling all application requests --> 8 <servlet> 9 <servlet-name>springDispatcherServlet</servlet-name> 10 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 11 <!-- 配置DiapacherServlet初始化参数 --> 12 <init-param> 13 <param-name>contextConfigLocation</param-name> 14 <param-value>classpath:springmvc.xml</param-value> 15 </init-param> 16 <!-- --> 17 <load-on-startup>1</load-on-startup> 18 </servlet> 19 20 <!-- Map all requests to the DispatcherServlet for handling --> 21 <servlet-mapping> 22 <servlet-name>springDispatcherServlet</servlet-name> 23 <url-pattern>/</url-pattern> 24 </servlet-mapping> 25 </web-app>
-
- 配置SpringMVC.xml
-
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xmlns:task="http://www.springframework.org/schema/task" 7 xmlns:aop="http://www.springframework.org/schema/aop" 8 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 9 http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd 10 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd 11 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd 12 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 13 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd 14 http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd 15 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 16 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> 17 <!-- 配置自定义扫描得包 --> 18 <context:component-scan base-package="org.handler"></context:component-scan> 19 <!-- 配置视图解析器:如何把handler返回值解析为实际的物理视图 --> 20 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 21 <property name="prefix" value="/WEB-INF/views/"></property> 22 <property name="suffix" value=".jsp"/> 23 </bean> 24 <!-- 自定义图 视图解析器 使用视图的名字来解析视图--> 25 <!-- 通过order属性来定义视图优先级 order值越小优先级越高--> 26 <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"> 27 <property name="order" value="100"></property> 28 </bean> 29 <!-- 配置直接转发的页面 --> 30 <mvc:view-controller path="/success" view-name="success"/> 31 <!-- 在实际开发中需要配置mvc:annotation-driven标签 --> 32 <mvc:annotation-driven></mvc:annotation-driven> 33 <!-- 配置国际化资源文件 --> 34 <bean id="messageSource" 35 class="org.springframework.context.support.ResourceBundleMessageSource"> 36 <property name="basename" value="i18n"></property> 37 </bean> 38 39 </beans>
-
- 编写jsp
- index.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 8 <title>Insert title here</title> 9 </head> 10 <body> 11 <a href="helloword">Hello Word</a> 12 <br> 13 <form action="testUser"> 14 id:<input type="text" name="id"/> 15 <br> 16 userName:<input type="text" name="userName"/> 17 <br> 18 email:<input type="text" name="email"/> 19 <br> 20 provience:<input type="text" name="address.provience"/> 21 <br> 22 city:<input type="text" name="address.city"/> 23 <input type="submit" value="提交"/> 24 </form> 25 <br/> 26 <a href="testServletAPI">testServletAPI</a> 27 <br> 28 <a href="testModelAndView">testModelAndView</a> 29 <br> 30 <a href="testMap">test Map</a> 31 <br> 32 <a href="testSessionAttributes">testSessionAttributes</a> 33 34 <br><br> 35 <!-- 36 模拟修改操作 37 1.原始数据为 1 tom @tom.com 38 2.名字不能被修改 39 3.表单回显,模拟操作直接在表单填写对应的属性值 40 --> 41 <form action="testModelAttribute"> 42 <input type="hidden" name = "id" value="1"/> 43 email:<input type="text" name ="email" value="@tom.com"/> 44 <input type="submit" value="提交"/> 45 </form> 46 <br><br> 47 48 <a href="testViewSourceAndViewResolver">testViewSourceAndViewResolver</a> 49 50 <br><br> 51 国际化: 52 <br> 53 <fmt:message key="i18n.username"></fmt:message> 54 <br> 55 <fmt:message key="i18n.password"></fmt:message> 56 57 <br><br> 58 <a href="testView">testView</a> 59 <br><br> 60 <a href=testRedirect>testRedirect</a> 61 </body> 62 </html>
- success.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 8 <title>Insert title here</title> 9 </head> 10 <body> 11 hello SpringMVC 12 <br> 13 time: ${requestScope.time} 14 <br> 15 name: ${requestScope.names} 16 <br><br> 17 request user: ${requestScope.user} 18 <br> 19 session user: ${sessionScope.user} 20 <br><br> 21 request email: ${requestScope.email} 22 <br> 23 session email: ${sessionScope.email} 24 <br> 25 <br><br> 26 国际化: 27 <br> 28 <fmt:message key="i18n.username"></fmt:message> 29 <br> 30 <fmt:message key="i18n.password"></fmt:message> 31 </body> 32 </html>
- index.jsp
- 编写Handler
-
1 package org.handler; 2 3 import java.io.IOException; 4 import java.io.Writer; 5 import java.util.Arrays; 6 import java.util.Date; 7 import java.util.HashMap; 8 import java.util.Map; 9 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 import javax.xml.ws.soap.MTOM; 13 14 import org.apache.catalina.startup.Tomcat; 15 import org.apache.taglibs.standard.lang.jstl.test.beans.PublicInterface2; 16 import org.entity.User; 17 import org.omg.PortableInterceptor.SUCCESSFUL; 18 import org.springframework.stereotype.Controller; 19 import org.springframework.validation.Errors; 20 import org.springframework.web.bind.annotation.ModelAttribute; 21 import org.springframework.web.bind.annotation.RequestMapping; 22 import org.springframework.web.bind.annotation.RequestParam; 23 import org.springframework.web.bind.annotation.SessionAttributes; 24 import org.springframework.web.servlet.ModelAndView; 25 import com.sun.net.httpserver.Authenticator.Success; 26 import com.sun.org.apache.bcel.internal.generic.NEW; 27 import com.sun.org.apache.regexp.internal.recompile; 28 //@SessionAttributes(value={"user"},types={String.class}) 29 @Controller 30 public class SpringMVC { 31 public static String SUCCESS = "success"; 32 /** 33 * 使用@RequestMapping注解来映射请求的URL 34 * @return 35 */ 36 @RequestMapping("/helloword") 37 public String testhello() { 38 System.out.println("helloword"); 39 return "success"; 40 } 41 /** 42 * 支持提交pojo 会根据name与pojo属性进行匹配 支持级联属性 43 * @param user 44 * @return 45 */ 46 @RequestMapping("/testUser") 47 public String testUser(User user) { 48 System.out.println("User:"+user.toString()); 49 return "success"; 50 } 51 /** 52 * 支持使用servlet原生api 53 * HttpServletReqyest 54 * HttpServletResponse 55 * HttpSession 56 * java.security.Prinipal 57 * Locale 58 * InputStream 59 * OutputStream 60 * Reader 61 * Writer 62 * @throws IOException 63 */ 64 @RequestMapping("testServletAPI") 65 public String testServletAPI(HttpServletRequest request, 66 HttpServletResponse response, 67 Writer out) throws IOException { 68 69 System.out.println("testServletAPI:"+request+"\n"+response+"\n"+out); 70 out.write("hello writer"); 71 out.write(1111); 72 return "success"; 73 } 74 /** 75 * ModelAndView 76 * Map及Model 77 * @sessionAttributes 78 * @ModelAttribute 79 * 目标方法的返回值可以是ModelAndView类型其中包含视图和模型信息 80 */ 81 @RequestMapping("testModelAndView") 82 public ModelAndView testModelAndView() { 83 String viewName="success"; 84 ModelAndView modelAndView = new ModelAndView(viewName); 85 modelAndView.addObject("time",new Date()); 86 return modelAndView; 87 } 88 /** 89 * 目标方法可以添加map(也可以是Model类型或ModelMap类型)类型参数 90 * @param map 91 * @return 92 */ 93 @RequestMapping("testMap") 94 public String testMap(Map<String,Object> map) { 95 map.put("names",Arrays.asList("tom","jerry","mike")); 96 return "success"; 97 } 98 /** 99 * map 默认在request域里不会装进Session域 100 * 用sessionAttributes在controller类上做注解使属性值进入session域 101 * 其括号内可放键、值 如上设置 102 * @SessionAttributes(value={"user"},types={String.class}) 103 * 表示将 键 为"user" 或 值为String类型的 键值对放入session域 104 * 注意 :该注解只能放在类上 105 */ 106 107 @RequestMapping("testSessionAttributes") 108 public String testSessionAttributes(Map<String, Object> map) { 109 User user = new User(121,"tom","@qwqx.com"); 110 map.put("user", user); 111 map.put("email", "@myemail.com"); 112 return SUCCESS; 113 } 114 /**@RequestMapping("testModelAttribute") 115 * 如果数据库中的数据进行修改操作,默认的表单提交会new一个对象传回后台 116 * 如果规定某些属性无法修改,在表单里我们是不需要列出来的,而表单里我们不对属性进行赋值, 117 * 会造成对象属性为null,在写入数据库时造成麻烦, 118 * 当然我们可以用hidden赋值,但如果是私密属性又会有麻烦 119 * 在这里我们可以选择先从数据库插叙获取到对象,传送到页面,表单提交只是对属性值作出更改,而不是新建对象 120 */ 121 @RequestMapping("testModelAttribute") 122 public String testModelAttribute(@ModelAttribute("user")User user) { 123 System.out.println("修改:"+user); 124 return SUCCESS; 125 } 126 /** 127 * 由@ModelAttribute标记的方法会在每个目标方法执行之前被SpringMVC调用 128 * 在ModelAttribute修饰的方法中,放入到Map时的键需要和目标方法参数类型的第一个字母小写的字符串一致 129 * 可以在目标方法的参数上用@ModelAttribute("user") 用于指定获取对象时需要查找的键 130 * testModelAttribute(@ModelAttribute("user")User user) 131 */ 132 @ModelAttribute 133 public void getUser(@RequestParam(value="id",required=false) Integer id, 134 Map<String, Object> map) { 135 if(id!=null) { 136 // 假设user为数据库查询出来的对象 137 User user = new User(2,"Tom", "@tom.com"); 138 System.out.println("数据库查询出来的对象:"+user.toString()); 139 map.put("user",user); 140 } 141 } 142 @RequestMapping("testViewSourceAndViewResolver") 143 public String testViewSourceAndViewResolver() { 144 145 return SUCCESS; 146 } 147 @RequestMapping("testView") 148 public String testView() { 149 System.out.println("testView"); 150 return "helloView"; 151 } 152 @RequestMapping("testRedirect") 153 public String testRedirect() { 154 System.out.println("testRedirect"); 155 return "redirect:/index.jsp"; 156 } 157 }
-
自定义视图测试:
1 package org.views; 2 3 import java.util.Date; 4 import java.util.Map; 5 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 import org.springframework.stereotype.Component; 10 import org.springframework.web.servlet.View; 11 12 @Component 13 public class HelloView implements View{ 14 15 @Override 16 public String getContentType() { 17 return "text/html"; 18 } 19 20 @Override 21 public void render(Map<String, ?> arg0, HttpServletRequest arg1, HttpServletResponse arg2) throws Exception { 22 arg2.getWriter().print("hello view .time"+new Date()); 23 } 24 25 }