视图解析器概述
将Controller的返回值进行解析,到浏览器。
在SpringMVC中也有很多视图解析器
这时通过视图解析器解析handler返回的值(逻辑视图,转发数据)
InternalResourceViewResolver会将逻辑视图与prefix和suffix组合成物理视图名, 如果逻辑视图返回值中包含redirect:,则进行重定向操作,如果是forward:或者没有前缀,则转发操作。
编写一个视图
package cn.cqie.controller.a_view; import org.springframework.web.servlet.View; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; /** * Description: * Author: tiancx * Date: Created in 2021/11/25 15:02 */ public class MyView implements View { @Override public String getContentType() { return null; } @Override public void render(Map<String, ?> map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { //map就是model中添加的数据 for (Map.Entry<String, ?> entry : map.entrySet()) { httpServletRequest.setAttribute(entry.getKey(), entry.getValue()); System.out.println(" "+entry.getKey()+" : " +entry.getValue()); } System.out.println("MyView.render"); httpServletRequest.getRequestDispatcher("abc.jsp").forward(httpServletRequest, httpServletResponse); } }
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="cn.cqie.controller.a_view"/> <mvc:annotation-driven/> <!-- BeanNameViewResolver是当前项目的中视图解析器 MyView声明了跳转的方式和数据转发 --> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"></bean> <bean id="myView" class="cn.cqie.controller.a_view.MyView"></bean> </beans>
package cn.cqie.controller.a_view; import cn.cqie.pojo.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /** * Description: * Author: tiancx * Date: Created in 2021/11/23 21:30 */ @Controller public class UserController { @RequestMapping("save") public String save(Model model){ System.out.println("UserController.save"); User xy = new User("xy", 30); model.addAttribute("a",xy); return "myView"; } }
请求映射
1、RequestMapping可以声明在类和方法上
RequestMapping
可以声明在类上,如果要访问方法,需要将类的RequestMapping的值与方法上的RequestMapping的值组合访问。
http://localhost:8080/项目名称/类上注解/方法上注解
为了防止直接通过浏览器访问jsp页面,将所有页面放到WEB-INF下。只能通过控制器跳转。在视图解析器中的前缀添加WEB-INF。
2、可以根据不同的请求方式来控制哪种请求可以访问
//method = RequestMethod.POST只有页面通过post传参,才可以访问到这个方法 @RequestMapping(value = "save",method = RequestMethod.POST) public String save(){ System.out.println("UserController.save"); return "b"; }
浏览器地址栏访问 都是Get请求
3、在RequestMapping中添加params
//页面需要传递params中声明的参数,且值必须相等,这时才可以访问该方法 @RequestMapping(value = "login",params = {"uname=admin","pwd=123"}) public String login(String uname,String pwd){//这里要和 地址栏里面的参数一致才行 uname与uname对应 要对应 System.out.println("UserController.save2"); System.out.println(uname+" "+pwd); return "b"; }
4、在RequestMapping中添加Headers
//可以在RequestMapping中声明headers,获得页面传递的请求头,从请求头中获得对应的信息,如果该信息相等,允许访问该方法 @RequestMapping(value = "list",headers = "host=localhost:8080") //headers = "host=localhost:8080"只允许本机访问 。 【注意】 127.0.0.1 也不行必须 localhost public String list(){ System.out.println("UserController.list"); return "b"; }
5、在RequestMapping中添加占位符
@RequestMapping(value = "login2/{uname}/{pwd}") //需要使用注解 public String login2(@PathVariable("uname") String uname,@PathVariable("pwd") String pwd){ System.out.println("UserController.save2"); System.out.println(uname+" "+pwd); return "b"; }
相应的配置文件
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="cn.cqie.controller.b_request_mapping"/> <mvc:annotation-driven/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
相关内容
控制器方法入参
1、基本数据类型的自动转化
2、自动封装数据
package cn.cqie.controller.c_param; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import java.util.Arrays; import java.util.List; /** * Description: * Author: tiancx * Date: Created in 2021/11/23 21:30 */ @Controller public class UserController { /** * 在SpringMVC的Controller中不再需要request.getParameter(),直接在方法的参数中声明即可,要求参数名与表单控件的name一致 * 如果非要不一致,则需要添加注解@RequestParam("表单的name值") */ @RequestMapping("save1") public String save1(String name,@RequestParam("pwd") String password){ System.out.println("UserController.save1:"+name+" : "+password); return null; } //SpringMVC的Controller,可以对数据进行自动转换 @RequestMapping("save2") public String save2(Integer age){ System.out.println("UserController.save2: "+(2021-age));//输出年份 return null; } //可以将表单的数据自动封装成对象(参数中指定的类型) @RequestMapping("save3") public String save3(User user){ System.out.println("UserController.save3: "+user); return null; } //复选框的值可以直接获得为字符串数据,整型数组,如果需要List<Integer>类型,则需要添加注解@RequestParam // @RequestMapping("save4") // public String save4(String[] ids){ // System.out.println("UserController.save4: "); // System.out.println(Arrays.toString(ids)); // return null; // } @RequestMapping("save4") public String save4(@RequestParam List<Integer> ids){ System.out.println("UserController.save4: "); System.out.println(ids); return null; } }
<%-- Created by IntelliJ IDEA. User: admin Date: 2021/11/25 Time: 17:18 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <h3>传递参数到Controller</h3> <form action="save1" method="post"> <input name="name"> <input name="pwd"> <button>submit</button> </form> <hr> <h3>传递整型数据</h3> <form action="save2"> <input name="age"> <button>submit</button> </form> <hr> <h3>传递对象数据</h3> <form action="save3"> <input name="name"> <input name="age"> <button>submit</button> </form> <hr> <h3>传递复选框数据</h3> <form action="save4"> <input type="checkbox" name="ids" value="1"> <input type="checkbox" name="ids" value="2"> <input type="checkbox" name="ids" value="3"> <button>submit</button> </form> </body> </html>
时间类型参数
SpringMVC中默认识别日期格式为yyyy/MM/dd
其他格式需要自己编写转换类
package cn.cqie.controller.d_convert; import org.springframework.core.convert.converter.Converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Description: * Author: tiancx * Date: Created in 2021/11/25 21:31 */ public class DateConverter implements Converter<String, Date> { @Override public Date convert(String s) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); //还可以转换其他的, 比如 yyyy.MM.dd Date date = null; try { //将日期转换成字符串 date= simpleDateFormat.parse(s); } catch (ParseException e) { e.printStackTrace(); } return date; } }
将转换类配置到SpringMVC框架中
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="cn.cqie.controller.d_convert"/> <mvc:annotation-driven conversion-service="conversionService"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="cn.cqie.controller.d_convert.DateConverter"></bean> </set> </property> </bean> </beans>
Controller里面的代码
package cn.cqie.controller.d_convert; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.util.Date; /** * Description: * Author: tiancx * Date: Created in 2021/11/23 21:30 */ @Controller public class UserController { @RequestMapping("save1") public String save(Date date){ System.out.println(date); return null; } }
使用ServletAPI
HttpServletRequest
HttpServletResponse
HttpSession
ServletContext
HttpServletRequest,HttpServletResponse,HttpSession对象都可以从方法参数中获取
@RequestMapping("login") public String login(HttpServletRequest req, HttpServletResponse resp, HttpSession session){ System.out.println("HttpServletRequest"+req); System.out.println("HttpServletResponse"+resp); System.out.println("HttpSession"+session); return null; }
SpringMVC数据校验
正则表达式
电话号码格式
邮箱格式
身份证格式等等
前端数据校验 (可以减轻服务器压力)
后端数据校验
1、添加依赖
<dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.20.Final</version> </dependency>
2、定义校验规则
在封装类上定义校验规则,JSR303
package cn.cqie.controller.e_validator; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.Serializable; /** * Description: * Author: tiancx * Date: Created in 2021/11/24 21:04 */ public class User implements Serializable { //null "" // 在封装类上定义校验规则,JSR303 // @NotBlank(message = "uname 不能为空!") @NotBlank(message = "name 不能为空") private String name; @NotNull(message = "age 不能为空") private Integer age; public User() { } public User(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } }