微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尚硅谷SpringMVC代码笔记之SpringMVC_1

项目结构:



用来测试的index.jsp首页视图:



index.jsp页面代码

<%@ page language=java contentType=text/html; charset=ISO⑻859⑴ pageEncoding=ISO⑻859⑴%> <!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⑻859⑴> <title>Insert title here</title> </head> <body> <a href=helloworld>Hello World</a> <br> <a href=springmvc/testRequestMapping>Test RequestMapping</a> <br> <!-- 许为get要求 --> <a href=springmvc/testMethod>Test GET Method</a> <br> <!-- 弄个表单,发post要求 --> <form action=springmvc/testMethod method=post> <input type=submit value=Test POST Method/> </form> <br> <a href=springmvc/testParamsAndHeaders?username=atguigu&age=11>Test ParamsAndHeaders</a> <br> <a href=springmvc/testAntPath/mnxyzaaa/abc>Test AntPath</a> <br> <a href=springmvc/testPathVariable/1>Test PathVariable</a> <br> <a href=springmvc/testRest/2>Test Rest Get</a> <br> <form action=springmvc/testRest method=post> <input type=submit value=TestRest POST/> </form> <br> <form action=springmvc/testRest/3 method=post> <input type=hidden name=_method value=DELETE/> <input type=submit value=TestRest Delete/> </form> <br> <form action=springmvc/testRest/4 method=post> <input type=hidden name=_method value=PUT/> <input type=submit value=TestRest PUT/> </form> <br> <a href=springmvc/testRequestParam?username=atguigu&age=11>Test RequestParam</a> <br> <a href=springmvc/testRequestHeader>Test RequestHeader</a> <br> <a href=springmvc/testCookieValue>Test CookieValue</a> <br><br> <form action=springmvc/testPojo method=post> 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> province:<input type=text name=address.province/> <br> city:<input type=text name=address.city/> <br> <input type=submit value=testPojo/> <br> </form> <br> <a href=springmvc/testServletAPI>Test ServletAPI</a> <br> <a href=springmvc/testModelAndView>Test ModelAndView</a> <br> <br> <a href=springmvc/testMap>Test Map</a> <br> <a href=springmvc/testSessionAttributes>Test SessionAttributes</a> <br> <!-- 摹拟修改操作 1. 原始数据为: 1,Tom,123456,[email protected],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 [email protected]/> <br> age: <input type=text name=age value=12/> <br> <input type=submit value=Test modelattribute/> </form> <br> <a href=springmvc/testViewAndViewResolver>Test ViewAndViewResolver</a> <br> <a href=springmvc/testView>Test View</a> <br> <a href=springmvc/testRedirect>Test Redirect</a> <br><br><br> </body> </html>


实体类

package com.atguigu.springmvc.entities; public class User { private Integer id; private String username; private String password; private String email; private int age; public Address address; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getpassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } @Override public String toString() { return User [id= + id + ,username= + username + ,password= + password + ,email= + email + ,age= + age + ,address= + address + ]; } public User(String username,String password,String email,int age) { super(); this.username = username; this.password = password; this.email = email; this.age = age; } public User(Integer id,String username,int age) { super(); this.id = id; this.username = username; this.password = password; this.email = email; this.age = age; } public User() {} } package com.atguigu.springmvc.entities; public class Address { private String province; // 省 private String city; // 市 public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return Address [province= + province + ,city= + city + ]; } }

自定义视图类:

package com.atguigu.springmvc.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,?> model,HttpServletRequest request,HttpServletResponse response) throws Exception { response.getWriter().print(hello view,time: + new Date()); } }


