专业建站公司费用,免费推广方式,怎么做下载网站,自动化产品的网站建设目标#xff1a; 1. 熟悉使用SpringMVC中的常用注解 目录 前言
1. Controller
2. RestController
3. RequestMapping
4. RequestParam
5. PathVariable
6. SessionAttributes
7. CookieValue 前言
SpringMVC是一款用于构建基于Java的Web应用程序的框架#xff0c;它通… 目标 1. 熟悉使用SpringMVC中的常用注解 目录 前言
1. Controller
2. RestController
3. RequestMapping
4. RequestParam
5. PathVariable
6. SessionAttributes
7. CookieValue 前言
SpringMVC是一款用于构建基于Java的Web应用程序的框架它通过注解的方式简化了Web应用的开发。在本文中我们将总结一些SpringMVC中常用的注解及其用法以便开发者更好地理解和使用这些注解 1. Controller
在方法中直接返回对象时Spring MVC 会将其作为模型数据传递给视图解析器然后解析为具体的视图。
Controller
public class MyController {RequestMapping(/hello)public String hello() {return hello.html;}
}
当在类注解中加上 ResponseBody 时返回的为数据而不是页面
Controller
public class MyController {ResponseBody RequestMapping(/hello)public String hello() {return hello;}
}
第一段代码返回 html 页面(html, css, js等都能返回)
第二个返回 hello 这个字符串 2. RestController
其方法的返回值会被直接写入 HTTP 响应体中而不是被视图解析器解析为视图。通常返回的是 JSON 或 XML 数据。
RestController
public class MyRestController {RequestMapping(/api/data)public MapString, String getData() {MapString, String data new HashMap();data.put(key, value);return data;}
}我们可以将 RestControll 是由Controller ResponseBody组成的所以是直接返回数据而不是页面 3. RequestMapping
RequestMapping 注解用于映射请求路径和Controller方法指定请求的URL路径。
Controller
RequestMapping(/myapp)
public class MyController {RequestMapping(/hello)public String hello() {return helloPage;}
}例如
如果你想要访问hello方法的时候你就可以这样访问127.0.0.1:8080/myapp/hello 4. RequestParam
RequestParam 注解用于将请求参数绑定到方法参数上。
Controller
public class MyController {RequestMapping(/greet)public String greet(RequestParam(name) String name) {// Method logic using name parameterreturn greetPage;}
}注意
这里RequestParam里面的参数应和前端传入的相同如果想要自行修改的话括号里这一样写(value 你想要改的, required false)
Controller
public class MyController {RequestMapping(/greet)public String greet(RequestParam(value name2, required false) String name) {// Method logic using name parameterreturn greetPage;}
}5. PathVariable
PathVariable 注解用于从URI中提取模板变量的值。
Controller
RequestMapping(/users)
public class UserController {RequestMapping(/{userId})public String getUser(PathVariable(userId) int userId) {// Method logic using userIdreturn userPage;}
}6. SessionAttributes
SessionAttributes 注解用于指定哪些模型属性需要存储在会话中。
Controller
SessionAttributes(user)
public class UserController {RequestMapping(/login)public String login(ModelAttribute(user) User user) {// Method logic for user loginreturn dashboard;}
}去掉最后一个s是得到 Session
RequestMapping(/getSession)
public String getSession(SessionAttribute(value lpy, required false) String lpy) {return 登录账户 lpy;
} 7. CookieValue
CookieValue 用于获取到浏览器中的cooike
RequestMapping(/getCookie)
public String getCookie(CookieValue(lpy) String lpy) {return lpy: lpy;
}