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">
<mvc:annotation-driven></mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<context:component-scan base-package="cn.worktogether.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
<?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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<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:springmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<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>
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.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
- Transform the Service layer
- 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
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
- 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>
<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
- Spring MVC提供对REST的支持
- Controler方法做如下改动
- @RequestMapping(value=”/view/{id}”)
- public String add(@PathVariable Integer id)
Spring文件上传
- MultipartResolver接口
- 用于处理上传请求,将上传请求包装成可以直接获取文件的数据
- 两个实现类
- StandardServletMultipartResolver
- 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);
}
}