SpringMVC 常用注解及页面跳转方式(面试)
1. SpringMVC常用注解
-
@Controller:标识一个类是Spring MVC的控制器, 返回视图名(需要视图解析器), 即返回一个HTML页面
-
@RequestMapping:映射URL到控制器方法, 对HTTP请求进行处理
-
@RequestBody: 将请求体转换为Java对象, 也就是用java对象去接收请求参数
-
@GetMapping/@PostMapping:特定HTTP方法的@RequestMapping简写/restful风格
-
@RequestParam:绑定请求参数到方法参数
-
@PathVariable:获取URL路径中的变量
-
@ModelAttribute:绑定请求参数到命令对象
-
@ResponseBody:将方法返回值直接写入HTTP响应体
-
@RestController:组合@Controller和@ResponseBody, 直接返回JSON数据, 一般在使用restful风格的时候使用
-
@SessionAttributes:声明会话级模型属性
-
@Valid:触发对命令对象的验证
2. 页面跳转方式
1. 返回字符串视图名
@Controller
public class MyController {@RequestMapping("/hello")public String hello() {return "hello"; // 返回视图名,对应/WEB-INF/views/hello.jsp}
}
2. 重定向(Redirect)
@Controller
public class MyController {@RequestMapping("/redirect")public String redirect() {return "redirect:/newUrl"; // 重定向到/newUrl}
}
3. 请求转发(Forward)
@Controller
public class MyController {@RequestMapping("/forward")public String forward() {return "forward:/newUrl"; // 转发到/newUrl}
}
4. 使用视图解析器(ViewResolver)
首先在已有WebMvc配置类的基础上, 创建一个WebConfig配置类, 继承WebMvc配置类, 并写一个方法, 返回类型为ViewResolver(视图解析器), 然后创建InternalResourceViewResolver对象, 并用这个对象.setPrefix("/WEB-INF/页面地址") 例如我的页面存储在/WEB-INF/views下, 再使用对象.setSuffis(".jsp")
配置视图解析器后,可以自动添加前缀后缀
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {@Beanpublic ViewResolver viewResolver() {InternalResourceViewResolver resolver = new InternalResourceViewResolver();resolver.setPrefix("/WEB-INF/views/");resolver.setSuffix(".jsp");return resolver;}
}
这种方式一般比较少用, 页面的跳转一般都是在前端执行的, 后端只需要对数据进行处理即可
5. 使用HttpServletResponse
方法直接返回void, 并用response.sendRedirect()
@Controller
public class MyController {@RequestMapping("/direct")public void direct(HttpServletResponse response) throws IOException {response.sendRedirect("http://localhost:8080/index");}
}
-
请求映射
-
当用户访问/direct
t
路径时(如:http://localhost:8080/index/direct),Spring会调direct()方法。
-
-
参数注入
-
Spring自动注入
HttpServletResponse
对象,用于直接操作HTTP响应。
-
-
重定向操作
-
调用response.sendRedirect("http://localhost:8080/index");
-
服务端返回 302状态码(临时重定向)
-
响应头中包含Location:http://localhost:8080/index
-
浏览器接收到响应后,自动跳转到指定的URL。
-
-
-
返回类型为void
-
方法返回
void
,表示完全由开发者手动控制响应内容(不依赖Spring的视图解析器)。
-