首先看看非注解的项目结构
[img]http://dl2.iteye.com/upload/attachment/0093/5380/60ef9462-e498-3385-a8ca-4344c3bb073a.jpg[/img]
在web.xml文件 配置springmvc 转发调度servlet 和 Date 类型参数的自动转型
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> springmvc org.springframework.web.servlet.DispatcherServlet springmvc *.do index.jsp
编写 spring 配置文件 配置 映射处理器 和 控制器 或者 拦截器
xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"> testController
然后编写 springmvc的控制器
package cn.sh.springmvc; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class TestController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { System.out.println("hello springmvc"); return new ModelAndView("homepage/index"); } }
http://localhost:8080/springmvc-1/hello.do 就可以访问了
采用注解类配置springmvc
[img]http://dl2.iteye.com/upload/attachment/0093/5390/c039b5c3-dbd8-3a9d-82f6-aa9cd1885cc8.jpg[/img]
在web.xml中配置spring的中央控制器
同时也可以指定初始化参数 设定 spring配置文件的路径
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> springmvc org.springframework.web.servlet.DispatcherServlet contextConfigLoaction classpath:springmvc.xml springmvc *.do index.jsp
编写 springmvc-servlet.xml文件
xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
编写控制器(类似struts里面的action)
下面有
传统的请求
有异步请求
文件上传 (注意添加jar和配置 文件上传解析器)
重定向请求
package cn.sh.springmvc; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.text.ParseException; import java.text.SimpleDateFormat; 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 org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.servlet.ModelAndView; import cn.sh.springmvc.model.Person; import cn.sh.springmvc.model.User; @Controller //用来标注但欠累是springmvc的控制层类 @RequestMapping("/homepage") //类是 struts2中的namespace public class TestController{ @RequestMapping("/hello.do") //用来访问控制方法的注解 public String hello(){ System.out.println("注解成功"); return "homepage/index"; } //参数的传递 /** * 方式一:HttpServletRequest * @param request * @return */ @RequestMapping("/toPesron.do") public String toPerson(HttpServletRequest request){ String result=request.getParameter("name"); System.out.println(result); return "homepage/index"; } /** * 方式二:将要传递的参数定义在方法中 而且 会自动转类型 * @param name * @param age * @return */ @RequestMapping("/toPesron1.do") public String toPerson1(String name,Integer age,Date birthday){ //定义 参数名也可以了 System.out.println(name); System.out.println(age); System.out.println(birthday); return "homepage/index"; } /** * 传递参数的 名字必须要与实体类的属性set方法后面的字符串匹配才能接受参数,首字母大小写不区分 * 请求中传递的参数只要是能和参数列表里面的变量名或者实体里面的set后面字符串匹配的上就能接受到 * @param person * @return */ @RequestMapping("/toPesron2.do") public String toPerson2(Person person,User user){ //定义 参数名也可以了 System.out.println(person); System.out.println(user); return "homepage/index"; } /** * 数组结构 * @param name * @return */ @RequestMapping("/toPerson3.do") public String upload(String[] name){ //定义 参数名也可以了 System.out.println(Arrays.toString(name)); return "homepage/index"; } /** * 将数据传递到 jsp页面去 * 不建议使用 * @throws ParseException */ @RequestMapping("/toPerson4.do") public ModelAndView toPerson4() throws ParseException{ Person person=new Person(); person.setName("james"); person.setAge(28); person.setAddress("maiami"); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); Date birthday=sdf.parse("1985-01-22"); person.setBirthday(birthday); Map map=new HashMap(); map.put("p",person); return new ModelAndView("index",map); } /** * 不建议使用 * @param map * @return * @throws ParseException */ @RequestMapping("/toPerson5.do") public String toPerson5(Map map) throws ParseException{ Person person=new Person(); person.setName("james"); person.setAge(28); person.setAddress("maiami"); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); Date birthday=sdf.parse("1985-01-22"); person.setBirthday(birthday); map.put("p",person); return "index"; } /** * 建议使用 * @param model * @return * @throws ParseException */ @RequestMapping("/toPerson6.do") public String toPerson6(Model model) throws ParseException{ Person person=new Person(); person.setName("james"); person.setAge(28); person.setAddress("maiami"); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); Date birthday=sdf.parse("1985-01-22"); person.setBirthday(birthday); model.addAttribute("p", person); return "index"; } /** * 不建议使用 * @param name * @param response * @throws ParseException */ @RequestMapping("/ajax.do") public void ajax(String name,HttpServletResponse response) throws ParseException{ String result="hello"+name; try { response.getWriter().write(result); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 建议使用 * @param name * @param out * @throws ParseException */ @RequestMapping("/ajax1.do") public void ajax1(String name,PrintWriter out) throws ParseException{ String result="hello"+name; try { out.print(result); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @RequestMapping("/toajax.do") public String toajax() throws ParseException{ return "ajax"; } @RequestMapping("/toFrom.do") public String toFrom() throws ParseException{ return "form"; } @RequestMapping(value="/toPerson7.do",method=RequestMethod.POST) public String toPerson7(Person person){ //定义 参数名也可以了 System.out.println(person); return "homepage/index"; } @RequestMapping(value="/toPerson8.do",method=RequestMethod.POST) public String toPerson8(Person person,HttpServletRequest request) throws FileNotFoundException{ //定义 参数名也可以了 System.out.println(person); MultipartHttpServletRequest rm=(MultipartHttpServletRequest)request; CommonsMultipartFile cfile=(CommonsMultipartFile)rm.getFile("image");// input的名称 byte[] bfile=cfile.getBytes(); String fileName=""; SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmssSSS"); fileName=format.format(new Date()); fileName+=(int)(Math.random()*1000); //3位随机数 //文件全名称 String origFileName=cfile.getOriginalFilename(); //文件后缀 String suffix=origFileName.substring(origFileName.lastIndexOf(".")); //项目的部署路径 String path=request.getSession().getServletContext().getRealPath("/"); System.out.println(path); System.out.println(request.getServletPath()); OutputStream out=new FileOutputStream(new File(path+"/upload/"+fileName+suffix)); try { out.write(bfile); out.flush(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "homepage/index"; } @RequestMapping("/redtoFrom.do") public String redirectToFrom() throws ParseException{ return "redirect:toFrom.do"; //可以在前面加上 namespace; } @RequestMapping("/redtoFrom1.do") public String redirectToFrom1() throws ParseException{ // "/"表示从根目录开始找 return "redirect:/test/toFrom.do"; //可以在前面加上 namespace; } /** * 注册时间类型的属性编辑器 * @param binder */ @InitBinder public void initBinder(ServletRequestDataBinder binder){ //注意 2012-12-02 和 2012-22-12(将变成 2013-10-12 做进制转换) binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true)); } }
多个控制器的相互引用
package cn.sh.springmvc; import java.text.ParseException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller //用来标注但欠累是springmvc的控制层类 @RequestMapping("/test") //类是 struts2中的namespace public class TestController1{ @RequestMapping("/toFrom.do") public String toFrom() throws ParseException{ return "form"; } }
自定义拦截器
package cn.sh.springmvc.interceptor; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class MyInterceptor implements HandlerInterceptor { /** * 执行时间:视图解析完毕 * 主要做一些监控的处理 比如 :异常 类是 try catch 后面的 finally */ public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception ex) throws Exception { System.out.println("afterCompletion"); ex.printStackTrace(); } /** * 执行时机:control 执行完, 视图解析没有把页面解析成页面 * 可以对视图做统一修改 主要提现在model上面(可以统一为 某个视图 添加头和尾 ) */ public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView mv) throws Exception { System.out.println("postHandle...."); Map map=mv.getModel(); map.put("test", "append something"); } /**前置拦截 * 执行时机:在control之前执行 * true:拦截通过 表示可以访问control * false:不可以访问control * Object: 访问的control 的类的对象 * 可以做权限 校验和控制 */ public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { System.out.println("preHandle...."); return true; } }
两个参数实体类
package cn.sh.springmvc.model; import java.util.Date; public class User { private String name; private Integer age; private String address; private Date birthday; //get set .. @Override public String toString() { return this.name+"/"+this.age+"/"+this.address+"/"+this.birthday; } } package cn.sh.springmvc.model; import java.util.Date; public class Person { private String name; private Integer age; private String address; private Date birthday; //get set... @Override public String toString() { return this.name+"/"+this.age+"/"+this.address+"/"+this.birthday; } }
几个jsp
form.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>