前台获取URL中的参数

URL参数解析函数

name为你想要获取参数的参数名

function getInfoString(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null)
                return unescape(r[2]);
            return null;
        }
在Spring Mvc项目里,前台向后台传递参数是常见操作,需要掌握常用的参数传递方式和注解使用。在URL中动态传入参数,有以下几种方法: ### 通过路径变量 在Spring Mvc里,可使用`@PathVariable`注解获取URL中的路径变量。示例代码如下: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @GetMapping("/users/{id}") public String getUser(@PathVariable("id") int userId) { return "User ID: " + userId; } } ``` 这里,`{id}`就是路径变量,在请求时会动态传入,例如`/users/123`,就能获取到`id`为`123`。 ### 通过查询参数 使用`@RequestParam`注解可获取URL中的查询参数。示例代码如下: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @GetMapping("/search") public String search(@RequestParam("keyword") String keyword) { return "Search keyword: " + keyword; } } ``` 在请求时,可通过`/search?keyword=java`这样的URL动态传入参数。 ### 处理中文参数URL传递中文参数时,由于ISO - 8859 - 1是Java中网络传输使用的标准字符集,使用`request.getParameter("message")`得到的是ISO - 8859 - 1字符集,所以要进行转换,通常转换成UTF - 8形式 [^2]。示例代码如下: ```java import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; public class ChineseParamExample { public void handleRequest(HttpServletRequest request) throws UnsupportedEncodingException { String message = request.getParameter("message"); message = new String(message.getBytes("ISO-8859-1"), "UTF-8"); } } ``` ### 传递多个参数 若要在URL中传递多个参数,可通过`&`符号连接。例如,要传递纬度和经度,可使用`/location?lat=28.534386&lon=77.472097`这样的URL [^3]。示例代码如下: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class LocationController { @GetMapping("/location") public String getLocation(@RequestParam("lat") double latitude, @RequestParam("lon") double longitude) { return "Latitude: " + latitude + ", Longitude: " + longitude; } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值