Spring MVC related miscellaneous knowledge record - 20170326 lesson preparation notes

Spring MVC+Spring+JDBC framework construction

  • add jar file
  • configuration file
    • Spring configuration file - applicationContext-jdbc.xml
    • If there are multiple subcontracts, you can write them in several sentences
        <context:component-scan package="要扫描的包的绝对路径" />

    • Spring MVC configuration file - springmvc-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    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)的注解功能 -->
        <mvc:annotation-driven></mvc:annotation-driven>
        <!-- 完成Controller返回(return)的逻辑路径名称的拼接
        InternalResourceViewResolver:专门用于JSP或HTML路径解析的 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <!-- prefix:前缀
                    之所以要放到WEB-INF下,是为了提高网站访问的安全性
                    因为WEB-INF下的文件无法通过浏览器直接访问
                      -->
                <property name="prefix" value="/WEB-INF/pages/"></property>
                <!-- 后缀不能是.html,只能是.jsp -->
                <property name="suffix" value=".jsp"></property>
        </bean>
        <context:component-scan base-package="cn.worktogether.controller">
                <!-- 由于Spring与Spring MVC均使用同一种方法扫描Bean,将Bean实例化到IoC容器中
                所以,在写扫描时,注意不要重复扫描!可使用过滤的方式,指定扫描的注解来解决重复扫描问题 -->
                <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>

</beans>

    • web.xml
       <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>worktogether2</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- Spring IoC容器的配置文件位置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- log4配置文件位置 -->
  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
  </context-param>
  <!-- 用于在项目启动时加载Spring Ioc容器的监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 用于启动log4j的监听器 -->
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
  <!-- SpringMVC启动的配置 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- spring MVC的配置文件读取 -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc-config.xml</param-value>
    </init-param>
    <!-- 让服务器启动时就加载 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!-- 指定任何请求到这个项目的链接首先接给DispatherServlet -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- 解决中文乱码 -->
  <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>
  </filter>
  <filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


</web-app>

    • database.properties
driver=com.mysql.jdbc.Driver
#在和mysql传递数据的过程中,使用unicode编码格式,并且字符集设置为utf-8
url=jdbc:mysql://127.0.0.1:3306/worktogether?useUnicode=true&characterEncoding=utf-8
user=mm
password=123456

    • log4j.properties
##################################################################
#基本配置:输出等说明
##################################################################
log4j.rootLogger=DEBUG,CONSOLE,File
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.cn.smbms.dao=debug
log4j.logger.com.ibatis=debug 
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug 
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug 
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug 
log4j.logger.java.sql.Connection=debug 
log4j.logger.java.sql.Statement=debug 
log4j.logger.java.sql.PreparedStatement=debug 
log4j.logger.java.sql.ResultSet=debug 
log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug

######################################################################################
# Console Appender  控制台输出说明
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %m %d  - %c%n


######################################################################################
# DailyRolling File  文件输出说明
######################################################################################
log4j.appender.File=org.apache.log4j.DailyRollingFileAppender
log4j.appender.File.DatePattern=yyyy-MM-dd
log4j.appender.File.File=log.log
log4j.appender.File.Append=true
log4j.appender.File.Threshold=info
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n


log4j.logger.com.opensymphony.xwork2=error  
  • Transform the DAO layer
    • Repository
  • Transform the Service layer
    • @Service/@Resource
  • Transform the Controller layer
    • Create UserController to implement business functions
  • Transform the View layer
    • static resource file
    • User page

Spring MVC jump

  • Defaults to in-server forwarding. You can also use the forward: prefix
    • Forward information, not re-request
  • If redirection is required, add "redirect:" prefix to return
    • Resend URL request

Static resource references (JS, CSS)

  • Method 1: Add the following code to SpringMVC-servlet.xml
    • The advantage of this is that you can put all static resources under the WEB-INF folder
    • May need a general folder (statics is used in the code below) to put all resources below
<mvc:resources location="/WEB-INF/statics/" mapping="/**" />
  • Method 2: Add the following code to SpringMVC-servlet.xml
    • The advantage of this is that the existing static resource files do not need to be moved, which is suitable for project upgrades.
    • Static resources cannot be under WEB-INF
    • Need to be used in conjunction with, otherwise invalid
<mvc:default-servlet-handler/>

exception handling

  • HandlerExceptionResolver
    • resolveException()
  • local exception handling
    • Can only handle exceptions in the specified Controller
    • @ExceptionHandler(value={RuntimeException.class}), specified in front of the exception handling method
  • global exception handling
    • Unified handling of all exceptions
    • Configure SimpleMappingExceptionResolver
      • When an exception occurs, use the corresponding view to report the exception
    <!-- 配置全局异常处理器 -->
        <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
                <property name="exceptionMappings">
                    <props>
                        <!--    指定RuntimeException由叫“error”的逻辑视图来处理 -->
                        <prop key="java.lang.RuntimeException">error</prop>
                    </props>
                </property>
        </bean>

