1、org.springframework.web.servlet.DispatcherServletinit-paramparam-namecontextConfigLocationparam-valueclasspath:springmvc-servlet.xml/init-param- 1 -/servletservlet-mappingurl-pattern/servlet-mapping3.在src下添加springmvc-servlet.xml配置文件161718192021222324252627?xml version=1.0 encoding=UTF-8beans xmlns=h
2、ttp:/www.springframework.org/schema/beansxmlns:xsi=/www.w3.org/2001/XMLSchema-instancecontext=/www.springframework.org/schema/contextmvc=/www.springframework.org/schema/mvcxsi:schemaLocation=/www.springframework.org/schema/beans http:/www.springframework.org/schema/beans/spring-beans.xsd/www.springf
3、ramework.org/schema/context http:/www.springframework.org/schema/context/spring-context-4.1.xsd/www.springframework.org/schema/mvc http:/www.springframework.org/schema/mvc/spring-mvc-4.1.xsd - scan the package and the sub package -context:component-scan base-package=test.SpringMVC/- dont handle the
4、static resource -mvc:default-servlet-handler /- if you use annotation you must configure following setting -annotation-driven /- configure the InternalResourceViewResolver -bean class=org.springframework.web.servlet.view.InternalResourceViewResolverid=internalResourceViewResolver- 前缀 -property name=
5、prefix value=/WEB-INF/jsp/ /- 后缀 -suffix.jsp/bean/beans4.在WEB-INF文件夹下创建名为jsp的文件夹,用来存放jsp视图。创建一个hello.jsp,在body中添加“Hello World”。5.建立包及Controller,如下所示6.编写Controller代码ControllerRequestMapping(/mvc)public class mvcController /hellopublic String hello()return hello;7.启动服务器,键入/localhost:8080/项目名/mvc/hello
6、二、配置解析1.DispatcherservletDispatcherServlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,Servlet拦截匹配规则要自已定义,把拦截下来的请求,依据相应的规则分发到目标Controller来处理,是配置spring MVC的第一步。2.InternalResourceViewResolver视图名称解析器3.以上出现的注解Controller负责注册一个bean 到spring 上下文中RequestMapping 注解为控制器指定可以处理哪些 URL 请求三、SpringMVC常用注解Controller负责注册一个bean 到spri
7、ng 上下文中RequestMapping注解为控制器指定可以处理哪些 URL 请求RequestBody该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上,再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上ResponseBody该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区ModelAttribute在方法定义上使用 Mod
8、elAttribute 注解:Spring MVC 在调用目标处理方法前,会先逐个调用在方法级上标注了ModelAttribute 的方法在方法的入参前使用 ModelAttribute 注解:可以从隐含对象中获取隐含的模型数据中获取对象,再将请求参数 绑定到对象中,再传入入参将方法入参对象添加到模型中RequestParam在处理方法入参处使用 RequestParam 可以把请求参 数传递给请求方法PathVariable绑定 URL 占位符到入参ExceptionHandler注解到方法上,出现异常时会执行该方法ControllerAdvice使一个Contoller成为全局的异常处理类
9、,类中用ExceptionHandler方法注解的方法可以处理所有Controller发生的异常四、自动匹配参数/match automatically/personpublic String toPerson(String name,double age)System.out.println(name+ +age);五、自动装箱1.编写一个Person实体类package test.SpringMVC.model;public class Person public String getName() return name;public void setName(String name) t
10、his.name = name;public int getAge() return age;public void setAge(int age) this.age = age;private String name;private int age;2.在Controller里编写方法/boxing automatically/person1public String toPerson(Person p)System.out.println(p.getName()+p.getAge();六、使用InitBinder来处理Date类型的参数/the parameter was converte
11、d in initBinder/datepublic String date(Date date)System.out.println(date);/At the time of initialization,convert the type String to type dateInitBinderpublic void initBinder(ServletRequestDataBinder binder)binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(yyyy-MM-dd),
12、true);七、向前台传递参数/pass the parameters to front-end/showpublic String showPerson(Map map)Person p =new Person();map.put(p, p);p.setAge(20);p.setName(jayjay);show前台可在Request域中取到八、使用Ajax调用/pass the parameters to front-end using ajax/getPersonpublic void getPerson(String name,PrintWriter pw)pw.write(hello
13、,+name);/namepublic String sayHello()name前台用下面的Jquery代码调用$(function()$(#btn).click(function()$.post(mvc/getPerson,name:#name).val(),function(data)alert(data););九、在Controller中使用redirect方式处理请求/redirect /redirectpublic String redirect()redirect:十、文件上传1.需要导入两个jar包2.在SpringMVC配置文件中加入- upload settings -be
14、an id=multipartResolverclass=mons.CommonsMultipartResolvermaxUploadSize102400000/property3.方法代码RequestMapping(value=/upload,method=RequestMethod.POST)public String upload(HttpServletRequest req) throws ExceptionMultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;MultipartFile file =
15、mreq.getFile(fileString fileName = file.getOriginalFilename();SimpleDateFormat sdf = new SimpleDateFormat(yyyyMMddHHmmssFileOutputStream fos = new FileOutputStream(req.getSession().getServletContext().getRealPath(/)+upload/+sdf.format(new Date()+fileName.substring(fileName.lastIndexOf(.);fos.write(f
16、ile.getBytes();fos.flush();fos.close();4.前台form表单form action=mvc/upload method=post enctype=multipart/form-datainput type= name=brsubmit/form十一、使用RequestParam注解指定参数的name/testpublic class mvcController1 /parampublic String testRequestParam(RequestParam(value=id) Integer id,RequestParam(value=)String
17、name)System.out.println(id+十二、RESTFul风格的SringMVC1.RestController28/restpublic class RestController /user/id,method=RequestMethod.GET)public String get(PathVariable() Integer id)System.out.println(get+id);public String post(PathVariable(,method=RequestMethod.PUT)public String put(PathVariable(put,met
18、hod=RequestMethod.DELETE)public String delete(PathVariable(delete2.form表单发送put和delete请求在web.xml中配置- configure the HiddenHttpMethodFilter,convert the post method to put or delete -filterfilter-nameHiddenHttpMethodFilterfilter-classorg.springframework.web.filter.HiddenHttpMethodFilter/filterfilter-mapping/*在前台可以用以下代码产生请求rest/user/1hidden_methodPUTDELETE十三、返回json格式的字符串1.导入以下jar包2.方法代码/jsonpublic class jsonController ResponseBodyReque
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1