SpringMVC细节(下)

SpringMVC细节

@RequestMapping的使用
基本使用
通过注解方式实现路径到处理器方法的映射。

可以用在类或方法上。

用在方法上表示将该方法变为一个处理器,且和指定路径做映射。

用在类上则配置的路径会作为这个类中所有处理器的路径的父路径使用。

@RequestMapping("/test01.action")

public ModelAndView test01() {

ModelAndView mav = new ModelAndView();

mav.addObject(“attr1”, “hello anno~”);

mav.addObject(“attr2”, “hello mvc~”);

mav.setViewName(“first”);

return mav;

}

注解属性
String [] value() default {};
指定要将当前处理器绑定到哪个访问路径上。

可以配置多个路径。

路径中也可以使用*号作为通配符匹配部分路径。

@RequestMapping({"/test02.action","/test002.action","/test002*.action"})

public ModelAndView test02() {

ModelAndView mav = new ModelAndView();

mav.addObject(“attr1”, “hello anno~”);

mav.addObject(“attr2”, “hello mvc~”);

mav.setViewName(“first”);

return mav;

}

RequestMethod[] method() default {}
指定当前处理器处理哪种提交方式提交的请求。

不指定则接收任意请求方式的请求

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

public ModelAndView test03() {

ModelAndView mav = new ModelAndView();

mav.addObject(“attr1”, “hello anno~”);

mav.addObject(“attr2”, “hello mvc~”);

mav.setViewName(“first”);

return mav;

}

String[] params() default {};
用来限定当前请求中必须包含指定名称的请求参数才会被当前处理器处理
通过params属性指定只处理请求参数符合指定要求的请求

格式1:只指定名称,要求必须具有该名称的请求参数

格式2:以"!名称"的方式指定必须不包含指定名称的请求参数

格式3:以"名称=值"或"名称!=值"的方式指定必须具有某个请求参数,且值必须等于或不等于给定值

@RequestMapping(value="/test04.action",params= {“name”,“gender=male”,"!age",“addr!=bj”})

public ModelAndView test04() {

ModelAndView mav = new ModelAndView();

mav.addObject(“attr1”, “hello anno~”);

mav.addObject(“attr2”, “hello mvc~”);

mav.setViewName(“first”);

return mav;

}

String[] headers() default {};
用来限定当前请求中必须包含指定名称的请求头才会被当前处理器处理
格式1:只指定名称,要求必须具有该名称的请求头

格式2:以"!名称"的方式指定必须不包含指定名称的请求头

格式3:以"名称=值"或"名称!=值"的方式指定必须具有某个请求头,且值必须等于或不等于给定值

@RequestMapping(value="/test05.action",headers= {“host=localhost”})

public ModelAndView test05() {

ModelAndView mav = new ModelAndView();

mav.addObject(“attr1”, “hello anno~”);

mav.addObject(“attr2”, “hello mvc~”);

mav.setViewName(“first”);

return mav;

}

可以接收的参数
web开发相关对象
在控制器方法中可以直接接收和web开发相关的对象

可以直接利用这些对象完成web开发相关功能

HttpServletRequest
代表请求的对象

/**

  • 使用Request

*/

@RequestMapping("/test01.action")

public void test01(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String uname = request.getParameter("uname");

request.setAttribute("k1","v1");

request.getRequestDispatcher("/index.jsp").forward(request,response);

}

HttpServletResponse
代表响应的对象

/**

  • 使用response

*/

@RequestMapping("/test02.action")

public void test02(HttpServletRequest request,HttpServletResponse response) throws IOException {

response.setHeader("xxx","xxx");

response.getWriter().write("xxx");

response.sendRedirect(request.getContextPath()+"/index.jsp");

}

HttpSession
代表会话的对象

/**

  • 使用Session

*/

@RequestMapping("/test03.action")

public void test03(HttpSession session){

session.setAttribute("k1","v1");

session.getAttribute("k1");

session.invalidate();

}

WebRequest
WebRequest对象相当于是request对象和session对象的合体

同时提供了request具有的方法和session具有的方法

/**

  • 使用WebRequest对象

*/

public void test04(WebRequest wreq){

wreq.getParameter("uname");

wreq.setAttribute("k1","v1",WebRequest.SCOPE_REQUEST);

wreq.getAttribute("k1",WebRequest.SCOPE_REQUEST);

wreq.getHeader("Host");

wreq.getContextPath();



wreq.setAttribute("k1","v1",WebRequest.SCOPE_SESSION);

wreq.getAttribute("k1",WebRequest.SCOPE_SESSION);

wreq.getAttribute("k1",WebRequest.SCOPE_SESSION);

wreq.getSessionId();

}

