SpringMVC总结

2023-11-10

SpringMVC总结

一、配置

1、SpringMVC.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 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">
<!--1、配置springmvc的处理器对象的扫描路径-->
    <context:component-scan base-package="com.qf.j2102.controller"/>
<!--2、设置springmvc处理方式-->
    <mvc:annotation-driven/>
<!--3、设置对常见资源请求的处理方式-->
    <mvc:default-servlet-handler/>
<!--4、配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

2、web.xml文件配置

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>helloController</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>helloController</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

3、依赖

  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.6.RELEASE</version>
    </dependency>

二、常用标签

1、@Controller 在控制器类上加,表示为一个控制器,共SpringMVC扫描

2、@RequestMapping(“/控制器名称”) ----相当于路径别名

(1)、加在控制器方法上,在浏览器输入地址时 /控制器名称 可进入对应的方法中

(2)、加在控制器类上,在浏览器输入地址时 /控制器名称/控制器方法 可进入到对应的方法中

​ 一般用于区别不同控制器类,但方法名相同时

三、传参

1、基本类型参数

​ 浏览器地址:Http://localhost:8080/参数名=参数值

​ 控制器接收:

(1)、直接接收

@RequestMapping("/控制器名")
public String 方法 (参数类型  参数名){
    
}

(2)、@RequestParam标签

@RequestMapping("/控制器名")
public String 方法 (@RequestParam(value="参数名",defaultValue="默认值") 参数类型 参数名){
    
}

注:(1)、@RequestParam中的参数名与形参名进行绑定

​ (2)、@RequestParam 标签接收前端页面的值,并将值赋给参数

​ (3)、若浏览器地址中没有参数,则defaultValue中的值充当默认值,并将其赋值给形参。

(4)、@RequestParam 只用于接收请求行的参数

(5)、若请求行中参数与形参一致,则可省略

(3)、接收时间类型

SpringMVC默认的时间类型为:“yyyy-MM-dd HH:mm:ss”

通过 @DateTimeFormat 标签可改变其格式

浏览器地址:Http://localhost:8080/date=2021-3-16

控制器接收:

@RequestMapping("/控制器名")
public String 方法 (@DateTimeFormat(pattern="yyyy-MM-dd")Date date){
    
}

注:可将@DataTimeFormt标签加载实体类的属性上,可设置date类型参数的接收格式,且只用设置一次

(4)@JsonFormt

此标签可设置后端传参给前端Json串时,date类型的格式

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Comment {
    private Integer id;
    private String comment;
    @JsonFormat(pattern = "yyyy-MM-dd hh:mm",timezone = "GMT+8")
    private Date date;
}

注:timezone参数可设置时区为东八区

2、实体传参

​ 先创建一个实体类:

public class Person {
    private Integer id;
    private String name;
    private Integer age;
    private Date birth;

    public String getBirth(){
        return new SimpleDateFormat("yyyy-MM-dd").format(birth);
    }
}

​ 浏览器地址:Http://localhost:8080/id=xxx&name=xxx&age=xxx&birth=yyyy-MM-dd HH:mm:ss

​ 在控制器中接收

@RequestMapping("/控制器名")
public String 方法 (Person person){
    
}

注:1、SpringMVC可自动识别浏览器中的地址,并将其自动封装为一个对象
2、若参数中的字段与对象属性名不一致,可在对象成员变量上加入@JsonProperty(“参数名”)标签

3、数组传参

​ 浏览器地址:Http://localhost:8080/控制器?变量名=变量值&变量名=变量值

​ 在控制器中接收:

@RequestMapping("/控制器名")
public String 方法 (数组类型[] 数组变量名){
    
}

注:数组类型一般为:8种基本类型,String类型

4、路径传参

​ 浏览器地址:Http://localhost:8080/参数1/参数2

​ 路径传参需要 @RequestMapping(“/控制器名/{参数名}/{参数名}”)

​ 在控制器中接收:

@RequestMapping("/控制器名/{参数1}/{参数2}")
public String 方法(@PathVariable("参数名") 参数类型 参数名){
    
}

注:(1)、@PathVariable标签可以自动匹配路径中的参数{参数},并将其赋值给参数。因此@RequestParam 中的参数与@PathVariable中的参数进行绑定,并将其赋值给形参。

​ (2)、若@RequestMapping中的参数与形参名相同,可将@PathVariable()简写为@PathVariable