Date type conversion

  • Spring MVC no string to date type conversion
    • Error: BindingException
    • Write @DateTimeFormat(pattern=”yyyy-MM-dd”) before the private property in the entity class

Spring MVC form tag usage

  • import tag library
    • <%@ taglib prefix=”fm” uri=”http://www.springframework.org/tags/form” %>

Spring MVC common form tags

name illustrate
form element
text box label
Password box label
hidden box label
Multiline input box label
radio button label
checkbox label
dropdown list label
Check the corresponding error message

- Label
- modelAttribute
- Specifies the model attribute to be bound, the default is command
- action
- can not be specified, the jumped path will be automatically applied as the specified path
-
- path: equivalent to the original name attribute
- cssClass: corresponding to the CSS style class name
- cssErrorClass: commends the CSS style used when reporting an error after the form is submitted
- cssStyle: corresponds to the style attribute
- htmlEscape: whether the bound form attribute value should be converted to HTML special characters, the default is true

Server-side data validation

  • JSR303
    • The standard framework provided by Java for Bean data validity verification
    • Spring MVC supports JSR303
    • JSR303 specifies validation rules by annotating annotations on bean properties.
    • Spring itself does not provide an implementation of JSR 303
    • Implementer: Hibernate Validator
  • JSR303 Constraints
    • Use startup validation annotations
    • In the processing method of the Controller, the declared entity class parameter must be marked with @Valid to implement the verification
    • The entity parameter must be followed by a BindingResult parameter, otherwise an exception will be thrown directly.
    • Then output the error message on the jsp page
    • The error message is customized using the message attribute of the annotation
The processing code of the Controller is as follows:
    public String addSave(@Valid Users user,BindingResult err){
        if(err.hasError()){
            return "user/add";
        }
        ...
    }
The processing code of jsp is as follows:
    <fm:errors path="userName" />
constraint illustrate
@Null The annotated element must be null
@NotNull The annotated element must not be null
@NotEmpty The annotated element is not null and not empty (for collections)
@NotBlind The annotated string is not Null and the length is not 0 after being trimmed
@AssertTrue The annotated element must be True
@AssertFalse The annotated element must be False
@Min(value) Annotated numbers and strings whose value must be less than or equal to the specified minimum value
@Max(value) Annotated numbers and strings, whose value must be greater than or equal to the specified maximum value
@DecimalMin(vlaue) The annotated element must be a number whose value must be less than or equal to the specified minimum value
@DecimalMax(value) The annotated element must be a number, and its value must be greater than or equal to the specified maximum value
@Size(min,max) The length of the annotated collection must be within the specified range
@Length(min,max) The length of the annotated string must be within the specified range
@Digits(integer,fraction) The annotated element must be a number and its value must be in the acceptable range (integer is integer precision, fraction is fractional precision)
@Range(min,max) Check if a number is in range
@Past Annotated Date and Calendar must be a past date
@Future Annotated Date and Calendar must be a future date
@Pattern The annotated string matches a regular expression
@Email The annotated string conforms to the email format. If it is null, it will pass the verification.

REST style

  • Representational State Transfer, representational state transfer, is a software architectural style
  • View/modify/delete the corresponding traditional URL and REST style URL corresponding style
    • /userview.html?id=12=====>/user/view/12
    • /userdelete.html?id=12====>/user/view/12
  • request method
    • GET
    • POST
    • DELETE
    • PUT
  • Spring MVC提供对REST的支持
    • Controler方法做如下改动
      • @RequestMapping(value=”/view/{id}”)
      • public String add(@PathVariable Integer id)

Spring文件上传

  • MultipartResolver接口
    • 用于处理上传请求,将上传请求包装成可以直接获取文件的数据
  • 两个实现类
    • StandardServletMultipartResolver
      • 使用了Servlet3.0标准的上传方式
    • CommonsMultipartREsolver
      • 使用了Apache的commons-fileupload来完成具体的上传操作
  • 实现步骤
  • 服务器端:
配置MultipartResolver(springmvc-config.xml)
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
Controller处理:多文件上传需要把MultipartFile改为数组,并在前面加上@RequestParam注解即可,必须加这个注解,否则会报不能实例化数组的错误
public String add(@RequestParam(value="imgPath"),required=false MultiPartFile upload,HttpSession session){
    //判断文件是否为空
    if(!upload.isEmpty()){
        //获得文件目标路径
        String path=session.getServletContext().getRealPath("/upload");
        //获得原文件名
        String oldFileName=upload.getOriginalFileName();
        //获得文件后缀
        String suffix=FilenameUtils.getExtension(oldFileName);
        //获得文件大小
        int fileSize=upload.getSize();
        //创建新的文件名
        String fileName=System.currentTimeMillis()+RandomUtils.nextInt(1000000);
        //创建服务器上的新文件
        File newFile=new File(path,fileName);
        //如果文件不存在,则创建
        if(!newFile.exists()){
            newFile.mkdirs();
        }
        //将上传的文件保存到磁盘上。
        upload.transferTo(newFile);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325384752&siteId=291194637