SpringMVC基础入门.docx

上传人:b****5 文档编号:3793531 上传时间:2022-11-25 格式:DOCX 页数:21 大小:247.91KB
下载 相关 举报
SpringMVC基础入门.docx_第1页
第1页 / 共21页
SpringMVC基础入门.docx_第2页
第2页 / 共21页
SpringMVC基础入门.docx_第3页
第3页 / 共21页
SpringMVC基础入门.docx_第4页
第4页 / 共21页
SpringMVC基础入门.docx_第5页
第5页 / 共21页
点击查看更多>>
下载资源
资源描述

SpringMVC基础入门.docx

《SpringMVC基础入门.docx》由会员分享,可在线阅读,更多相关《SpringMVC基础入门.docx(21页珍藏版)》请在冰豆网上搜索。

SpringMVC基础入门.docx

SpringMVC基础入门

一、SpringMVC基础入门,创建一个HelloWorld程序

1.首先,导入SpringMVC需要的jar包。

2.添加Web.xml配置文件中关于SpringMVC的配置

--configurethesettingofspringmvcDispatcherServletandconfigurethemapping-->

springmvc

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:

springmvc-servlet.xml

--1-->

springmvc

/

3.在src下添加springmvc-servlet.xml配置文件

xmlversion="1.0"encoding="UTF-8"?

>

//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/beanshttp:

//www.springframework.org/schema/beans/spring-beans.xsd

http:

//www.springframework.org/schema/contexthttp:

//www.springframework.org/schema/context/spring-context-4.1.xsd

http:

//www.springframework.org/schema/mvchttp:

//www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

--scanthepackageandthesubpackage-->

component-scanbase-package="test.SpringMVC"/>

--don'thandlethestaticresource-->

default-servlet-handler/>

--ifyouuseannotationyoumustconfigurefollowingsetting-->

annotation-driven/>

--configuretheInternalResourceViewResolver-->

id="internalResourceViewResolver">

--前缀-->

--后缀-->

4.在WEB-INF文件夹下创建名为jsp的文件夹,用来存放jsp视图。

创建一个hello.jsp,在body中添加“HelloWorld”。

5.建立包及Controller,如下所示

6.编写Controller代码

@Controller

@RequestMapping("/mvc")

publicclassmvcController{

@RequestMapping("/hello")

publicStringhello(){

return"hello";

}

}

7.启动服务器,键入 http:

//localhost:

8080/项目名/mvc/hello

二、配置解析

1.Dispatcherservlet

  DispatcherServlet是前置控制器,配置在web.xml文件中的。

拦截匹配的请求,Servlet拦截匹配规则要自已定义,把拦截下来的请求,依据相应的规则分发到目标Controller来处理,是配置springMVC的第一步。

2.InternalResourceViewResolver

  视图名称解析器

3.以上出现的注解

@Controller 负责注册一个bean到spring上下文中

@RequestMapping注解为控制器指定可以处理哪些URL请求

三、SpringMVC常用注解

@Controller

  负责注册一个bean到spring上下文中

@RequestMapping

  注解为控制器指定可以处理哪些URL请求

@RequestBody

  该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上 ,再把HttpMessageConverter返回的对象数据绑定到controller中方法的参数上

@ResponseBody

   该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区

@ModelAttribute    

  在方法定义上使用@ModelAttribute注解:

SpringMVC在调用目标处理方法前,会先逐个调用在方法级上标注了@ModelAttribute的方法

  在方法的入参前使用@ModelAttribute注解:

可以从隐含对象中获取隐含的模型数据中获取对象,再将请求参数–绑定到对象中,再传入入参将方法入参对象添加到模型中 

@RequestParam 

  在处理方法入参处使用@RequestParam可以把请求参数传递给请求方法

@PathVariable

  绑定URL占位符到入参

@ExceptionHandler

  注解到方法上,出现异常时会执行该方法

@ControllerAdvice

  使一个Contoller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常

四、自动匹配参数

//matchautomatically

@RequestMapping("/person")

publicStringtoPerson(Stringname,doubleage){

System.out.println(name+""+age);

return"hello";

}

五、自动装箱

1.编写一个Person实体类

packagetest.SpringMVC.model;

publicclassPerson{

publicStringgetName(){

returnname;

}

publicvoidsetName(Stringname){

this.name=name;

}

publicintgetAge(){

returnage;

}

publicvoidsetAge(intage){

this.age=age;

}

privateStringname;

privateintage;

}

2.在Controller里编写方法

//boxingautomatically

@RequestMapping("/person1")

publicStringtoPerson(Personp){

System.out.println(p.getName()+""+p.getAge());

return"hello";

}

六、使用InitBinder来处理Date类型的参数

//theparameterwasconvertedininitBinder

@RequestMapping("/date")

publicStringdate(Datedate){

System.out.println(date);

return"hello";

}

//Atthetimeofinitialization,convertthetype"String"totype"date"

@InitBinder

publicvoidinitBinder(ServletRequestDataBinderbinder){

binder.registerCustomEditor(Date.class,newCustomDateEditor(newSimpleDateFormat("yyyy-MM-dd"),

true));

}

