SpringMVC-Controller
接上:
- Controller层是控制层,在其类上添加@Controller注解,会被Spring-servlet.xml中的<context:component-scan>扫描识别;
- 在类上添加@RequestMapping,表示定义了命名空间,e.g.@RequestMapping("/spitter"),'/spitter'表示访问到此类,但具体到哪个方法,还需追加方法上的RequestMapping的参数;
- 方法上的@RequestMapping还有一个参数,RequestMethod,与页面有关,一般表单数据使用POST方法,在<form>的参数method定义:<form method="post" action="...">;
- 本例中,register的GET方法,代表了最简单的交互,返回的registerForm与Spring-servlet.xml的前后缀组成/WEB-INF/views/registerForm.jsp,表示访问指定路径的jsp页面;
- 通过命名空间和访问方法就可以定位具体的方法,在SpringMVC中,在与页面交互执行一系列操作时,难免要传递参数,提交注册页面时,需要将各个单参数包装成Spitter,此时需要在页面上添加
<jsp:useBean id="spitter" class="com.spring.mvc.pojo.Spitter" scope="request" ></jsp:useBean>
- Controller中另外一个比较重要的参数是Model,它可以用来封装数据,只是现在的model不允许缺省参数名,否则会报错;
- SpringMVC支持REST风格,在参数前添加@PathVariable,在@RequestMapping中用{}包裹原参数;
- SpringMVC支持JSR303校验框架,在Controller的需要校验方法参数前添加@Valid注解,它位于javax.validation.Valid类中,同时需要添加Error或BindingResult类型参数,并且要紧跟在待验证参数的后面,jsp页面中input标签应采用SpringForm标签,并且使用errors标签通过path参数将错误信息与对应的参数绑定,当校验不通过时,errors会显示错误信息;
- 错误信息需要在POJO中通过注解表示
@NotNull @Size(max=20,min=4,message="长度必须在4-20个字符之间") private String firstName;
SpringMVC数据验证
- 若不喜欢硬编码,则可以将验证信息写在classpath目录下的ValidationMessages.properties
Controller:
1 package com.spring.mvc.controller;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.Locale;
6
7 import javax.servlet.http.HttpServletRequest;
8 import javax.servlet.http.HttpServletResponse;
9 import javax.validation.Valid;
10
11 import org.springframework.beans.factory.annotation.Autowired;
12 import org.springframework.stereotype.Controller;
13 import org.springframework.ui.Model;
14 //import org.springframework.validation.BindingResult;
15 import org.springframework.validation.Errors;
16 import org.springframework.validation.ObjectError;
17 import org.springframework.web.bind.annotation.ModelAttribute;
18 import org.springframework.web.bind.annotation.PathVariable;
19 import org.springframework.web.bind.annotation.RequestMapping;
20 import org.springframework.web.bind.annotation.RequestMethod;
21 import org.springframework.web.servlet.ModelAndView;
22 import org.springframework.web.servlet.i18n.CookieLocaleResolver;
23
24 import com.spring.mvc.dao.impl.SpitterDaoImpl;
25 import com.spring.mvc.pojo.Spitter;
26
27 @Controller
28 @RequestMapping("/spitter")
29 public class SpitterController {
30
31 @Autowired
32 private SpitterDaoImpl spitterDaoImpl;
33 /**
34 * 前往注册页面
35 * @return
36 */
37 @RequestMapping(value="/register",method=RequestMethod.GET)
38 public String register(){
39 return "registerForm";
40 }
41 /**
42 * 实现添加功能,完成后跳转至个人信息
43 * @param s
44 * @param mv
45 * @return
46 */
47 @RequestMapping(value="/register",method=RequestMethod.POST)
48 public String register(@Valid Spitter spitter,Errors errors){
49 if(errors.hasErrors()){
50 //取得所有验证未通过的error,遍历打印
51 List<ObjectError> list=new ArrayList<ObjectError>();
52 list=errors.getAllErrors();
53 for(int i=0;i<list.size();i++){
54 System.out.println(list.get(i).getDefaultMessage());
55 }
56 System.out.println(spitter);
57 System.out.println("属性验证未通过");
58 return "registerForm";
59 }
60 spitterDaoImpl.add(spitter);
61 return "redirect:/spitter/"+spitter.getUsername();
62 }
63 /**
64 * 获取个人信息
65 * @param username
66 * @param model
67 * @return
68 */
69 @RequestMapping(value="/{name}",method=RequestMethod.GET)
70 public String showSpitterProfile(@PathVariable("name") String username,Model model){
71 Spitter s=spitterDaoImpl.findByUsername(username);
72 System.out.println("传入的参数为:"+username);
73 System.out.println(s);
74 model.addAttribute("spitter",s);
75 return "profile";
76 }
77 public SpitterDaoImpl getSpitterDaoImpl() {
78 return spitterDaoImpl;
79 }
80 public void setSpitterDaoImpl(SpitterDaoImpl spitterDaoImpl) {
81 this.spitterDaoImpl = spitterDaoImpl;
82 }
83 }
registerForm.jsp:
1 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 2 <%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf"%> 3 <%@ page session="false" %> 4 <% 5 request.setCharacterEncoding("UTF-8"); 6 response.setCharacterEncoding("UTF-8"); 7 %> 8 <jsp:useBean id="spitte" class="com.spring.mvc.pojo.Spitter" scope="request" ></jsp:useBean> 9 <html> 10 <head> 11 <title>Spitter</title> 12 <link rel="stylesheet" type="text/css" 13 href="<c:url value="/resources/style.css" />" > 14 </head> 15 <body> 16 <h1>Register</h1> 17 18 <sf:form method="POST" modelAttribute="spitte"> 19 First Name: <sf:input type="text" path="firstName" /><sf:errors path="firstName" cssClass="errors"/><br/> 20 Last Name: <sf:input type="text" path="lastName" /><sf:errors path="lastName" cssClass="errors"/><br/> 21 Email: <sf:input type="email" path="email" /><sf:errors path="email" cssClass="errors"/><br/> 22 Username: <sf:input type="text" path="username" /><sf:errors path="username" cssClass="errors"/><br/> 23 Password: <sf:input type="password" path="password" /><sf:errors path="password" cssClass="errors"/><br/> 24 <input type="submit" value="Register" /> 25 </sf:form> 26 </body> 27 </html>
God, Grant me the SERENITY, to accept the things I cannot change,
COURAGE to change the things I can, and the WISDOM to know the difference.