美文网首页
chapter06_渲染Web视图_1_创建JSP视图

chapter06_渲染Web视图_1_创建JSP视图

作者: 米都都 | 来源:发表于2019-01-15 17:35 被阅读0次
    • 通常将JSP文件放在 /WEB-INF目录下,防止对它的直接访问

    • InternalResourceViewResolver是JSP的视图解析器,它遵循一种约定,会在视图名上添加前缀和后缀,进而定位JSP文件的位置

      (1) JavaConfig

        @Configuration
        @EnableWebMvc
        @ComponentScan("spittr.web")
        public class WebConfig extends WebMvcConfigurerAdapter {
      
            @Bean
            public ViewResolver viewResolver() {
      
                InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        
                resolver.setPrefix("/WEB-INF/views/");
                resolver.setSuffix(".jsp");
         
                return resolver;
            }
      
            ...
        }
      

      (2) 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:p="http://www.springframework.org/schema/p"
               xsi:schemaLocation="http://www.springframework.org/schema/beans 
                                   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
      
            <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>
      
            ...
        
        </beans>
      
    • (1) 如果JSP文件使用JSTL处理格式化和信息的话,应该将视图解析为 JstlView。这时需要设置InternalResourceViewResolver的viewClass属性

      (2) Java Config

        @Configuration
        @EnableWebMvc
        @ComponentScan("spittr.web")
        public class WebConfig extends WebMvcConfigurerAdapter {
      
            @Bean
            public ViewResolver viewResolver() {
      
                InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        
                resolver.setPrefix("/WEB-INF/views/");
                resolver.setSuffix(".jsp");
                resolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);
         
                return resolver;
            }
      
            ...
        }
      

      (3) 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:p="http://www.springframework.org/schema/p"
               xsi:schemaLocation="http://www.springframework.org/schema/beans 
                                   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
      
            <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/views/" p:suffix=".jsp" p:viewClass="org.springframework.web.servlet.view.JstlView.class"/>
      
            ...
        
        </beans>
      
    • 使用Spring的JSP库(一):绑定model中的某个属性

      (1) Spring的表单绑定JSP库包含14个标签。与原生html标签的区别在于它们可以绑定模型中的一个对象,根据模型中的对象填充值

      (2) 使用前要进行声明

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

      (3) 14个标签

        <sf:input>
        <sf:errors>
        ...
      

      (4) 示例

      SpitterController.java

        @Controller
        @RequestMapping("/spitter")
        public class SpitterController {
      
            ...
      
            @RequestMapping(value = "/register", method = GET)
            public String showRegistrationForm(Model model) {
      
                model.addAttribute("spitter", new Spitter());
      
                return "registerForm";
            }
      
            ...
        }
      

      registerForm.jsp

        <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
        <%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
        <%@ page session="false" %>
        <html>
        <head>
            <title>Spitter</title>
            <link rel="stylesheet" type="text/css" href="<c:url value="/resources/style.css" />">
        </head>
        <body>
            <h1>Register</h1>
      
            <sf:form method="POST" commandName="spitter">
      
                First Name:<sf:input path="firstName"/><br/>
                Last Name:<sf:input path="lastName"/><br/>
                Email:<sf:input path="email"/><br/>
                Username:<sf:input path="username"/><br/>
                Password:<sf:password path="password"/><br/>
                <input type="submit" value="Register"/>
            </sf:form>
        </body>
        </html>
      

      (5) <form>标签的commandName属性用来绑定某个model,这需要在Controller中添加这个对应名称的model,否则会报错(这里model的名称为"spitter")

      (6) <input>标签中的path属性用于设置原生html中value的值,例如<sf:input path="firstName"/>代表这个input的值设定为 spitter.firstName

    • 展现错误

      (1) 使用 <sf:errors>

      示例

        <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
        <%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
        <%@ page session="false" %>
        <html>
        <head>
            <title>Spitter</title>
            <link rel="stylesheet" type="text/css" href="<c:url value="/resources/style.css" />">
        </head>
        <body>
            <h1>Register</h1>
      
            <sf:form method="POST" commandName="spitter" action="/spitter/register">         
      
                <sf:label path="firstName" cssErrorClass="error">First Name</sf:label>:
                <sf:input path="firstName" cssErrorClass="error"/>
                <sf:errors path="firstName" element="span" cssClass="error"/>
                <br/>
      
                <sf:label path="lastName" cssErrorClass="error">Last Name</sf:label>:
                <sf:input path="lastName" cssErrorClass="error"/>
                <sf:errors path="lastName" element="span" cssClass="error"/>
                <br/>
      
                <sf:label path="email" cssErrorClass="error">Email</sf:label>:
                <sf:input path="email" cssErrorClass="error"/>
                <sf:errors path="email" element="span" cssClass="error"/>
                <br/>
      
                <sf:label path="username" cssErrorClass="error">Username</sf:label>:
                <sf:input path="username" cssErrorClass="error"/>
                <sf:errors path="username" element="span" cssClass="error"/>
                <br/>
      
                <sf:label path="password" cssErrorClass="error">Password</sf:label>:
                <sf:password path="password" cssErrorClass="error"/>
                <sf:errors path="password" element="span" cssClass="error"/>
                <br/>
      
                <input type="submit" value="Register"/>
            </sf:form>
        </body>
        </html>
      

      <sf:errors>的path属性会绑定model的某个字段,以<sf:errors path="firstName" element="span" cssClass="error"/>为例,它会绑定 spitter.firstName这个字段。如果这个字段有问题,那么则显示错误;否则,不渲染任何内容。

      <sf:errors>的element属性用于确定错误的渲染类型,span代表html中的<span>用于渲染一行;div代表<div>,代表一个块。

      cssClass指定了出现错误时的显示方式,对应的css文件中会有 span.error指定错误时的样式

      style.css

        ...
      
        span.error {
            color: red;
        }
      
        ...
      

      (2) 何时产生错误与产生何种错误信息都在模型对应的类中决定

      示例

        public class Spitter {
      
            ...
      
            @NotNull(message = "{username.size}")
            @Size(min = 5, max = 16, message = "{username.size}")
            private String username;
      
            @NotNull(message = "{password.size}")
            @Size(min = 5, max = 25, message = "{password.size}")
            private String password;
      
            @NotNull(message = "{firstName.size}")
            @Size(min = 2, max = 30, message = "{firstName.size}")
            private String firstName;
      
            @NotNull(message = "{lastName.size}")
            @Size(min = 2, max = 30, message = "{lastName.size}")
            private String lastName;
      
            @NotNull
            @Email(message = "{email.valid}")
            @Size(min = 3, message = "{email.valid}")
            private String email;
      
            ...
        }
      

      当不满足注解中的要求时,会产生错误;错误的信息由每个注解的message属性指定(添加多重校验注解时,每个注解可以对应不同的message);

      当message属性的内容是"xxx"时,则直接错误信息显示为xxx;当message属性的内容是"{xxx}"时,则错误信息从ValidationMessages.properties属性文件中读取;

      ValidationMessages.properties必须叫这个名字,且必须放在根类路径下(即src/main/resources/ValidationMessages.properties);在属性文件中定义message中各种对应的参数

      示例 ValidationMessages.properties

        firstName.size=First name must be between {min} and {max} characters long.
        lastName.size=Last name must be between {min} and {max} characters long.
        username.size=Username must be between {min} and {max} characters long.
        password.size=Password must be between {min} and {max} characters long.
        email.valid=The email address must be valid.
      

      属性文件也可以有占位符{},{min}代表从校验注解上读取min属性的值

      (3) <sf:errors>用来显示额外的错误信息,<sf:input>,<sf:label>同样可以指定发生错误时的显示样式,通过设置 cssError属性

      示例

      registerForm.jsp

        ...
      
        <sf:label path="email" cssErrorClass="error">Email</sf:label>:
        <sf:input path="email" cssErrorClass="error"/>
      
        ...
      

      style.css

        ...
      
        label.error {
            color: red;
        }
      
        input.error {
            background-color: #ffcccc;
        }
      
        ...
      
    • 使用Spring的JSP库(二):Spring的通用标签库

      (1) 使用前要添加声明

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

      (2) 常用的有10个标签 P180

      (3) 代替硬编码 -- <s:message>

      将信息放在属性文件里,使用时只需引用属性文件中的值即可

      示例

      home.jsp

        <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
        <%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
        <%@ page session="false" %>
        <html>
      
        ...
        <body>
            <h1><s:message code="spitter.welcome"/></h1>
      
            ...
        </body>
        </html>
      

      messages.properties

        spitter.welcome=Welcome to Spitter!
      

      为了可以使用属性文件,需要配置信息源,即在JavaConfig文件中添加信息源的Bean

      WebConfig.java

        @Configuration
        @EnableWebMvc
        @ComponentScan("spittr.web")
        public class WebConfig extends WebMvcConfigurerAdapter {
      
            ....
      
            @Bean
            public MessageSource messageSource() {
      
                // Method 1
                ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        
                messageSource.setBasename("/WEB-INF/messages");
                messageSource.setCacheSeconds(10);
                return messageSource;
      
                // Method 2
                /*ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
      
                messageSource.setBasename("messages");
                messageSource.setCacheSeconds(10);
      
                return messageSource;*/
            }
        }
      

      常用的信息源类有两种,一种是ReloadableResourceBundleMessageSource,它从 src/main/webapp开始查找(即web应用的根路径);另一种是ResourceBundleMessageSource,它从src/main开始查找(即根类路径)

    相关文章

      网友评论

          本文标题:chapter06_渲染Web视图_1_创建JSP视图

          本文链接:https://www.haomeiwen.com/subject/kdxddqtx.html