本文主要是讲解在Controller中的开发,主要的知识点有以下:javascript
@RequestMapping
详解在SpringMVC的控制器中,若是没有对编码进行任何的操做,那么获取到的中文数据是乱码!html
即便咱们在handle()方法中,使用request对象设置编码也不行!缘由也很是简单,咱们SpringMVC接收参数是经过控制器中的无参构造方法,再通过handle()方法的object对象来获得具体的参数类型的。java
Struts2是使用拦截器来自动帮咱们完成中文乱码的问题的。那么SpringMVC做为一个更增强大的框架,确定也有对应的方法来帮咱们完成中文乱码问题!web
值得注意的是:该过滤编码器只能解决POST的乱码问题!ajax
咱们只须要在web.xml配置文件中设置过滤编码器就好了!spring
<!-- 编码过滤器 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
咱们在快速入门的例子中使用的是XML配置的方式来使用SpringMVC的,SpringMVC也可以支持注解。【我的很是喜欢注解的方式】json
咱们在使用Action的时候,要么继承着AbstractCommandController类,要么显示使用注解Controller接口。当咱们使用了注解之后就不用显示地继承或实现任何类了!数组
使用@Controller这个注解,就代表这是一个SpringMVC的控制器!微信
@Controller public class HelloAction { }
固然了,如今Spring是不知道有这么一个注解的,所以咱们须要在配置文件中配置扫描注解session
值得注意的是:在配置扫描路径的时候,后面不要加.*
否则扫描不了,我不知道学Struts2仍是其余的地方时候,习惯加了.*,因而就搞了好久!
<!--扫描注解,后面不要加.*--> <context:component-scan base-package="zhongfucheng"/>
在控制器中写业务方法
@Controller public class HelloAction { /** * * @RequestMapping 表示只要是/hello.action的请求,就交由该方法处理。固然了.action能够去掉 * @param model 它和ModelAndView相似,它这个Model就是把数据封装到request对象中,咱们就能够获取出来 * @return 返回跳转的页面【真实路径,就不用配置视图解析器了】 * @throws Exception */ @RequestMapping(value="/hello.action") public String hello(Model model) throws Exception{ System.out.println("HelloAction::hello()"); model.addAttribute("message","你好"); return "/index.jsp"; } }
跳转到index页面,首页获得对应的值。
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> 这是个人首页 <br> ${message} </body> </html>
固然了,基于注解和基于XML来开发SpringMVC,都是经过映射器、适配器和视图解析器的。 只是映射器、适配器略有不一样。可是都是能够省略的!
<!-- 基于注解的映射器(可选) --> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> <!-- 基于注解的适配器(可选) --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <!-- 视图解析器(可选) --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>
更新:上边的适配器和映射器只是Spring3.1版本以前使用的、3.1版本以后如今通常用如下的两个
映射器: org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping 适配器: org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
固然了,这上面两个配置也可使用<mvc:annotation-driven>
>替代注解处理器和适配器的配置。
@RequestMapping可以控制请求路径和请求方式!
到目前为止,咱们都是一个控制器写一个业务方法,这确定是不合理的。咱们在Struts2中一个Action就对应多个业务方法了。那么咱们在SpringMVC中又怎么写呢???
其实咱们能够推理出来,@RequestMapping就是用于配置哪一个请求对应哪一个业务方法的!
public @interface RequestMapping { String[] value() default {}; RequestMethod[] method() default {}; String[] params() default {}; String[] headers() default {}; }
当咱们请求hello.action的时候,处理的业务方法是hello().....当咱们请求bye.action的时候,处理的业务方法是bye()
@Controller public class HelloAction { /** * * @RequestMapping 表示只要是/hello.action的请求,就交由该方法处理。固然了.action能够去掉 * @param model 它和ModelAndView相似,它这个Model就是把数据封装到request对象中,咱们就能够获取出来 * @return 返回跳转的页面【真实路径,就不用配置视图解析器了】 * @throws Exception */ @RequestMapping(value="/hello.action") public String hello(Model model) throws Exception{ System.out.println("HelloAction::hello()"); model.addAttribute("message","你好"); return "/index.jsp"; } @RequestMapping(value = "/bye.action") public String bye(Model model) throws Exception { model.addAttribute("message","再见"); return "/index.jsp"; } }
固然了,咱们在Struts2经常使用namespace来进行分模块开发,在SpringMVC中咱们也能够这样干,而且咱们又是使用的是@RequestMapping这个注解!
只要把@RequestMapping这个注解写到类上面去,就表明了分模块。
@Controller //咱们知道,若是是value属性上的注解,咱们能够把value省略掉的 @RequestMapping("/zhongfucheng") public class HelloAction { /** * @param model 它和ModelAndView相似,它这个Model就是把数据封装到request对象中,咱们就能够获取出来 * @return 返回跳转的页面【真实路径,就不用配置视图解析器了】 * @throws Exception * @RequestMapping 表示只要是/hello.action的请求,就交由该方法处理。固然了.action能够去掉 */ @RequestMapping(value = "/hello.action") public String hello(Model model) throws Exception { System.out.println("HelloAction::hello()"); model.addAttribute("message", "你好"); return "/index.jsp"; } @RequestMapping(value = "/bye.action") public String bye(Model model) throws Exception { model.addAttribute("message", "再见"); return "/index.jsp"; } }
那么咱们想要HelloAction该控制器处理咱们的请求,访问的地址要么是:http://localhost:8080/zhongfucheng/hello.action
,或者要么是http://localhost:8080/zhongfucheng/bye.action
咱们若是想要限定某个业务控制方法,只容许GET或POST请求方式访问。仍是经过@RequestMapping来实现。只要设定它的method属性就好了!
@RequestMapping(value = "/bye.action",method = RequestMethod.POST) public String bye(Model model) throws Exception { model.addAttribute("message", "再见"); return "/index.jsp"; }
当我把业务方法的请求设置为POST之后,我想要经过GET方式来访问该业务方法。就行不通了!
咱们的业务方法除了能够写Model这个参数之外,若是有须要咱们还能够写request,response等传统Servlet的参数。这是同样可使用的....
可是呢,咱们并不建议使用传统的web参数,由于会耦合
@RequestMapping(method=RequestMethod.POST,value="/register") public String registerMethod(HttpServletRequest request,HttpServletResponse response) throws Exception{ //获取用户名和薪水 String username = request.getParameter("username"); String salary = request.getParameter("salary"); System.out.println("用户注册-->" + username + ":" + salary); //绑定到session域对象中 request.getSession().setAttribute("username",username); request.getSession().setAttribute("salary",salary); //重定向/jsp/success.jsp页面 //response.sendRedirect(request.getContextPath()+"/jsp/success.jsp"); //转发/jsp/ok.jsp页面 request.getRequestDispatcher("/jsp/ok.jsp").forward(request,response); //转发(提倡) return "/jsp/success.jsp"; }
小细节:若是咱们的返回值是返回一个真实路径,而咱们在程序中又使用了转发或重定向。。。那么具体跳转的位置就是按咱们程序中跳转的路径为准!
咱们在Struts2中收集web端带过来的参数是在控制器中定义成员变量,该成员变量的名字与web端带过来的名称是要一致的...而且,给出该成员变量的set方法,那么Struts2的拦截器就会帮咱们自动把web端带过来的参数赋值给咱们的成员变量....
那么在SpringMVC中是怎么收集参数的呢????咱们SpringMVC是不可能跟Struts2同样定义成员变量的,由于SpringMVC是单例的,而Struts2是多例的。所以SpringMVC是这样干的:
若是是普通参数的话,咱们直接在方法上写上与web端带过来名称相同的参数就好了!
<form action="${pageContext.request.contextPath}/hello.action" method="post"> <table align="center"> <tr> <td>用户名:</td> <td><input type="text" name="username"></td> </tr> <tr> <td>编号</td> <td><input type="text" name="id"></td> </tr> <tr> <td colspan="2"> <input type="submit" value="提交"> </td> </tr> </table> </form>
@RequestMapping(value = "/hello.action") public String hello(Model model, String username, int id) throws Exception { System.out.println("用户名是:" + username); System.out.println("编号是:" + id); model.addAttribute("message", "你好"); return "/index.jsp"; }
效果:
咱们处理表单的参数,若是表单带过来的数据较多,咱们都是用JavaBean对其进行封装的。那么咱们在SpringMVC也是能够这么作的。
建立JavaBean,javaBean属性与表单带过来的名称相同
public class User { private String id; private String username; public User() { } public User(String id, String username) { this.id = id; this.username = username; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String toString() { return "User{" + "id='" + id + '\'' + ", username='" + username + '\'' + '}'; } }
在业务方法参数上写入Javabean
@RequestMapping(value = "/hello.action") public String hello(Model model,User user) throws Exception { System.out.println(user); model.addAttribute("message", "你好"); return "/index.jsp"; }
收集数组和收集普通的参数是相似的,看了如下的代码就懂了。
<form action="${pageContext.request.contextPath}/hello.action" method="post"> <table align="center"> <tr> <td>用户名:</td> <td><input type="text" name="username"></td> </tr> <tr> <td>爱好</td> <td><input type="checkbox" name="hobby" value="1">篮球</td> <td><input type="checkbox" name="hobby" value="2">足球</td> <td><input type="checkbox" name="hobby" value="3">排球</td> <td><input type="checkbox" name="hobby" value="4">羽毛球</td> </tr> <tr> <td colspan="2"> <input type="submit" value="提交"> </td> </tr> </table> </form>
业务方法获取参数
@RequestMapping(value = "/hello.action") public String hello(Model model,int[] hobby) throws Exception { for (int i : hobby) { System.out.println("喜欢运动的编号是:" + i); } model.addAttribute("message", "你好"); return "/index.jsp"; }
效果:
List<JavaBean>
集合咱们在Spring的业务方法中是不能够用List<JavaBean>这样的参数来接收的,SpringMVC给了咱们另外一种方案!
咱们使用一个JavaBean把集合封装起来,给出对应的set和get方法。那么咱们在接收参数的时候,接收的是JavaBean
/** * 封装多个Emp的对象 * @author AdminTC */ public class Bean { private List<Emp> empList = new ArrayList<Emp>(); public Bean(){} public List<Emp> getEmpList() { return empList; } public void setEmpList(List<Emp> empList) { this.empList = empList; } }
业务方法接收JavaBean对象
/** * 批量添加员工 */ @RequestMapping(value="/addAll",method=RequestMethod.POST) public String addAll(Model model,Bean bean) throws Exception{ for(Emp emp:bean.getEmpList()){ System.out.println(emp.getUsername()+":"+emp.getSalary()); } model.addAttribute("message","批量增长员工成功"); return "/jsp/ok.jsp"; }
在JSP页面直接写上empList[下表].
<form action="${pageContext.request.contextPath}/emp/addAll.action" method="POST"> <table border="2" align="center"> <caption><h2>批量注册员工</h2></caption> <tr> <td><input type="text" name="empList[0].username" value="哈哈"/></td> <td><input type="text" name="empList[0].salary" value="7000"/></td> </tr> <tr> <td><input type="text" name="empList[1].username" value="呵呵"/></td> <td><input type="text" name="empList[1].salary" value="7500"/></td> </tr> <tr> <td><input type="text" name="empList[2].username" value="班长"/></td> <td><input type="text" name="empList[2].salary" value="8000"/></td> </tr> <tr> <td><input type="text" name="empList[3].username" value="键状哥"/></td> <td><input type="text" name="empList[3].salary" value="8000"/></td> </tr> <tr> <td><input type="text" name="empList[4].username" value="绿同窗"/></td> <td><input type="text" name="empList[4].salary" value="9000"/></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="批量注册"/> </td> </tr> </table> </form>
其实这种方法看起来也没有那么难理解,咱们就是向上封装了一层【与接收普通的JavaBean相似的】。
咱们有可能在JSP页面上即有User模型的数据要收集,又有Emp模型的数据要收集....而且User模型的属性和Emp模型的属性如出一辙....此时咱们该怎么办呢???
咱们也是能够在User模型和Emp模型上向上抽象出一个Bean,该Bean有Emp和User对象
/** * 封装User和Admin的对象 * @author AdminTC */ public class Bean { private User user; private Admin admin; public Bean(){} public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Admin getAdmin() { return admin; } public void setAdmin(Admin admin) { this.admin = admin; } }
在JSP页面收集的时候,给出对应的类型就好了。
<form action="${pageContext.request.contextPath}/person/register.action" method="POST"> <table border="2" align="center"> <tr> <th>姓名</th> <td><input type="text" name="user.username" value="${user.username}"/></td> </tr> <tr> <th>月薪</th> <td><input type="text" name="user.salary" value="${user.salary}"></td> </tr> <tr> <th>入职时间</th> <td><input type="text" name="user.hiredate" value='<fmt:formatDate value="${user.hiredate}" type="date" dateStyle="default"/>'/></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="普通用户注册" style="width:111px"/> </td> </tr> </table> </form>
咱们在Struts2中,若是web端传过来的字符串类型是yyyy-mm-dd hh:MM:ss这种类型的话,那么Struts2默认是能够自动解析成日期的,若是是别的字符串类型的话,Struts2是不能自动解析的。要么使用自定义转换器来解析,要么就本身使用Java程序来解析....
而在SpringMVC中,即便是yyyy-mm-dd hh:MM:ss这种类型SpringMVC也是不能自动帮咱们解析的。咱们看以下的例子:
JSP传递关于日期格式的字符串给控制器...
<form action="${pageContext.request.contextPath}/hello.action" method="post"> <table align="center"> <tr> <td>用户名:</td> <td><input type="text" name="username"></td> </tr> <tr> <td>出生日期</td> <td><input type="text" name="date" value="1996-05-24"></td> </tr> <tr> <td colspan="2"> <input type="submit" value="提交"> </td> </tr> </table> </form>
User对象定义Date成员变量接收
public Date getDate() { return date; } public void setDate(Date date) { this.date = date; }
业务方法获取Date值
@RequestMapping(value = "/hello.action") public String hello(Model model, User user) throws Exception { System.out.println(user.getUsername() + "的出生日期是:" + user.getDate()); model.addAttribute("message", "你好"); return "/index.jsp"; }
结果出问题了,SpringMVC不支持这种类型的参数:
如今问题就抛出来了,那咱们要怎么解决呢????
SpringMVC给出相似于Struts2类型转换器这么一个方法给咱们使用:若是咱们使用的是继承AbstractCommandController类来进行开发的话,咱们就能够重写initBinder()方法了....
具体的实现是这样子的:
@Override protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception { binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true)); }
那咱们如今用的是注解的方式来进行开发,是没有重写方法的。所以咱们须要用到的是一个注解,代表我要重写该方法!
@InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { binder.registerCustomEditor( Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true)); }
再次访问:
值得注意的是:若是咱们使用的是Oracle插入时间的话,那么咱们在SQL语句就要写TimeStrap时间戳插入进去,不然就行不通!
咱们通常作开发的时候,常常编辑完数据就返回到显示列表中。咱们在Struts2是使用配置文件进行重定向或转发的:
而咱们的SpringMVC就很是简单了,只要在跳转前写上关键字就好了!
public String hello(Model model, User user) throws Exception { System.out.println(user.getUsername() + "的出生日期是:" + user.getDate()); model.addAttribute("message", user.getDate()); return "redirect:/index.jsp"; }
以此类推,若是是想要再次请求的话,那么咱们只要写上对应的请求路径就好了!
@RequestMapping(value = "/hello.action") public String hello(Model model, User user) throws Exception { return "redirect:/bye.action"; } @RequestMapping("/bye.action") public String bye() throws Exception { System.out.println("我进来了bye方法"); return "/index.jsp"; }
回顾一下Struts2返回JSON文本是怎么操做的:
那么咱们在SpringMVC又怎么操做呢???
导入两个JSON开发包
在要返回JSON的业务方法上给上注解:
@RequestMapping(value = "/hello.action") public @ResponseBody User hello() throws Exception { User user = new User("1", "zhongfucheng"); return user; }
配置JSON适配器
<!-- 1)导入jackson-core-asl-1.9.11.jar和jackson-mapper-asl-1.9.11.jar 2)在业务方法的返回值和权限之间使用@ResponseBody注解表示返回值对象须要转成JSON文本 3)在spring.xml配置文件中编写以下代码: --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> </list> </property> </bean>
测试的JSP
<input type="button" value="Emp转JSON"/><p> <input type="button" value="List<Emp>转JSON"/><p> <input type="button" value="Map<String,Object>转JSON"/><p> <!-- Map<String,Object>转JSON --> <script type="text/javascript"> $(":button:first").click(function(){ var url = "${pageContext.request.contextPath}/hello.action"; var sendData = null; $.post(url,sendData,function(backData,textStaut,ajax){ alert(ajax.responseText); }); }); </script>
测试:
Map测试:
@RequestMapping(value = "/hello.action") public @ResponseBody Map hello() throws Exception { Map map = new HashMap(); User user = new User("1", "zhongfucheng"); User user2 = new User("12", "zhongfucheng2"); map.put("total", user); map.put("rows", user2); return map; }
更新------------------------------------------------------------------
若是传递进来的数据就是JSON格式的话,咱们咱们须要使用到另一个注解@RequestBody
,将请求的json数据转成java对象
若是文章有错的地方欢迎指正,你们互相交流。 习惯在微信看技术文章,想要获取更多的Java资源的同窗,能够关注微信公众号:Java3y