WEB开发相关的流对象
Reader
request.getReader()

Writer
response.getWriter()

InputStream
request.getInputStream()

OutputStream
response.getOutputStream()

@RequestMapping("/test05.action")

//public void test05(InputStream in, OutputStream out){

public void test05(Reader reader, Writer writer) throws IOException {

writer.write("abc");

}

数据模型对象
可以接收Model、Map、ModelMap类型的参数作为数据模型对象

这三个对象功能类似,api有所不同

@RequestMapping("/test04.action")

public String test04(ModelMap mm){

mm.put("k1","v1");

mm.addAttribute("k2","v2");

return "my03test04";

}

@RequestMapping("/test03.action")

public String test03(Map map){

map.put("k1","v1");

map.put("k2","v2");

return "my03test03";

}

@RequestMapping("/test02.action")

public String test02(Model model){

model.addAttribute("k1","v1");

model.addAttribute("k2","v2");

return "my03test02";

}

@RequestMapping("/test01.action")

public ModelAndView test01(){

ModelAndView mav = new ModelAndView();

mav.addObject("k1","v1");

mav.addObject("k2","v2");

mav.setViewName("my03test1");

return mav;

}

请求参数
直接接收请求参数
可以在Controller方法中直接接收请求参数相同名称的方法形参,可以直接得到请求参数的值

