springmvc的addurlpatterns非匹配
时间: 2023-07-12 11:32:37 浏览: 47
`addurlpatterns`不是Spring MVC框架中的函数,而是Django Web框架中的函数。在Spring MVC中,URL与控制器的映射是通过`@RequestMapping`注解来实现的,而非使用`addurlpatterns`函数。
在Spring MVC中,我们可以使用`@RequestMapping`注解来定义URL与控制器方法之间的映射关系。例如:
```
@Controller
@RequestMapping("/users")
public class UserController {
@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
public String getUser(@PathVariable String userId, Model model) {
User user = userRepository.findById(userId);
model.addAttribute("user", user);
return "user";
}
@RequestMapping(value = "/new", method = RequestMethod.GET)
public String newUser(Model model) {
model.addAttribute("user", new User());
return "userForm";
}
@RequestMapping(value = "/new", method = RequestMethod.POST)
public String createUser(@ModelAttribute User user) {
userRepository.save(user);
return "redirect:/users/" + user.getId();
}
}
```
在上述代码中,`@RequestMapping`注解指定了`/users`前缀,即所有的请求都以`/users`开头,而`value="/{userId}"`则表示该方法处理`/users/{userId}`的请求。同时,`@RequestMapping`注解还可以指定HTTP请求方法,例如`method = RequestMethod.GET`表示该方法只处理GET请求。
需要注意的是,Spring MVC中并没有内置的非匹配功能。如果需要在URL配置中排除某些URL,可以通过在控制器方法中进行判断来实现。例如:
```
@Controller
public class UserController {
@RequestMapping(value = "/admin/**", method = RequestMethod.GET)
public String adminPage(HttpServletRequest request) {
String uri = request.getRequestURI();
if (uri.startsWith("/admin/")) {
return "admin";
} else {
return "pageNotFound";
}
}
}
```
在上述代码中,我们使用了`HttpServletRequest`对象来获取当前请求的URI,然后判断其是否以`/admin/`开头,如果是,则返回`admin`页面,否则返回`pageNotFound`页面。这样就可以实现类似于Django中的非匹配功能。
相关推荐
![xmind](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)