一、Controller和RestFul
第一步:配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring_mvc_servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springMvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- <filter> <filter-name>encode</filter-name> <filter-class>com.ssl.filter.EncodeFilter</filter-class> </filter> <filter-mapping> <filter-name>encode</filter-name> <url-pattern>/</url-pattern> </filter-mapping>--> <filter> <filter-name>encode</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encode</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
第二步:spring_mvc_servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--自动扫描包,让指定包下的注解生效,由IOC容器统一管理--> <context:component-scan base-package="com.ssl.controller"/> <!--让SpringMvc不处理静态资源。让.css,.js等不进视图解析器--> <mvc:default-servlet-handler/> <!--注解加载映射器、适配器,不用之前那么麻烦配置了--> <mvc:annotation-driven/> <!--以上的是定死的代码, 以下是配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!--不使用注解开发的适配器:/demo1,注意点是id需要配置/--> <bean id="/demo" class="com.ssl.controller.ControllerDemo1"/> </beans>
参考文档:https://blog.csdn.net/Edward_He_/article/details/122310741
Controller不使用注解:
不使用注解,极其不推荐使用,因为:
配置麻烦:<bean id="/demo" class="com.ssl.controller.ControllerDemo1"/>,并且需要 implements Controller
不够灵活,太费力气,浪费时间
访问:http://localhost:8080/springmvc_04_controller/demo
public class ControllerDemo1 implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("demo1","demo1:Controller会返回一个modelAndView"); modelAndView.setViewName("demo1"); return modelAndView; } }
@Controller
- 使用注解开发,@Controller注册进Spring容器,如果返回值是String,并且有具体的页面可以跳转,那么就会被视图解析器解析访问:http://localhost:8080/springmvc_04_controller/demo2
-
@Controller public class ControllerDemo2 { @RequestMapping("/demo2") public String test1(Model model) { model.addAttribute("demo2", "demo2"); return "demo2"; } }
@RequestMapping
- 可以在类和方法上配置url访问路径访问:http://localhost:8080/springmvc_04_controller/controller/demo3
-
@Controller @RequestMapping("/controller") public class ControllerDemo3 { @RequestMapping("/demo3") public String test1(Model model) { model.addAttribute("demo3", "demo3"); return "demo3"; } }
RestFul风格
- 优点:
- 最大的优势是安全,看不出源代码的参数和意义
- 实现地址复用,使得get和post访问url相同,框架会自动进行类型转换
- 高效:支持缓存
- 缺点:
- 不像原生的url见名知意,url理解不直观
- 实现方式:
- 1:url @GetMapping("/addRest/{a}/{b}") + 参数@PathVariable int a, @PathVariable int b
- 访问:http://localhost:8080/springmvc_04_controller/addRest/1/2
- 2:url @PostMapping("/addRest/{a}/{b}") + 参数不变@PathVariable int a, @PathVariable int b
- 使用Postman中的post访问:http://localhost:8080/springmvc_04_controller/addRest/1/2
-
@Controller public class RestFulController { /** * 原生的url:http://localhost:8080/springmvc_04/add?a=1&b=1 */ @RequestMapping("/add") public String getAdd1(int a, int b, Model model) { int result = a + b; model.addAttribute("add", "原生的url:结果为" + result); return "add"; } /** * RestFul方式一:method = get * RequestMapping("/addRest/{a}/{b}" method=requestMethod.GET) = @GetMapping() * http://localhost:8080/springmvc_04/addRest/1/1 */ @GetMapping("/addRest/{a}/{b}") public String getAdd2(@PathVariable int a, @PathVariable int b, Model model) { int result = a + b; model.addAttribute("add", "Rest的url:结果为" + result); return "addRest"; } /** * 复用相同的url * RestFul方式二:method=post,使用RestFul的话,请求的url和GET就一样了 */ @PostMapping("/addRest/{a}/{b}") public String getAdd3(@PathVariable int a, @PathVariable int b, Model model) { int result = a + b; model.addAttribute("add", "Rest的url:结果为" + result); return "addRest"; } }
-
重定向和转发
- 可以使用原生的request转发或者response重定向
- 推荐使用SpringMvc的
return “forward:xxx”/"redirect:xxx"
-
@Controller public class ModelTest1 { //原生的转发:返回值是void,没有经过视图解析器;原生的重定向同样如此,都不走视图解析器,直接重定向 @RequestMapping("/test1") public void test1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getSession().getId(); System.out.println(id); request.getRequestDispatcher("index.jsp").forward(request,response); } //SpringMvc转发:测试结果是不走视图解析器,url没变是转发 @RequestMapping("/test2") public String test2(Model model) { model.addAttribute("demo1","这是test2中的Spring转发"); return "forward:/WEB-INF/jsp/demo1.jsp"; } //SpringMvc重定向:测试结果是不走视图解析器 @RequestMapping("/test3") public String test3() { System.out.println("跳转回首页index.jsp"); return "redirect:index.jsp"; } }
接受请求参数和数据回显
- 前端提交的name和后端映射器接受的形参名一样,则直接接受
- 前端提交的name和后端映射器接受的形参名不用一样,再形参前@RequestParam("xxx")更改名称一致
- 养成习惯:无论是否一样,都必须加上@RequestParam
- 后端参数封装如果成一个pojo,前端传过来的name会自动pojo中的成员属性,不匹配的属性=null/0
乱码问题
方法一:web.xml里面配置的SpringMvc自带的过滤器CharacterEncodingFilter
<url-pattern>/*</url-pattern>
:因为要跳转到xxx.jsp页面,所以url是/*(≠/)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--配置SpringMVC--> <servlet> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring_mvc_servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springMvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--web容器解决中文乱码问题--> <filter> <filter-name>encode</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encode</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
方法二:一劳永逸,但需要重启Tomcat服务器,修改Tomcat里面的server.xml配置文件:URIEncoding = "UTF-8"
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding = "UTF-8"/> <!-- A "Connector" using the shared thread pool-->