计算机生成了可选文字:(table) < t r 〉 < td 〉 用 户 名 < / td 〉 (tdxinput type K/tr) < t r 〉
(td)&H/td) (tdxinput type Ot r 丬 < t r 〉 (td) 年 *‘ltd) (tdxinput type K/tr)
< t r 〉 (form action: $fpageContext. request.contextPath )/heLL04.00 亡 讠 on ’ ’
met "text ’ ’ name: username ’ Xltd) na e: age ass or ’ ass or " / K/to
只 要 请 求 黲 敵 申 请 求 黲 敵 的 名 称 和 Control 方 法 的 黲 敵 名 称 相 一 致 , 就 可 以 自 动 得 到
值 , 即 使 类 型 不 一 致 , 也 会 自 动 类 型 转 换 "text ’ ’ na pe— ‘submit’ alue
()d colspan:“2"Xinput K/tr) K/table) @RequestMapping( " / he1104 . act . on” )
public String he1104(String sername,String password,int age,Mode1 model)f
System. out.println(username+’ ~ +password+ 、 "+age);
model . addAttribute ( "msg " he110 springMvc4,he110 闪 0r1d4 、 " ) ;
return " he110

请求参数中的名称和属性名不同的处理@RequestParam
可以通过@RequestParam来修饰Controller方法中用来接收请求参数的形参,有如下属性可以配置:

value
参数名字,即入参的请求参数名字,如value=“delId”表示请求的参数区中的名字为delId的参数的值将传入

required
是否必须,默认是true,表示请求中一定要有相应的参数,否则将报400错误码;

defaultValue
默认值,表示如果请求中没有同名参数时的默认值

value来指定 将那个请求参数赋值给当前形参

将required声明为true,则请求参数中必须有该属性,如果没有客户端将受到400

计算机生成了可选文字:HTTP Status 400 - Status report he Ton at / 7 . 0 . 53

defaultValue可以设定当前形参的默认值

请求参数中存在多个同名参数
如果请求参数中存在多个同名值

计算机生成了可选文字:< t r 〉 (td) 爱 F’ltd) “checkbox” “checkbox” “checkbox” “checkbox”
name: name: name: name: "Like "Like "Like "Like ’ value value ’ value ’ value
zq / 〉 足 琳 "Lq’ / 〉 篮 琳 "qq ’ / 〉 铅 琳 < t d 〉 (input (input (input (input Kltd)
K/tr) type type type type

此时直接获取,会得到一个用逗号分隔的字符串

计算机生成了可选文字:* 封 装 话 求 黲 到 bean @RequestMapping( " / he1106 . action " )
public String he1106(String like,Mode1 model)f System . 0 亡 . println(like) ;
model . addAttribute ( "msg " he110 springMvc4,he110 闪 0r1d4 、 " )
return " he110

也可以修改Controller方法的形参为数组类型,则直接接收到一个数组

计算机生成了可选文字:* 封 装 话 求 黲 到 bean @RequestMapping( " / he1106 . action " )
public String he1106(String 冂 like,Mode1 model)f
System . 0 亡 . println (Arrays . 亡 OS 亡 r 讠 g ( ke ) ) ;
model . addAttribute ( "msg " he110 springMvc4,he110 闪 0r1d4 、 " ) ;
return " he110

封装请求参数到bean
自动封装请求参数信息到bean
SpringMVC框架可以自动将请求参数封装到bean中

要求bean中必须提供属性的setXxx方法,且bean的属性名和请求参数中请求参数的名字必须一致,才可以自动设置。

计算机生成了可选文字:(table) < t r 〉 < td 〉 用 户 名 < / td 〉 (tdxinput type < t r 〉
(td)&H/td) (tdxinput type K/tr) < t r 〉 (td) 年 *'ltd) (tdxinput type K/tr)
< t r 〉
(form action: $fpageContext. request.contextPath } / heLL05 . 00 亡 讠 on ’
’ method: "text ’ ’ name: 7 〉 < / td 〉 username 胃 ass or 冒 " / 〉 < / td 〉
ass or ’ name: “text ’ ’ name: age 'submit” value ()d colspan:"2"xinput type
K/tr) K/table)

计算机生成了可选文字:public class U s e r { private String username;
private String password; private int age; public String getusername() {
return username; public void setUsername(String username) { this. username
username; public String getpassword() { return password;
public void setPassword(String password) { this . password password;
public int getAge ( ) { return age;

计算机生成了可选文字:* 快 速 获 得 话 求 黲 @RequestMapping( " / he1105 . action " )
public String he1105(Ur userModel model)f System . 0 亡 . println(user) ;
model . addAttribute ( "msg " he110 springMvc4,he110 闪 0r1d4 、 " ) ;
return " he110

处理复杂类型
如果自动封装的bean中存在复杂类型,只要该复杂类型的属性同样具有setXxx方法,则可以在请求参数中包含[bean中复杂类型].[属性]的方式为该复杂类型的参数复制,从而实现自动封装bean的过程中处理其中的复杂类型

计算机生成了可选文字:public class U s e r { private String username;
private String password; rivate int a e ; private Dog dog;
public Dog getDog ( ) { return dog; public void setDog(Dog dog) this.dog = dog,
public String getusername() return username; public void setUsername(String
username) public class Dog { private String name; private int age;
public String getName() { return name; public void setName(String name) {
this . name name; public int getAge return age; public void setAge ( int age) {
this . age age; Ve r r 1 e public String tostring() {
return " Dog Cname: ’ + name + age: + age + this. username < t r 〉
(td)äfi) 名 Kltd) (tdxinput type K/tr) < t r 〉 (td)ä*’/td) (tdxinput type K/tr)

  • 快 速 获 得 话 求 黲 username; "text ’ ’ "text ’ ’ name: name: dog. name ’ 7 K/tcb
    "dog . age @RequestMapping( " / he1105 . action " )
    public String he1105(User user,Mode1 model) System . 0 亡 . println(user) ;
    model . addAttribute ( "msg return " he110
    " he110 springMvc4,he110 闪 0r1d4 、 " ) ; age = 123 , dog—Dog Cname—wc, age:51 ]
    U S e r Cusername:aaa, password:123,

请求参数中的中文乱码
SpringMVC中获取中文请求参数存在乱码

计算机生成了可选文字:1508859一1张三utf一8111000100001010000101011111000100001010000101011
QC7QQQQ111000100001010000101011110011011001001110111010方案1:
re职est.setCharaCterEncading(j,utf一8,1100110110010011101110101100110110010011
10111010此方法必须用在获取任何请求参数之前此方法只对POST提交有效方案2:修改t。mcat的:erver.x记中的连接器配置
‘connec七。了艺:烹::::骂:翼二二翼百;默’’"’"}re"rectPort一8,。3”匣亘亚巫三巫到肠此方法只对GET提交有效l方案3:
手动编解码解决乱码b丫te[]data二str.getBytes(111508859一1,I)str二newstring(data,“utf一8”);
对GET和PosT都有效每个参数都要手动编解码处理太麻烦

对于GET提交乱码可以通过修改Tomcat连接器配置解决

此方案只对GET有效

计算机生成了可选文字:-Connector pr0t000 工 = " HT 了 p / 1 . 1 " connection 二 = " 20000 "
UR 工 "

对于POST提交乱码可以通过设置过滤器解决(本质上是设置了request.setCharacterEncoding(xxx))

此方案只对POST有效

计算机生成了可选文字:配 置 Spr1ngMVC 乱 码 解 决 过 滤 器 一 一 〉 (filter)
(filter-nam»characterEncodingFi1terK/fi1ter-narne)
(filter-clas»org . springframework . web . filter . CharacterEncodingFi1ter
(init—param) ‘param—name)encoding’/pararn—name) (param-valu»utf-8
4/param—value) K/init—param) K/filter) (filter-mappino
(filter-nam»characterEncodingFi1terK/fi1ter-narne)
Kurl-pattern)/*(/url-pattern) K/filter-mappino

当如上两个方法不适用时–如不允许修改tomcat服务器配置时–可以手动进行编解码解决乱码

这种方式对于GET和POST都有效,但每个请求参数都要处理,比较麻烦

**自定义类型数据
日期数据的处理
在SpringMVC中解析页面提交的请求参数时,无法自动获取封装日期到Data。

如果想要实现自动封装,必须手动注册适配器自己来指定转换方式。

计算机生成了可选文字:@工 nitBinder
public void 工 nitBinder(Serv1etRequestDataBinder binder)f
binder . registerCustomEditor ( Date . class
new CustomDateEditor(new SimpleDateFormat(“yyyy-MM-dd”), true

域属性
@RequestAttribute
用在控制器方法参数上

用来从Request域中获取指定名称的属性的属性值

计算机生成了可选文字:@RequestMaI)Ding ( /test02. action")
public void test02(@RequestAttribute(“k1”) String v) { System. 0 厶 printIn (v)
@RequestMapping ( /test01. action")
public String test01 (HttpServIetRequest request) {
request. setAttribute ( s: “kl” 0 : " VI 勹 ,
re turn forward: /my01/test02. action

@SessionAttrribute
用在控制器方法参数上

用来从Session域中获取指定名称的属性的属性值

计算机生成了可选文字:@RequbstMapping ( " /test02. action")
public void test02(@SessionAttribute(“k1”) String v) { System. 0 厶 printIn (v)
@RequestMapping ( /test01. action")
public String test01 (HttpSession session) {
session. setAttribute ( s: “kl” 0 : " VI 勹
re turn forward: /my02/test02. action

cookie值
@CookieValue
用在控制器方法参数上

用来从Cookie中获取指定名称的Cookie值

计算机生成了可选文字:@RequestMaI)I)1ng ( /test01. action")
public void test01 (@CookieVaIue (“JSESSIONID”) String v) {
System. 0 厶 printIn (v)

header值
@RequestHeader
用在控制器方法参数上

用来获取指定名称请求头的值

计算机生成了可选文字:@RenuestMapping ( /test01. action")
public void test01 (@RequestHeader (“User—Agent”) String v) {
System. 0 厶 printIn (v)

模型数据值
@ModelAttribute
使用在方法上
则被修饰的方法将会在当前类的任意控制器方法执行之前执行

该方法返回的返回值会自动存入model供后续使用

计算机生成了可选文字:@Mode1Attribute(“uname”)publicStringmaol(){System.outreturn’‘25
.println(“maol”);"’;}自动将uname二25存入model中

使用在控制器方法参数之前
则会从model中获取属性值赋值到被修饰的方法参数上

计算机生成了可选文字:@RequestMapping("/test02.action")
publicvoidtestOZ(@Mode1Attribute(“uname”)Stringuname){SVStem.OUt.D广intln(Un日me、:
.尸.、工日尸自动从model中获取uname对应的值赋值到当前方法参数上飞J

路径参数
RESTFul风格的请求:
普通get请求:

Url:localhost/XXXX/addUser.action?name=tom&age=18

RESTFul风格的请求:

Url:localhost/XXXX/addUser/tom/18.action

SpringMVC对RESTFul风格的请求的处理:
计算机生成了可选文字:* RESTFul 支 持 @RequestMapping("/he1101e username . action " )
public String he1101e ( Pat Vanla e S ring username @PathVariab1e int 引
System. out.println(username +" 、 "+age); model . addAttribute ( "msg
" he110 springMvc4,he110 闪 0r1d4 、 " ) ; return " he110

计算机生成了可选文字:C G) localhost.8080/Spring MVCDem002/hellolO/zs/19.action WelCOme!
hello springMvc4,hello World4— Sat Oct 20 15 : 54 : 58 CST 2018

请求体数据
@RequestBody注解用来获取请求体的内容,可以直接获取为字符串或将json自动解析为对象

获取请求体为字符串
/**

  • 接收json - @RequestBody直接读取实体内容为字符串

  • http://http://localhost/SpringMVCDay02_02_Details03/my05test03.jsp

*/

@RequestMapping("/test03.action")

public void test03(@RequestBody String str) {

System.out.println(str);

}

获取请求体为对象
/**

  • 读取json - @RequestBody直接读取json为对象

  • http://http://localhost/SpringMVCDay02_02_Details03/my05test04.jsp

*/

@RequestMapping("/test04.action")

public void test04(@RequestBody User user) {

System.out.println(user);

}

MultipartFile
实现文件上传接收数据

参考文件上传专题

Errors、BindingResult
实现数据校验的参数

参考数据校验专题

可以返回的数据
ModelAndView
以返回一个ModelAndView对象,在其中封装Model和View信息

计算机生成了可选文字:* 可 以 一 回 办 巭 - 湘 L 胃 n 冒 五 e 射
@RequestMapping( " /testøl . action" ) public ModelAndView testel( ) {
ModelAndView mav = new ModelAndView( ) ;
mav.addObject( attributeName: " kl " attributeValue:
mav.addObject( attributeName: " k2 " attributeValue:
mav . setViewName ( "myøltestøl " ) ;

**View
可以直接返回一个代表视图的View对象

字符串
普通字符串
返回的字符串将作为视图名称使用

计算机生成了可选文字:* 可 以 返 回 - 庐 筘 - 声 筘 * 返 回 庐 筘 会 为 图 名 愆 孵
@RequestMapping( " /testø2 . action" ) public String teste2(Mode1 model)f
model.addAttribute( s: " kl " 0 : “VI”);
model.addAttribute( s: " k2 " 0 : “v2”); retu rn “myø1testø2”

forward
可以通过返回forward:/xxxx.xxx格式的字符串表明要转发到指定地址

计算机生成了可选文字:* 可 以 返 回 - 庐 芹 筘 - forward: 义 . 筘 , 实 发
@RequestMapping( " /testø4 . action" ) public String teste4( ) {
retu rn "forward:/index.jsp

redirect
可以通过返回redirect:/xxxx.xxx格式的字符串表明要重定向到指定地址

通过这种方式实现请求重定向时不用在路径前写应用名,SpringMVC会自动拼接应用名

计算机生成了可选文字:* 可 以 返 回 - 庐 芹 筘 - redirect: 义 . 筘 , 实 重 定
@RequestMapping ( " /te stø6 . action " ) public String teste6( ) {
retu rn "redirect:/index.jsp

void
如果返回值类型是void,则springmvc会采用默认视图名来作为当前请求的视图名称来使用

所谓的默认视图名,就是当前访问的控制器方法访问路径去除后缀的结果

计算机生成了可选文字:/***可以返回时君袭一v。龙d*尹匆日1/test日7.act毛on一)厂砂81/test日7*/
@RequestMapping("/test07.action")publicvoidtesto7(){}

被@ResponseBody修饰的方法
被@ResponseBody修饰的方法直接将返回值加入响应体发送给浏览器

返回字符串数据
通过@ResponseBody将返回值直接写入响应

/**

  •     向客户端直接返回数据 - 字符串
    
  •     通过@ResponseBody将返回值直接写入响应
    
  •    其中可以通过@RequestMapping的produces属性控制输出时的类型编码
    
  •     http://localhost/SpringMVCDay02_02_Details3/my01/test03.action
    

*/

@ResponseBody

@RequestMapping(value="/test03.action",produces=“text/html;charset=utf-8”)

public String test03() {

return “abcd中国”;

}

返回json数据
通过配置@ResponseBody利用内置的jackson将对象处理为json返回

/**

  •     向客户端直接返回数据 - json
    
  •     http://localhost/SpringMVCDay02_02_Details3/my01/test05.action
    

*/

@ResponseBody

@RequestMapping(value="/test05.action",produces=“application/json;charset=utf-8”)

public User test05() throws Exception {

User user = new User(99,“张三”,Arrays.asList(“bj”,“sh”,“gz”));

return user;

}

其他
除以上之外返回的任何内容都会被存入模型中供后续使用

值为返回的数据,键为返回类型名首字母转小写

而返回的视图名为默认视图名,即等同于返回值为void的时的视图名

计算机生成了可选文字:* 可 以 返 回 髭 - 真 返 回 在 的 容 会 型 屮 髭 * 趸 回 意 , 回 类 型 名 庐 以 小 写
回 图 名 老 彩 以 图 名 - 等 . 丆 返 回 , 。 证 图 名 zs 99,new Stringt)f"bj" age:
@RequestMapping( " /test12 . action" ) public U s e r test12( ) {
new User( icy: 3 U S e r u S e r name: USer;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值