SpringMVC中如何编写一个Controller呢?
下文笔者讲述SpringMVC中编写Controller的方法分享,如下所示:
Controller的作用
Controller的功能: 负责接收参数 调用相关业务层 封装数据 及路由到jsp页面 然后jsp页面上使用各种标签(jstl/el) 或手写java(<%=%>)将后台的数据展现出来那么如何编写一个Controller呢?下文笔者将通过具体的步骤,进行相关说明,如下所示
1.编写类,加上@Controller注解
功能:
让springmvc的dispatcherServlet知道
此类是一个Controller,可被dispatcherServlet的上下文所管理
2.在类上使用@RequestMapping注解
如:@RequestMapping("/getTest")
功能:
使/getTest/** 下的所有路径都会被此Controller所拦截
3.在方法上使用 @RequestMapping
如:@RequestMapping(value = "test.action", method = RequestMethod.POST)
功能:
使该方法负责处理/getTest/test.action 这个url,并且使用post方法方法传递过来的请求
4.在方法的参数前绑定@RequestParam/@PathVariable/@Param注解
功能:
负责把请求传入的参数,绑定到方法中的参数上,使方法中的参数值为请求传入的参数值
如 url /getTest/test.action?username="maomao"&password="pwd123"
例:
示例代码
@Controller
@RequestMapping("/getTest")
public class UserController {
@Autowired
private IUserService iUserService;
@RequestMapping(value = "test.action", method = RequestMethod.POST)
自动序列化成json
@ResponseBody
public ServerResponse<User> login(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session) {
ServerResponse<User> response = iUserService.login(username, password);
if (response.isSuccess()) {
session.setAttribute(Const.CURRENT_USER, response.getData());
}
return response;
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


