好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

基于SpringMVC中的路径参数和URL参数实例

1、springmvc中的路径参数就是指在路径中添加参数,用于实现伪静态是很好的。

2、路径参数实现方式(一个controller方法)

?

1

2

3

4

5

6

7

@requestmapping (value= "/page/{name}/{age}" ,method=requestmethod.get)

public string getname(modelmap map, @pathvariable ( "name" ) string name, @pathvariable ( "age" ) int age)

{

   map.addattribute( "name" ,name);

   map.addattribute( "age" ,age);

   return "name" ;

}

3、创建name.jsp文件

?

1

2

3

4

5

6

7

8

9

10

11

12

13

<% @page pageencoding= "utf-8" %>

<html>

<head>

   <meta charset= "utf-8" >

   <title>test</title>

</head>

<body>

<div>

   名字:${name}<br/>

   年龄:${age}

</div>

</body>

</html>

4、在浏览器请求这个controller

http://localhost:8080/page/xiaoming/18

需要注意的是,我这里使用的编辑器是idea旗舰版

5、在controller中接受请求参数的实现(controller)

?

1

2

3

4

5

6

7

@requestmapping (value= "/result" ,method=requestmethod.get)

public string resultparam(modelmap map, @requestparam string name, @requestparam int age)

{

   map.addattribute( "name" ,name);

   map.addattribute( "age" ,age);

   return "result" ;

}

6、创建result.jsp文件

?

1

2

3

4

5

6

7

8

9

10

11

<% @page pageencoding= "utf-8" >

<html>

<head>

   <meta charset= "utf-8" >

   <title>测试</title>

</head>

<body>

名字:${name}<br/>

年龄:${age}

</body>

</html>

6、在浏览器中请求这个controller

http://localhost:8080/result?name=xiaoming&age=20

补充:spring mvc 之可选路径参数

在spring mvc中,注解@pathvariable可以获得路径参数,但如果我想让路径参数可选呢?

?

1

2

3

4

@getmapping ({ "/get/{offset}/{count}" , "/get/{offset}" , "/get/{offset}" , "/get" })

public void getgoods( @pathvariable (required = false ) integer offset, @pathvariable (required = false ) integer count){

   system.out.println( "offset:" +offset+ "\ncount:" +count+ "\n" );

}

此时在这个例子中,offset和count都是可选的了,但是count存在时offset必须存在。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/lovelongjun/article/details/57416888

查看更多关于基于SpringMVC中的路径参数和URL参数实例的详细内容...

  阅读:26次