​ (3)、@RequestMapping中参数 [控制器名/{参数}] 的匹配能力与 [控制器名/*] 匹配能力相同

四、请求重定向与请求转发

1、在方法中返回的字符串会被SpringMVC拦截,并将其加上前缀与后缀,从而生成一个完整的请求地址,从而在浏览器中进行跳转。

<!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>   前缀
        <property name="suffix" value=".jsp"/>  后缀
    </bean>

注:若页面在不同的包中可在方法返回值中加入(root/index) ----> /root/index.jsp

2、一般默认为请求转发,在返回值中开头加上 “redirect : 页面” 可进行请求重定向。

​ 3、请求重定向与请求转发的区别:

​ (1)、请求转发是转发的模式视图 (ModelView),请求重定向发送的一个地址

​ (2)、在SpringMVC中,请求重定向不能直接跳转页面,需要先跳转到另一个控制器中,再通过请求转发进行页面跳转。

4、请求转发向 Request 域中插入数据

​ (1)、在方法的参数列表加入 Model model 参数,通过Spring向其中注入一个对象,通过 model.addAttribute(“参数名”,值)的方式,向 Request 域中加入数据

@RequestMapping("/控制器名")
public String 方法 (Model model){
    model.addAttribute("参数名",值)
}

​ (2)、在方法中 new 一个 ModelAndView 对象,再调用其 modelAndView.addObject(“参数名”,值)的方式向Request域中加入数据。

@RequestMapping("/控制器名")
public String 方法 (){
	//创建一个模型视图对象
    ModelAndView modelAndView = new ModelAndView();
    //设置逻辑视图名
    modelAndView.setViewName("名称");
    //设置传到视图中的数据(默认为Request域)
    modelAndView.addObject("参数名",值);
    return modelAndView;
}

注:最后根据逻辑视图名进行跳转

五、Ajax

1、通过HttpServletResponse发送AJAX请求

​ (1)、首先获取 Response 对象

​ 可在参数列表中通过Spring注入 Resonse 对象

​ (2)、获取到 Response 对象后与 Servlet 用法相同

@RequestMapping("/控制器名称")
public String 方法 (Response response){
    Writer writer = response.getWriter();
    writer.writer();
    writer.flush();
    writer.close();
}

2、通过@ResponseBody 标签发送AJAX请求

​ 直接return 的就就是JSON数据

六、向Session域中插入数据

1、同过形参注入 HttpSession 对象

@RequestMapping("控制器名称")
public String 方法 (HttpSession session){
    session.setAttribute("参数名",);
}

​ 2、在类上添加 @SessionAttributes( {“参数名1”,“参数名2”} ) 标签,在方法中通过 model.addAttribute(“参数名”,值) 向Session域中加入值。

@Controller
@SessionAttribute({"参数名1""参数名2"})
public class{
    @RequestMapping("/控制器名")
    public String 方法 (Model model){
        model.addAttribute("参数名",);
    }
}

注:model.addAttribute(“参数名”,值) 中的参数名必须与 @SessionAttribute 标签中的参数名相同

七、SpringMVC上传文件

1、依赖

 <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>

2、Spring配置文件

<!--配置文件解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
    </bean>

3、前端使用标签

<form action="路径" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
</form>

注:form表单中必须用post提交

4、控制器接收

//在参数列表中注入MultiparfFile
public String onload(MultipartFile imgFile){
    //1、截取上传文件的后缀名,生成新的文件名
    String oriFileName=imgFile.getOriginalFilename();
    String ext=oriFileName.substring(originalFilename.lastIndexOf("."));
    String fileName=UUID+ext;
    //2、获取imgs目录在服务器的路径
    String dir=request.getServletContext().getRealPath("imgs");
    String savePath=dir+"/"+fileName;
    //3、保存文件
    imgFile.transferTo(new File(savePath));
    //4、将文件名存入数据库
    对象.set(savePath);
    调用service方法;
        
}

5、MultipartFile类实现多文件上传

 @RequestMapping("fileImgSave")
	public String  fileImgSave(@RequestParam("filename") MultipartFile[] files,HttpServletRequest request){
		//保存文件的路径
		String realPath = request.getSession().getServletContext().getRealPath("/imgssss");
		File path = new File(realPath);
		if(!path.exists()){
			path.mkdirs();
		}
                //判断file数组不能为空并且长度大于0
                if(files != null && files.length > 0){
                    //循环获取file数组中得文件
                    for(int i = 0;i < files.length;i++){
                        MultipartFile file = files[i];
                        //保存文件
                        if (!file.isEmpty()){
    	                    try {
    	                        //转存文件  file.getOriginalFilename();文件原名称包括后缀名
    	                        file.transferTo(new File(realPath+"/img"+i+".png"));
    	                    } catch (IOException e) {
    	                        e.printStackTrace();
    	                    }
    	                }
                    }
                }
 
		return "ok";
	}

八、SpringMVC文件下载

1、前端缩略图

<div class="row"> 
    <div class="col-xs-6 col-md-3"> 
        <a href="#" class="thumbnail"> 
            <img src="..." alt="..."> 
        </a> 
    </div> ... 
</div>

注:标签中的href属性为服务器控制器路径,响应方式为AJAX请求

2、通过流传输文件(本地不保存)

@RequestMapping("/download")
public void downloadImg(String fname,HttpServletRequest request,HttpServletResponse response){
	//1、从服务器目录找到当前文件
	String dir=request.getServletContext().getRealPaht("服务器文件名");
	String filePath=dir+"/"+fname;
	FileInputStream fileImputStream =new FileInputStream(filePath);

	//2、将服务器文件流复制到用户流
	IOUtils.copy(fileInputStream,response.getOutPutStream());
}

3、通过流传输文件(本地保存)

@RequestMapping("/download")
public void downloadImg(String fname,HttpServletRequest request,HttpServletResponse response){
	//1、从服务器目录找到当前文件
	String dir=request.getServletContext().getRealPaht("服务器文件名");
	String filePath=dir+"/"+fname;
	FileInputStream fileImputStream =new FileInputStream(filePath);
    
    //2、设置响应头
    response.setContextType("application/exe");
    response.addHeader("content-disposition","attachment;filename="+fname);

	//2、将服务器文件流复制到用户流
	IOUtils.copy(fileInputStream,response.getOutPutStream());
}

九、解决中文乱码

1、JSP

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" isELIgnored="false" %>

2、Html

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

3、TmoCat

<Connector connectionTimeout="20000" port="8080" 
			   protocol="HTTP/1.1" redirectPort="8443"  URIEncoding="UTF-8"/>

​ 通过Mevan插件部署Tomcat解决乱码问题

<plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <path>/</path>
          <port>8080</port>
          <uriEncoding>UTF-8</uriEncoding>
        </configuration>
      </plugin>
    </plugins>

注:解决解决过程乱码问题,特别是 get 的提交方式

4、设置控制器编码

​ 在 web.xml 文件设置全局过滤器,通过过滤器设置编码格式

 <filter>
    <filter-name>encoding</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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

十、请求方式

1、请求行提交参数

​ (1)、form 表单提交

​ (2)、get与post都是请求行传值,post隐藏参数,get不隐藏

​ (3)、标签提交,URL提交,也是请求行传参

2、AJAX提交

$.ajad{
    url:"", //请求行传参
    headers:"", //请求头传参
    contextType:"application/json", //参数类型,若请求体为对象类型,则需要定义json类型
   	data:{}, //请求体传参
        success(function({
            
        }) )
}

十一、SpringMVC前端控制器

1、前端控制器的作用

​ SpringMVC中只有一个Servlet,这个Servlet用于接收所有的非页面跳转,在接收到其请求后,根据他的RequestURI跳调用其具体的业务类的方法,最后将返回值返回到这个Servlet中进行跳转。因此,SpringMVC的前端控制器主要是起到到一个调度与分发请求与相应的作用;即SpringMVC的前端控制器的作用类似于大堂经理的作用。
在这里插入图片描述

2、实现流程

在这里插入图片描述
​ Controller接口

public interface Controller {
    String handlerRequest(HttpServletRequest request, HttpServletResponse response);
}

​ DespatcherServlert控制器

@WebServlet({"/input","/save"})
public class DispatcherServlet extends HttpServlet {
    private final String INPUTURI="input";
    private final String SAVEURI="save";
    private String prefix="/WEB-INF/root/";
    private String suffix=".jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path="";
        Controller controller=null;
        String requestURI = req.getRequestURI();
        String uri = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        if (uri.equalsIgnoreCase(INPUTURI)){
            controller=new InputServlet();
        }else if (uri.equalsIgnoreCase(SAVEURI)){
            controller=new SaveServlet();
        }
        path = controller.handlerRequest(req, resp);
        req.getRequestDispatcher(prefix+path+suffix).forward(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}

​ ControllerService控制器

public class SaveServlet implements Controller {
    @Override
    public String handlerRequest(HttpServletRequest request, HttpServletResponse response) {
        Student student=new Student();
        String sid1 = request.getParameter("sid");
        Integer sid = request.getParameter("sid")==""?0:Integer.valueOf( request.getParameter("sid"));
        String sname = request.getParameter("sname");
        String birth1 = request.getParameter("birth");
        Date birth= birth1==""?null:DateTool.dateFormat(birth1);
        Double money = request.getParameter("money")==""?0:Double.valueOf(request.getParameter("money"));

        Check check=new Check(sname,birth,money);
        CheckEnty checkEnty=new CheckEnty();
        Map<String, String> errors = checkEnty.check(check);

        if (errors.size()==0){
            student.setSid(sid);
            student.setSname(sname);
            student.setBirth(birth);
            student.setMoney(money);
            request.setAttribute("student",student);
            return "save";
        }else {
            request.setAttribute("err",errors);
            request.setAttribute("val",check);
            return "input";
        }

    }
}

十二、通过Spring代理SpringMVC

1、依赖

​ 需要 spring-webmvc依赖

 <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.6.RELEASE</version>
</dependency>

2、通过Spring.xml文件代理SpringMVC

​ Spring代理了SpringMVC的DispatcherController类,因此需要在Spring.xm文件中注册业务Controller,以及定义请求全路径的前缀与后缀。

<?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:p="http://www.springframework.org/schema/p"
       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">
    //注册业务Controller
    <bean class="com.qf.controller.DeptAllController" name="/all"/>
    <bean class="com.qf.controller.DeptDeleteController" name="/delete"/>
	//定义请求全路径的前缀与后缀
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/root/" p:suffix=".jsp"/>
    //加载静态资源
    <mvc:default-servlet-handler/>
</beans>

​ 在实体Controller中仍然要实现Controller类的HandlerReuqest方法,并只要在该方法写业务逻辑即可,最终返回ModelAndView对象

public class DeptAllController implements Controller {
    DeptService deptService=new DeptServiceImpl();

    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Dept> depts = deptService.selectAll();
        return new ModelAndView("AllDepts","depts",depts);
    }
}

注:若在Spring.xml文件中定义了请求全路径的前缀与后缀,就需要定义处理静态资源的标签,通过此标签可使Spring处理静态资源,即可以直接加载欢迎页面

3、ModelAndView类详解

(1)Model为数据,即给请求域中加入的数据;View为视图,即需要跳转的页面名

(2)单参控制器

ModelAndView ma=new ModelAndView("页面名");

(2)三参控制器

ModelAndView ma=new ModelAndView("页面名","数据别名","数据");

注:1、若在Spring.xml文件中定义了请求全路径的前缀以及后缀,只需要写页面名即可;若没有定义则需要写页面的请求全路径,但通过此方法只能传入单个参数

2、通过 ma.addObject(“数据别名”,“数据”) 向请求域中加入多个数据

(3)Model类

Model m=new Model();
m.addAttribute("数据别名","数据");

​ 通过 m.addAttribute() 方法也可向请求域中加入数据

4、通过注解代理SpringMVC

(1)通过代理的方式代理SpringMVC需要需要在Spring.xml文件中定义扫描器扫描Controller,还需要开启标签模式,以及定义请求全路径的前缀与后缀,和设置加载静态资源

<?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:p="http://www.springframework.org/schema/p"
       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="com.qf.controller"/>
	//加载静态资源
    <mvc:default-servlet-handler/>
	//开启标签模式
    <mvc:annotation-driven/>
	//定义请求全路径的前缀与后缀
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/root/" p:suffix=".jsp"/>

</beans>

(2)常用标签

​ 在控制器中需要 @Controller 标签来声明一个控制器,由于@Controller 标签中就包含 @Component 标签,因此不需要在定义 @Component 标签;还需要@RequestMapping(“Servlet名”) 标签来定义一个Servlet的请求路径,可以定义在控制器上也可定义在方法上(可以不定义在控制器上但必须定义在方法上)

@Controller
public class DeptController {
    DeptService deptService=new DeptServiceImpl();
	//路径传参
    @RequestMapping("/one/{did}")
    public String selectOne(@PathVariable("did") Integer did, HttpServletRequest request){
        Dept dept = deptService.selectOne(did);
        request.setAttribute("dept",dept);
        return "Dept";
    }
	//问号传参
    @RequestMapping("/update")
    public String update(Dept dept){
        deptService.update(dept);
        return "redirect:/all";
    }
}

(3)返回值

​ 标签模式可以返回一个字符串,也可返回一个ModelAndView对象;若返回字符串则默认请求转发,即返回一个ModelAndView对象;若需要请求重定向,则需要在请求名中加入“redirect:”的前缀,但只能跳转到控制器中,不能直接跳转到页面中。

(4)参数的注入

​ 需要什么对象就在参数列表中定义即可,Spring可以注入该对象

十二、RestFul风格

1、随着前端越来越多,如移动端、平板等,需要统一后端的访问接口;其思想是将网络链接都看作一种网络资源,前后端交互时,是访问后端的网络资源

2、RestFul风格是用于前后端分离的一种编程风格,在RestFul风格下后端给前端传的值都为Json串

3、在控制器上加标签@RestController标签,可将该控制器下所有的方法的返回值都设置为Json串

​ 在方法上添加标签@ResponseBoday标签,可将该方法的返回值设置为Json串

4、由于前端访问后端的资源,因此访问时使用Http动词,常用的Http动词如下:

Get:查询

Post:新增

Put:修改

Delete:删除

​ 其对应的后端控制器为:

GetMapping (“name”)

PostMapping(“name”)

Put(“name”)

Delete(“name”)

十三、校验与国际化

1、SpringMVC中的Validator类可以校验用户输入的值的合法性

2、自定义Validate类并继承Validator类,并实现supports(Class<?> aClass)方法与validate(Object o, Errors errors)方法

public class DeptValiDate implements Validator {
    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.isAssignableFrom(Dept.class);
    }

    @Override
    public void validate(Object o, Errors errors) {
        Dept dept = (Dept) o;
		//获取需要校验的值
        String dname = dept.getDname();
        Integer count = dept.getCount();
		//非空校验
        ValidationUtils.rejectIfEmpty(errors, "dname", "dname");
        ValidationUtils.rejectIfEmpty(errors, "count", "count");
		//正确性校验
        if (count != null && count < 0) {
            errors.rejectValue("count", "count.invalidate");
        }
    }
}

注:1、其中需要supports()方法的返回值为true,才会继续调用validate方法进行校验

2、rejectIfEmpty(),第一个参数为错误信息的类,第二个参数为需要校验的类,第三个参数为错误码

​ 3、rejectValue()方法只需要两个参数,第一个参数为需要校验的类,第二个参数为错误码

4、其中,错误码会匹配 webapp/WEB-INF/msg.properties 文件中的key,输出错误信息

3、在Spring.xml文件中定义节点

<bean class="org.springframework.context.support.ReloadableResourceBundleMessageSource" id="messageSource">
        <property name="basename" value="/WEB-INF/msg"/>
    </bean>

注:1、该bean一定要有id,且id名一定要为messageSource

​ 2、basename属性定义的为msg.properties文件的路径

4、在controller中调用

	@RequestMapping("/add")
    public String add(Dept dept, BindingResult bindingResult, Model model) {
        DeptValiDate valiDate = new DeptValiDate();
        //校验
        valiDate.validate(dept, bindingResult);
        //判定校验是否通过
        if (bindingResult.hasErrors()) {
            //校验未通过,向request中存一个空构造
            model.addAttribute("dept", dept);
            return "Save";
        }
        deptService.add(dept);
        return "redirect:/all";
    }

注:1、在参数列表中注入BindingResult对象,作为errors错误信息

2、如果信息有误,需要向页面中传递一个空的构造器,因此需要向request域中存一个空构造

5、在JSP页面中的使用

需要先在头部页面中引入form标签

<%@taglib prefix="f" uri="http://www.springframework.org/tags/form" %>

使用form标签

<%--
  Created by IntelliJ IDEA.
  User: dell
  Date: 2021-06-10
  Time: 20:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="f" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap-theme.min.css">
</head>
<body>
<f:form class="form-horizontal" action="/add" method="post" commandName="dept">
    <div class="form-group">
        <label for="inputPassword3" class="col-sm-2 control-label">部门名称</label>
        <div class="col-sm-10">
            <f:input type="text" class="form-control" id="inputPassword3" placeholder="请输入部门名称" path="dname"/><font
                color="red"><f:errors path="dname"/></font>
        </div>
    </div>
    <div class="form-group">
        <label for="inputPassword4" class="col-sm-2 control-label">部门人数</label>
        <div class="col-sm-10">
            <f:input type="text" class="form-control" id="inputPassword4" placeholder="请输入部门人数" path="count"/><font
                color="red"><f:errors path="count"/></font>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-default">提交</button>
        </div>
    </div>
</f:form>
</body>
</html>

注:1、一定要在form标签中加入 method="post" commandName="dept"

​ 2、在form标签内,name需要写成path

​ 3、<f:errors path="count"/>标签在有错误信息时,可自动渲染为错误信息

6、国际化

(1)、msg.properties文件

/webapp/WEB-INF/msg.properties 文件中定义错误信息

dname=the dname not be Empty
count=the count not be Empty
count.invalidate=the count id illegal

validate类将会在 msg.properties 文件中根据key匹配value

(2)、国际化

同样是在 /web/WEB-INF 路径下,创建带国际化标识的的 msg.properties 文件
例如中文国际化就需要创建 msg_zh_CN.properties 文件

注:1、若为中文国际化,则需要把 msg_zh_CN.properties 文件的编码设为 utf-8

2、或者输入转换过的字符集 (通过JDK自带工具中的 native2ascii 转换)

(3)常见的国际化标识

简体中文(中国)        zh_CN
繁体中文(台湾地区)     zh_TW
繁体中文(香港)        zh_HK
英语(香港)            en_HK
英语(美国)            en_US
英语(英国)            en_GB
英语(全球)    en_WW
英语(加拿大)    en_CA
英语(澳大利亚)    en_AU
英语(爱尔兰)    en_IE
英语(芬兰)    en_FI
芬兰语(芬兰)    fi_FI
英语(丹麦)    en_DK
丹麦语(丹麦)    da_DK
英语(以色列)    en_IL
希伯来语(以色列)    he_IL
英语(南非)    en_ZA
英语(印度)    en_IN
英语(挪威)    en_NO
英语(新加坡)    en_SG
英语(新西兰)    en_NZ
英语(印度尼西亚)    en_ID
英语(菲律宾)    en_PH
英语(泰国)    en_TH
英语(马来西亚)    en_MY
英语(阿拉伯)    en_XA
韩文(韩国)    ko_KR
日语(日本)    ja_JP
荷兰语(荷兰)    nl_NL
荷兰语(比利时)    nl_BE
葡萄牙语(葡萄牙)    pt_PT
葡萄牙语(巴西)    pt_BR
法语(法国)    fr_FR
法语(卢森堡)    fr_LU
法语(瑞士)    fr_CH
法语(比利时)    fr_BE
法语(加拿大)    fr_CA
西班牙语(拉丁美洲)    es_LA
西班牙语(西班牙)    es_ES
西班牙语(阿根廷)    es_AR
西班牙语(美国)    es_US
西班牙语(墨西哥)    es_MX
西班牙语(哥伦比亚)    es_CO
西班牙语(波多黎各)    es_PR
德语(德国)    de_DE
德语(奥地利)    de_AT
德语(瑞士)    de_CH
俄语(俄罗斯)    ru_RU
意大利语(意大利)    it_IT
希腊语(希腊)    el_GR
挪威语(挪威)    no_NO
匈牙利语(匈牙利)    hu_HU
土耳其语(土耳其)    tr_TR
捷克语(捷克共和国)    cs_CZ
斯洛文尼亚语    sl_SL
波兰语(波兰)    pl_PL
瑞典语(瑞典)    sv_SE
西班牙语 (智利)    es_CL
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringMVC总结 的相关文章

  • 如何将本机库链接到 IntelliJ 中的 jar?

    我正在尝试在 IntelliJ 中设置 OpenCV 但是我一直在弄清楚如何告诉 IntelliJ 在哪里可以找到本机库位置 在 Eclipse 中 添加 jar 后 您可以在 Build Config 屏幕中设置 Native 库的位置
  • 序列的排列?

    我有具体数量的数字 现在我想以某种方式显示这个序列的所有可能的排列 例如 如果数字数量为3 我想显示 0 0 0 0 0 1 0 0 2 0 1 0 0 1 1 0 1 2 0 2 0 0 2 1 0 2 2 1 0 0 1 0 1 1 0
  • Mockito:如何通过模拟测试我的服务?

    我是模拟测试新手 我想测试我的服务方法CorrectionService correctPerson Long personId 实现尚未编写 但这就是它将执行的操作 CorrectionService将调用一个方法AddressDAO这将
  • Junit:如何测试从属性文件读取属性的方法

    嗨 我有课ReadProperty其中有一个方法ReadPropertyFile返回类型的Myclass从属性文件读取参数值并返回Myclass目的 我需要帮助来测试ReadPropertyFile方法与JUnit 如果可能的话使用模拟文件
  • 如何循环遍历所有组合,例如48 选择 5 [重复]

    这个问题在这里已经有答案了 可能的重复 如何在java中从大小为n的集合中迭代生成k个元素子集 https stackoverflow com questions 4504974 how to iteratively generate k
  • 使用 LinkedList 实现下一个和上一个按钮

    这可能是一个愚蠢的问题 但我很难思考清楚 我编写了一个使用 LinkedList 来移动加载的 MIDI 乐器的方法 我想制作一个下一个和一个上一个按钮 以便每次单击该按钮时都会遍历 LinkedList 如果我硬编码itr next or
  • 过滤两次 Lambda Java

    我有一个清单如下 1 2 3 4 5 6 7 和 预期结果必须是 1 2 3 4 5 6 7 我知道怎么做才能到7点 我的结果 1 2 3 4 5 6 我也想知道如何输入 7 我添加了i gt i objList size 1到我的过滤器
  • 谷歌应用程序引擎会话

    什么是java应用程序引擎 默认会话超时 如果我们将会话超时设置为非常非常长的时间 会不会产生不良影响 因为谷歌应用程序引擎会话默认情况下仅存储在数据存储中 就像facebook一样 每次访问该页面时 会话仍然永远存在 默认会话超时设置为
  • 来自 dll 的 Java 调用函数

    我有这个 python 脚本导入zkemkeeperdll 并连接到考勤设备 ZKTeco 这是我正在使用的脚本 from win32com client import Dispatch zk Dispatch zkemkeeper ZKE
  • 检测并缩短字符串中的所有网址

    假设我有一条字符串消息 您应该将 file zip 上传到http google com extremelylonglink zip http google com extremelylonglink zip not https stack
  • java.lang.IllegalStateException:提交响应后无法调用 sendRedirect()

    这两天我一直在尝试找出问题所在 我在这里读到我应该在代码中添加一个返回 我做到了 但我仍然得到 java lang IllegalStateException Cannot call sendRedirect after the respo
  • 无法创建请求的服务[org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]-MySQL

    我是 Hibernate 的新手 我目前正在使用 Spring boot 框架并尝试通过 hibernate 创建数据库表 我知道以前也问过同样的问题 但我似乎无法根据我的环境找出如何修复错误 休眠配置文件
  • 将 MOXy 设置为 JAXB 提供程序,而在同一包中没有属性文件

    我正在尝试使用 MOXy 作为我的 JAXB 提供程序 以便将内容编组 解组到 XML JSON 中 我创建了 jaxb properties 文件 内容如下 javax xml bind context factory org eclip
  • Spring Boot Data JPA 从存储过程接收多个输出参数

    我尝试通过 Spring Boot Data JPA v2 2 6 调用具有多个输出参数的存储过程 但收到错误 DEBUG http nio 8080 exec 1 org hibernate engine jdbc spi SqlStat
  • 在我的 Spring Boot 示例中无法打开版本 3 中的 Swagger UI

    我在 Spring Boot 示例中打开 swagger ui 时遇到问题 当我访问 localhost 8080 swagger ui 或 localhost 8080 root api name swagger ui 时出现这种错误 S
  • 尝试将 Web 服务部署到 TomEE 时出现“找不到...的 appInfo”

    我有一个非常简单的项目 用于培训目的 它是一个 RESTful Web 服务 我使用 js css 和 html 创建了一个客户端 我正在尝试将该服务部署到 TomEE 这是我尝试部署时遇到的错误 我在这里做错了什么 刚刚遇到这个问题 我曾
  • 如何使用 jUnit 将测试用例添加到套件中?

    我有 2 个测试类 都扩展了TestCase 每个类都包含一堆针对我的程序运行的单独测试 如何将这两个类 以及它们拥有的所有测试 作为同一套件的一部分执行 我正在使用 jUnit 4 8 在 jUnit4 中你有这样的东西 RunWith
  • Cucumber 0.4.3 (cuke4duke) 与 java + maven gem 问题

    我最近开始为 Cucumber 安装一个示例项目 并尝试使用 maven java 运行它 我遵循了这个指南 http www goodercode com wp using cucumber tests with maven and ja
  • Opencv Java 灰度

    我编写了以下程序 尝试从彩色转换为灰度 Mat newImage Imgcodecs imread q1 jpg Mat image new Mat new Size newImage cols newImage rows CvType C
  • Spring Rest 和 Jsonp

    我正在尝试让我的 Spring Rest 控制器返回jsonp但我没有快乐 如果我想返回 json 但我有返回的要求 完全相同的代码可以正常工作jsonp我添加了一个转换器 我在网上找到了用于执行 jsonp 转换的源代码 我正在使用 Sp

随机推荐

  • 重叠社区发现-UEOC算法(unfold and extract overlapping communities)学习笔记

    本文提出了一种基于马尔可夫动力学模型的发现节点共享社区的算法UEOC 在UEOC方法中 为了检测出所有的自然群落 将马尔可夫随机游动方法与一种新的约束策略相结合 该策略基于相应的退火网络 21 用于展开每个群落 然后 利用一个借助电导的截止
  • 【Python编程入门】环境搭建

    作为一门跨平台的高级编程语言 Python可以运行在几乎所有主流的操作系统中 这也意味着 只要我们在本机电脑安装配置完Python环境后 便可以轻松愉快的学习Python语言了 这是一门值得大部分人学习的计算机编程语言知识 关于Python
  • angular自定义form表单元素-checkList

    实际使用form的时候 最外层的form的某个表单元素可能是个组合的 这种情况如果是可多场景复用的 最好封装一个表单元素 本文以组合复选框为例来说明下自定义表单元素的过程 实现效果 展示效果 html
  • TeamViewer三种许可证的区别是什么?

    很多想要购买TeamViewer正版许可证的用户 不清楚这三种许可证的区别 所以今天小编就为大家介绍一下 这三种许可证到底有何区别以及购买那种最划算 首先为大家介绍一下TeamViewer Business商业版许可证 如下图所示 图1 B
  • 汇编语言基础知识

    文章目录 80386常用寄存器 一 常用寄存器 1 1 通用寄存器 1 2 段寄存器 1 3 程序状态与控制寄存器 二 常用基本指令 2 1 数据传送指令 2 2 算术运算指令 2 2 1 加法指令 2 2 2 减法指令 2 2 3 乘法指
  • 查看使用systemctl启动日志

    2019独角兽企业重金招聘Python工程师标准 gt gt gt 1 查看启动日志 journalctl f或者 journalctl xe 2 设置开机自启动 systemctl enable nginx service 3 启动ngi
  • 2023最新SSM计算机毕业设计选题大全(附源码+LW)之java制造类企业erp23725

    面对老师五花八门的设计要求 首先自己要明确好自己的题目方向 并且与老师多多沟通 用什么编程语言 使用到什么数据库 确定好了 在开始着手毕业设计 1 选择课题的第一选择就是尽量选择指导老师擅长的课题 其实说白一点 你们的指导老师每年都是那几个
  • C3P0连接池参数配置

  • Linux系统wget unable to resolve host address解决办法

    Linux系统运行yum安装rpm包的时候提示wget unable to resolve host addresswget 无法解析主机地址 这就能看出是DNS解析的问题 错误提示 wget unable to resolve host
  • 用于CTF(MISC)的kali虚拟机更改过程记录

    Kali更改记录 安装pip2 太多工具需要python2了 安装setuptools 18 5 wget https pypi python org packages source s setuptools setuptools 18 5
  • 面向对象的编程思想和Python的继承和多态,特殊方法,引用计数

    面向对象的编程思想和Python的类 访问和属性 继承 在上一文中我们了解到了 私有的属性的访问方式 实例名 类名 私有属性名 一 私有的属性如何对外提供公有的取值和赋值方法呢 提供公有的方法作为接口进行取值 例如 class Avg Sc
  • 思科路由器NAT配置详解(转)

    思科路由器NAT配置详解 转 网络技术 2010 07 11 17 48 14 阅读104 评论0 字号 大中小 订阅
  • ubuntu安装vscode_vscode远程开发配置

    Remote development是一个支持vscode远程开发的插件 非常方便在windows下调试远程linux系统上的代码 使用配置方式如下 首先windows和远端服务器都要安装ssh windows上启用ssh服务即可 linu
  • RBAC权限管理

    RBAC权限管理 RBAC应用最为广泛的权限管理模型 核心的三要素是 用户 角色 权限 但并不仅仅局限于这三个核心要素 基于企业规模 用户规模 运维复杂度 RBCA其实是有很多的变种 从理论角度 有所谓的RBAC0 RBAC1 RBAC2
  • python opencv cv2在图片中画mask掩码/掩膜

    python opencv cv2在图片中画mask掩膜 import cv2 import numpy as np from PIL import Image import matplotlib pyplot as plt mask th
  • 年度最火的AOA蓝牙室内定位原理

    AOA 定位方法 AOA 定位方法 主要是测量信号移动台和基站之间的到达角度 以基站为起点形成的射线必经过移动台 两条射线的交点即为移动台的位置 该方法只需两个基站就可以确定 MS 的估计位置 其定位示意图如图所示
  • 语音转文字,视频转文字的新大陆!--飞书(好用记得点个赞)

    语音转文字 视频转文字的新大陆 飞书 1 选择自己对应的系统 下载飞书 飞书是字节跳动于2016年自研的新一代一站式协作平台 网址 https www feishu cn 2 下载安装之后 使用手机号 邮箱等注册登录 点击会议 点击进入子菜
  • 现代框架背后的概念

    很多初学者问 我应该学哪个框架 和 学一个框架之前需要学多少JS或TS 无数自以为是的文章都在宣传作者首选框架或库的优势 而不是向读者展示其背后的概念以做出明智的决定 那么让我们先解决第二个问题 学一个框架之前要学多少JS TS 尽可能多地
  • python调用c++动态库_使用python 调用 pybind11封装的 cuda C++ 动态链接库

    使用python 调用 pybind11封装的 cuda C 动态链接库 pybind11是可以使C 和python程序间互相调用的轻量头文件库 它可以将C 代码编译成python可调用的动态链接库 pybind11可以自动实现C 中vec
  • SpringMVC总结

    SpringMVC总结 一 配置 1 SpringMVC xml配置文件