控制器SpringMVCTest文件代码

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 { private static final String SUCCESS=success; /** * 1. @RequestMapping 除修饰方法,还可来修饰类 * 2. * 1). 类定义处: 提供初步的要求映照信息。相对 WEB 利用的根目录 * 2). 方法处: 提供进1步的细分映照信息。 相对类定义处的 URL。若类定义处未标注 @RequestMapping,则方法标记的 URL * 相对 WEB 利用的根目录 */ @RequestMapping(/testRequestMapping) public String testRequestMapping(){ System.out.println(testRequestMapping); return SUCCESS; } /** * 经常使用: 使用 method 属性来指定要求方式 */ @RequestMapping(value=/testMethod,method=RequestMethod.POST) public String testMethod(){ System.out.println(testMethod); return SUCCESS; } /** * 了解: 可使用 params 和 headers 来更加精确的映照要求. params 和 headers 支持简单的表达式. * * @return */ @RequestMapping(value=testParamsAndHeaders,params={username,age!=10},headers = { Accept-Language=zh-CN,zh;q=0.8 }) public String testParamsAndHeaders(){ System.out.println(testParamsAndHeaders); return SUCCESS; } /** * 支持通配符 * @return */ @RequestMapping(/testAntPath/*/abc) public String testAntPath(){ System.out.println(testAntPath); return SUCCESS; } /** * @PathVariable 可以来映照 URL 中的占位符到目标方法的参数中. * @param id * @return */ @RequestMapping(/testPathVariable/{id}) public String testPathVariable(@PathVariable(id) Integer id){ 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 要求时携带1个 name=_method 的隐藏域,值为 DELETE 或 PUT * * 在 SpringMVC 的目标方法中如何得到 id 呢? 使用 @PathVariable 注解 */ @RequestMapping(value=/testRest/{id},method=RequestMethod.GET) public String testRest(@PathVariable Integer id){ System.out.println(testRest GET:+id); return SUCCESS; } @RequestMapping(value=/testRest,method=RequestMethod.POST) public String testRest(){ System.out.println(testRest POST); return SUCCESS; } @RequestMapping(value=/testRest/{id},method=RequestMethod.DELETE) public String testRestDelete(@PathVariable Integer id){ System.out.println(testRest Delete:+id); return SUCCESS; } @RequestMapping(value=/testRest/{id},method=RequestMethod.PUT) public String testRestPut(@PathVariable Integer id){ System.out.println(testRest Put: + id); return SUCCESS; } /** * @RequestParam 来映照要求参数. value 值即要求参数的参数名 required 该参数是不是必须. 许为 true * defaultValue 要求参数的许值 */ @RequestMapping(value=/testRequestParam) public String testRequestParam(@RequestParam(value=username) String un,@RequestParam(value=age,required=false,defaultValue=0) int age){ System.out.println(testRequestParam,username: + un + ,age: + age); return SUCCESS; } /** * 了解: 映照要求头信息 用法同 @RequestParam */ @RequestMapping(/testRequestHeader) public String testRequestHeader( @RequestHeader(value = Accept-Language) String al) { System.out.println(testRequestHeader,Accept-Language: + al); return SUCCESS; } /** * 了解: * * @CookieValue: 映照1个 Cookie 值. 属性同 @RequestParam */ @RequestMapping(/testCookieValue) public String testCookieValue(@CookieValue(JSESSIONID) String sessionId) { System.out.println(testCookieValue: sessionId: + sessionId); return SUCCESS; } /** * Spring MVC 会按要求参数名和 POJO 属性名进行自动匹配, 自动为该对象填充属性值。支持级联属性。 * 如:dept.deptId、dept.address.tel 等 */ @RequestMapping(/testPojo) public String testPojo(User user){ System.out.println(testPojo: + user); return SUCCESS; } /** * 可使用 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; } /** * 目标方法的返回值可以是 ModelAndView 类型。 * 其中可以包括视图和模型信息 * SpringMVC 会把 ModelAndView 的 model 中数据放入到 request 域对象中. * @return */ @RequestMapping(/testModelAndView) public ModelAndView testModelAndView(){ String viewName=SUCCESS; ModelAndView mv=new ModelAndView(viewName); //添加模型数据到 ModelAndView 中. mv.addobject(time,new Date()); return mv; } /** * 目标方法可以添加 Map 类型(实际上也能够是 Model 类型或 ModelMap 类型)的参数. * @param map * @return */ @RequestMapping(/testMap) public String testMap(Map<String,Object> map){ System.out.println(map.getClass().getName()); map.put(names,Arrays.asList(Tom,Jerry,Mike)); return SUCCESS; } /** * @SessionAttributes 除可以通过属性名指定需要放到会话中的属性外(实际上使用的是 value 属性值),* 还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中(实际上使用的是 types 属性值) * * 注意: 该注解只能放在类的上面. 而不能修饰放方法. */ @RequestMapping(/testSessionAttributes) public String testSessionAttributes(Map<String,Object> map){ User user=new User(Tom,123456,[email protected],15); map.put(user,user); map.put(shool,atguigu); return SUCCESS; } /** * 运行流程: * 1. 履行 @modelattribute 注解修饰的方法: 从数据库中取出对象,把对象放入到了 Map 中. 键为: user * 2. SpringMVC 从 Map 中取出 User 对象,并把表单的要求参数赋给该 User 对象的对应属性. * 3. SpringMVC 把上述对象传入目标方法的参数. * * 注意: 在 @modelattribute 修饰的方法中,放入到 Map 时的键需要和目标方法入参类型的第1个字母小写的字符串1致! * * SpringMVC 肯定目标方法 POJO 类型入参的进程 * 1. 肯定1个 key: * 1). 若目标方法的 POJO 类型的参数木有使用 @modelattribute 作为修饰,则 key 为 POJO 类名第1个字母的小写 * 2). 若使用了 @modelattribute 来修饰,则 key 为 @modelattribute 注解的 value 属性值. * 2. 在 implicitModel 中查找 key 对应的对象,若存在,则作为入参传入 * 1). 若在 @modelattribute 标记方法中在 Map 中保存过,且 key 和 1 肯定的 key 1致,则会获得到. * 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 为类名第1个字母小写. * *注意: 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; } /** * 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(null!=id){ //摹拟从数据库中获得对象 User user=new User(1,Tom,12); System.out.println(从数据库中取1个对象:+user); map.put(user,user); } } /** * 测试视图和视图解析器 * @return */ @RequestMapping(/testViewAndViewResolver) public String testViewAndViewResolver(){ System.out.println(testViewAndViewResolver); return SUCCESS; } /** * 测试 视图 BeanNameViewResolver 解析器(需要在springmvc配置文件中配置对应的bean) * @return */ @RequestMapping(/testView) public String testView(){ System.out.println(testView); return helloview; } @RequestMapping(/testRedirect) public String testRedirect(){ System.out.println(testRedirect); return redirect:/index.jsp; } }


跳转页面sucess页面代码

<%@ page language=java contentType=text/html; charset=ISO⑻859⑴ pageEncoding=ISO⑻859⑴%> <%@ taglib prefix=ftm 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⑻859⑴> <title>Insert title here</title> </head> <body> <h4>Sucess Page</h4> time: ${requestScope.time} <br> names: ${requestScope.names } <br> request user: ${requestScope.user } <br> session user: ${sessionScope.user } <br><br> <ftm:message key=i18n.username></ftm:message> <br><br> <ftm:message key=i18n.password></ftm:message> <br><br> </body> </html>


SpringMVC配置文件 springmvc.xml代码

<?xml version=1.0 encoding=UTF⑻?> <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/mvc http://www.springframework.org/schema/mvc/spring-mvc⑷.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⑷.0.xsd> <!-- 配置自动扫描的包 --> <context:component-scan base-package=com.atguigu.springmvc/> <!-- 配置视图解析器: 如何把 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/> </bean> <!-- 配置国际化资源文件 --> <bean id=messageSource class=org.springframework.context.support.ResourceBundleMessageSource> <property name=basename value=i18n></property> </bean> <!-- 配置直接转发的页面 --> <!-- 可以直接相应转发的页面,而无需再经过 Handler 的方法. --> <mvc:view-controller path=/success view-name=success/> <!-- 在实际开发中通常都需配置 mvc:annotation-driven 标签 --> <mvc:annotation-driven></mvc:annotation-driven> </beans>

web.xml代码

<?xml version=1.0 encoding=UTF⑻?> <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_3_0.xsd id=WebApp_ID version=3.0> <display-name>SpringMVC_1</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置 dispatcherServlet --> <servlet> <servlet-name>springdispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherServlet</servlet-class> <!-- 配置 dispatcherServlet 的1个初始化参数: 配置 SpringMVC 配置文件的位置和名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springdispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置 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> </web-app>


版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