七、向前台传递参数

//passtheparameterstofront-end

@RequestMapping("/show")

publicStringshowPerson(Mapmap){

Personp=newPerson();

map.put("p",p);

p.setAge(20);

p.setName("jayjay");

return"show";

}

前台可在Request域中取到"p"

八、使用Ajax调用

//passtheparameterstofront-endusingajax

@RequestMapping("/getPerson")

publicvoidgetPerson(Stringname,PrintWriterpw){

pw.write("hello,"+name);

}

@RequestMapping("/name")

publicStringsayHello(){

return"name";

}

前台用下面的Jquery代码调用

$(function(){

$("#btn").click(function(){

$.post("mvc/getPerson",{name:

$("#name").val()},function(data){

alert(data);

});

});

});

九、在Controller中使用redirect方式处理请求

//redirect

@RequestMapping("/redirect")

publicStringredirect(){

return"redirect:

hello";

}

十、文件上传

1.需要导入两个jar包

2.在SpringMVC配置文件中加入

--uploadsettings-->

3.方法代码

@RequestMapping(value="/upload",method=RequestMethod.POST)

publicStringupload(HttpServletRequestreq)throwsException{

MultipartHttpServletRequestmreq=(MultipartHttpServletRequest)req;

MultipartFilefile=mreq.getFile("file");

StringfileName=file.getOriginalFilename();

SimpleDateFormatsdf=newSimpleDateFormat("yyyyMMddHHmmss");

FileOutputStreamfos=newFileOutputStream(req.getSession().getServletContext().getRealPath("/")+

"upload/"+sdf.format(newDate())+fileName.substring(fileName.lastIndexOf('.')));

fos.write(file.getBytes());

fos.flush();

fos.close();

return"hello";

}

4.前台form表单


十一、使用@RequestParam注解指定参数的name

@Controller

@RequestMapping("/test")

publicclassmvcController1{

@RequestMapping(value="/param")

publicStringtestRequestParam(@RequestParam(value="id")Integerid,

@RequestParam(value="name")Stringname){

System.out.println(id+""+name);

return"/hello";

}

}

十二、RESTFul风格的SringMVC

1.RestController

@Controller

@RequestMapping("/rest")

publicclassRestController{

@RequestMapping(value="/user/{id}",method=RequestMethod.GET)

publicStringget(@PathVariable("id")Integerid){

System.out.println("get"+id);

return"/hello";

}

@RequestMapping(value="/user/{id}",method=RequestMethod.POST)

publicStringpost(@PathVariable("id")Integerid){

System.out.println("post"+id);

return"/hello";

}

@RequestMapping(value="/user/{id}",method=RequestMethod.PUT)

publicStringput(@PathVariable("id")Integerid){

System.out.println("put"+id);

return"/hello";

}

@RequestMapping(value="/user/{id}",method=RequestMethod.DELETE)

publicStringdelete(@PathVariable("id")Integerid){

System.out.println("delete"+id);

return"/hello";

}

}

2.form表单发送put和delete请求

在web.xml中配置

--configuretheHiddenHttpMethodFilter,convertthepostmethodtoputordelete-->

HiddenHttpMethodFilter

org.springframework.web.filter.HiddenHttpMethodFilter

HiddenHttpMethodFilter

/*

在前台可以用以下代码产生请求

十三、返回json格式的字符串

1.导入以下jar包

2.方法代码

@Controller

@RequestMapping("/json")

publicclassjsonController{

@ResponseBody

@RequestMapping("/user")

publicUserget(){

Useru=newUser();

u.setId

(1);

u.setName("jayjay");

u.setBirth(newDate());

returnu;

}

}

十四、异常的处理

1.处理局部异常(Controller内)

@ExceptionHandler

publicModelAndViewexceptionHandler(Exceptionex){

ModelAndViewmv=newModelAndView("error");

mv.addObject("exception",ex);

System.out.println("intestExceptionHandler");

returnmv;

}

@RequestMapping("/error")

publicStringerror(){

inti=5/0;

return"hello";

}

2.处理全局异常(所有Controller)

@ControllerAdvice

publicclasstestControllerAdvice{

@ExceptionHandler

publicModelAndViewexceptionHandler(Exceptionex){

ModelAndViewmv=newModelAndView("error");

mv.addObject("exception",ex);

System.out.println("intestControllerAdvice");

returnmv;

}

}

3.另一种处理全局异常的方法

在SpringMVC配置文件中配置

--configureSimpleMappingExceptionResolver-->

error

error是出错页面

十五、设置一个自定义拦截器

1.创建一个MyInterceptor类,并实现HandlerInterceptor接口

publicclassMyInterceptorimplementsHandlerInterceptor{

@Override

publicvoidafterCompletion(HttpServletRequestarg0,

HttpServletResponsearg1,Objectarg2,Exceptionarg3)

throwsException{

System.out.println("afterCompletion");

}

@Override

publicvoidpostHandle(HttpServletRequestarg0,HttpServletResponsearg1,

Objectarg2,ModelAndViewarg3)thro

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 小学教育 > 语文

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1