SSM框架功能总结
参考代码:mybatis整合spring整合springmvc代码及注解
0.配置文件:
SqlMapConfig.xml
applicationContext.xml
applicationContext-service.xml
applicationContext-transaction.xml
springmvc.xml
web.xml:加载spring容器,配置前端控制器dispatcher
1.spring与struts2的区别:
1.springmvc基于方法开发,struts2基于类开发。
springMvc将url和controller方法映射,映射成功后springMvc生成一个handler对象,兑仓只包含一个method方法
方法执行结束,形参数据销毁。
springMvc开发类似于service开发,更符合开发习惯,利于管理。
2.springMvc可以进行单利开发,并且建议使用单利开发,struts2通过类的成员变量接收参数,无法使用单例,只能使用多例。
3.经测试:struts2速度慢,在于使用struts标签,如果使用struts2建议使用jstl。
2.参数转换器(绑定器):
在springmvc.xml中定义参数转换器<bean id="cinversionService">
配置绑定器还需要在适配器中添加conversion-service="conversionService"
创建装换器类:CustomDateConverter 继承Converter<String, Date>
public class CustomDateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
//实现日期串转换为日期类型
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return simpleDateFormat.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
//如果参数绑定失败就返回空
return null;
}
3.静态资源解析器:
在springmvc.xml中对解析器进行配置
静态资源解析js,css,img
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:resources location="/img/" mapping="/img/**"/>
在springmvc.xml中配置静态资源解析器后,可以web中对静态资源进行访问。
4.拦截器:
在springmvc.xml中配置全局拦截器,拦截器的顺序需要注意
<mvc:interceptors>
<!-- 多个拦截器,顺序执行 -->
<mvc:interceptor>
<!-- 登录认证拦截器 -->
<mvc:mapping path="/**"/>
<bean class="ssm.interceptor.LoginInterceptor"/>
</mvc:interceptor>
<mvc:interceptor>
<!-- /**表示所有url包括所有路径 -->
<mvc:mapping path="/**"/>
<bean class="ssm.interceptor.HandlerInterceptor1"/>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="ssm.interceptor.HandlerInterceptor2"/>
</mvc:interceptor>
</mvc:interceptors>
5.参数校验:
服务端校验:
-
控制层 controller:校验页面请求的参数的合法性。在服务端控制层controller校验,不区分客户端类型(浏览器,手机客户端,远程调用。。。)
-
业务层 service(使用较多):主要校验关键业务参数,仅限于service接口中使用的参数。
-
持久层 dao:一般不校验。
1.配置校验器
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- 校验器 -->
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
<property name="validationMessageSource" ref="messageSource"/>
</bean>
</校验错误信息配置文件>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- 资源文件 -->
<property name="basenames">
<list>
<value>CustomValidationMessages</value>
</list>
</property>
<!-- 资源文件编码格式 -->
<property name="fileEncodings" value="utf-8"/>
<!-- 对资源文件内容缓存时间,单位秒 -->
<property name="cacheSeconds" value="120"/>
</bean>
2.配置校验器还需要在适配器中添加
validator="validator"
3.校验错误信息的配置文件:CustomValidationMessages.properties中添加
items.name.length.error=请输入1到30个字符的商品名称
items.createtime.isNULL = 请输入商品的生产日期
4.校验器的实现类:
public interface ValidGroup1 {
//此分组只校验商品名称长度
}
校验类只是一个接口,不实现任何方法,是对校验的分组,可以定义多个。
5.校验器的使用:
在pojo的属性上添加校验器:
//校验名称:名称在1-30之间
//group:此校验属于哪一个分组,groups可以定义多个分组
@Size(min = 1,max = 10,message = "{items.name.length.error}",groups={ValidGroup1.class})
//非空校验
@NotNull(message = "{items.createtime.isNULL}")
private Date createtime;
6.全局异常处理器:
在springmvc.xml中配置全局异常处理器,只要所指向的类实现啦HandlerExceptionResolver接口,就是全局异常处理器。
<bean class="ssm.exception.CustomExceptionResolver"/>
全局异常处理器的class类实现:
创建系统异常类 CustomException 继承 Exception
创建全局异常处理器 CustomExceptionResolver 继承 HandlerExceptionResolver
如果是系统自定异常,直接取出异常,输出
如果是为止错误,将会跳转到错误显示页面,并输出错误信息。
7.文件上传配置:
在springmvc.xml中配置
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺度为5MB -->
<property name="maxUploadSize" value="1024000"/>
</bean>
8.参数绑定
1.参数绑定:
客户端请求key/value数据,经过参数绑定,将key/value数据绑定到controller方法的形参上
在参数绑定过程中,如果遇到下面的类型,直接进行绑定
2.1HttpServletRequest
通过request对象获取请求信息
2.2HTTPServletResponse
通过response处理响应信息
2.3HTTPSession
通过session对象得到session中存放的对象
2.4Model/ModelMap
Model是一个接口,modelMap是一个接口实现,
作用相同,将Model数据(model里面就是一个map)填充到request域
controller形参还支持简单类型,Integer ,String等
通过@RequestParam对简单类型参数进行绑定
@RequestParam(value = "id",required = true) Integer items_id
2.pojo绑定:
页面中input的name和controller的pojo形参属性名称一致,就会将页面中的数据绑定到pojo
public String editItemsSubmit(Integer id,ItemsCustom itemsCustom)throws Exception {
//调用servlet更新商品信息,页面需要将商品信息传入到此方法
itemsService.updateItemsById(id,itemsCustom);
9.乱码解决方法:
post乱码:
在web.xml中添加过滤器:
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
10.controller的返回值:
1.返回modelAndView
return modelAndView("");
2.返回string
return "";
3.返回void
使用request转向页面
request.getRequsetDispatcher("页面路径").forward(request,response);
使用request重定向页面
response.sedRedirect("url")
使用request定制响应结果,如:响应json数据
response.sedCharacterEncoding("utf-8");
response.sedContentType("application/json;charset=utf-8");
response.getWriter().writ("json串");
11.数据回显:
什么是数据回显:
数据提交后,如果出现错误,将刚才提交的数据回显到刚才提交的页面
......
12.RESTful:
1.什么是RESTful
- RESTful是目前最流行的一种互联网软件架构。结构清晰,符合标准,易于理解,扩展方便,所以越来越多网站应用
- 是一个开发理念,是对http的很好的诠释。
- HTTP协议里,有四个基本操作:GET:获取资源
POST:新建资源
PUT:更新资源
DELETE:删除资源
2.RESTful的配置:
配置RESTful理念的spring前端控制器:
<!-- spring前端控制器 REST配置 -->
<servlet>
<servlet-name>dispatcher_rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher_rest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
13.json:
请求的json串,输出json串
function requestJson1() {
$.ajax({
type:'post',
url:'${pageContext.request.contextPath}/requestJson1.action',
contentType:'application/json;charset=utf-8',
//数据格式是json串
data:'{"name":"手机","price":999}',
success:function (data) {//返回json结果
alert(data.name);
}
})
}
请求key/value,输出json
function requestJson2() {
$.ajax({
type:'post',
url:'${pageContext.request.contextPath}/requestJson2.action',
//请求的是key/value值了不需要指定contentType,默认是key/value类型
//contentType:'application/json;charset=utf-8',
//数据格式是key/value
data:'name=手机&price=999',
success:function (data) {//返回json结果
alert(data.name);
}
})
}