Ssm整合步骤
三层的实现分工:控制层采用springmvc,持久层采用mybatis,分离控制采用spring。
一、 导入所需jar包
二、 搭建工程框架
(一)创建结构化文件包
Com.***.***.controller;
Com.***.***.pojo;
Com.***.***.dao;
Com.***.***.service;
Com.***.***.serviceimpl;
Com.***.***.vo;
(二)准备数据库及日志
1. 准备好数据库以及需要使用的表。
2. 在项目下新建source folder类型的文件夹,装载所有的配置文件。配置数据库连接文件 db.properties。
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=
3. 配置log4j文件
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
(三)使用mybatis逆向工程生成本项目所需的dao包和pojo包文件
另创建一个专门生成项目文件的项目。根据数据库表,配置好相应参数,逆向生成pojo类文件和动态代理文件。方法详见mybatis文档。
(四)加载配置文件
在source folder类型的文件夹中,装载其他所有的配置文件。
1. Dao层 sqlMapConfig.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPEconfiguration
PUBLIC"-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
空文件即可,无需配置。
2. Spring做控制权分离配置 applicationContext
1) Spring装配dao层 applicationContext-dao.xml
A. 配置连接池
<!-- 加载配置文件-->
<context:property-placeholderlocation="classpath:db.properties"/>
<!-- 数据库连接池-->
<bean id="dataSource"class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<propertyname="driverClassName" value="${jdbc.driver}"/>
<property name="url"value="${jdbc.url}"/>
<propertyname="username" value="${jdbc.username}"/>
<propertyname="password" value="${jdbc.password}"/>
<property name="maxActive"value="10"/>
<propertyname="maxIdle" value="5"/>
</bean>
B. 配置sqlSessionFactory,需要设置连接池属性和dao层mybatis配置文件属性
<!-- mapper配置 -->
<!-- 让spring管理sqlsessionfactory -->
<bean id="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<propertyname="dataSource" ref="dataSource"/>
<!-- 加载mybatis的全局配置文件-->
<propertyname="configLocation"value="classpath:sqlMapConfig.xml"/>
</bean>
C. 配置mapper文件扫描
<!-- 配置Mapper扫描配置器 -->
<beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">
<propertyname="basePackage" value="com.***.***.dao"/>
</bean>
D. Example
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="10"/>
<property name="maxIdle" value="5"/>
</bean>
<!-- mapper配置 -->
<!-- 让spring管理sqlsessionfactory使用mybatis和spring整合包中的 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
</bean>
<!-- 配置Mapper扫描配置器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.***.***.dao"/>
</bean>
</beans>
2) Spring装配service层 applicationContext-service.xml
A. 开启注解扫描
B. Example
<?xml version="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<context:component-scan base-package="com.***.***.service"/>
</beans>
3) Spring装配service层事务 applicationContext-trans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS"read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS"read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(*com.***.***.service.*.*(..))"/>
</aop:config>
</beans>
3. 控制层 springmvc.xml
1) 开启扫描@Controller注解类
<context:component-scan base-package=”” />
2) 加载注解驱动
<mvc:annotation-driven />
3) 配置视图解析器
<beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
<propertyname="viewClass"value="org.springframework.web.servlet.view.JstlView"/>
<!-- jsp前缀 -->
<propertyname="prefix" value="/WEB-INF/jsp/"/>
<!-- jsp后缀 -->
<propertyname="suffix" value=".jsp"/>
</bean>
4) 配置自定义的转换器
<bean id="convertService"class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<propertyname="converters">
<set>
<!-- 指定自定义的转换器的全路径的名称 -->
<beanclass="com.***.***.controller.converter.StrConvertToDate"/>
</set>
</property>
</bean>
然后在注解驱动中,注册自定义的转换器。
<mvc:annotation-drivenconversion-service=”convertService” />
同时在相应的包中,配置StrConvertToDate的类文件。
5) 配置文件上传的解析器
<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传的尺寸 5M=5*1024KB*1024Byte-->
<propertyname="maxUploadSize">
<value>5242880</value>
</property>
</bean>
注意:id需要使用官方默认的固定名,不可以自定义或者缺省。
6) example
<?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:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 扫描带Controller注解的类 -->
<context:component-scan base-package="com.***.***.controller"/>
<!-- 加载注解驱动
处理器映射器 处理器适配器
注解适配器 开启json注解
-->
<mvc:annotation-driven conversion-service="convertService" />
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"/>
<!-- jsp前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- jsp后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
<!--
配置自定义的转换器
-->
<bean id="convertService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<!-- 指定自定义的转换器的全路径的名称 -->
<bean class="com.***.***.controller.converter.StrConvertToDate"/>
</set>
</property>
</bean>
<!-- 配置全局的异常处理器 -->
<!-- <bean class="com.***.***.exception.MyExceptionResolver"></bean>-->
<!-- 配置文件上传的解析器
id不能缺少,而且名字不能改变
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传的尺寸 5M=5*1024KB*1024Byte-->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
</beans>
(五)配置web.xml文件
1. 加载spring配置文件的容器
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
2. 配置前端控制器
<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.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--
*.action:映射后缀名为.action结尾的url
/:映射所有,但是不包含jsp
/*:映射所有,也包含了jsp
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
关于前端控制器,url-pattren的配置问题。
不论配置为/或者/*,都将导致css,js,图片等文件进入控制器的请求映射,即产生@RequestMapping(“xxx.css”)的请求,结果产生404报错,所以一般不采用/或者/*。
3. 配置post请求乱码
<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>
4. Example
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"id="WebApp_ID" version="3.0">
<display-name>ssm</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的容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</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.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--
*.action:访问后缀名为.action结尾的
/访问所有,但是不包含jsp
/* 访问所有,也包含了jsp
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置Post请求乱码 -->
<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>
</web-app>
三、 进行业务处理
创建业务处理器类
(一) @Autowired
注入service业务处理类。
(二) @Controller
注解类为后端控制器类
@Controller
public class ItemsController{
……
}
(三) @RequestMapping(value="/list")
1. 声明前端url与某控制器的业务单元的映射
@RequestMapping("/itemsList")
public ModelAndView itemsList(){
……
}
2. 对整个控制器做窄化请求映射设置
窄化请求映射,在请求的路径中加入前置层,防止业务单元重名的问题。
@RequestMapping("/items")
public class ItemsController {
……
@RequestMapping("/itemsList")
public ModelAndViewitemsList(){
……
}
}
注意:在窄化请求的情况下,业务单元的请求映射的值前面需要加上/,否则可能404报错。
3. 请求映射中,设置请求方式
@RequestMapping(value="/itemsList",method=RequestMethod.POST)
在请求映射中,设置多个参数,不可以省略键的名字,否则失去对应关系。
(四) 控制器返回类型
1. ModelAndView
2. String
返回值,可以为1、jsp地址;2、转发或重定向的处理器地址。
1) 重定向
在springmvc中使用重定向的方式,也可以传递参数,但要配合model的addAttribute方法使用。
@RequestMapping("/updateitem")
public String updateItem(Itemsitem,Modelmodel){
//item.setCreatetime(newDate());
itemService.updateItem(item);
model.addAttribute("id",item.getId());
return "redirect:itemEdit.action";
}
2) 转发
public String updateItem(Itemsitem,Modelmodel){
//item.setCreatetime(newDate());
itemService.updateItem(item);
//model.addAttribute("id",item.getId());
//return"redirect:itemEdit.action";
return "forward:itemsList.action";
}
转发或者重定向的相对与绝对路径的写法:路径头不写/是相当路径;路径头写/是绝对路径,绝对路径的定位点为项目。
3. Pojo类型
一般前端使用ajax,处理器传参给前端使,需要返回某个pojo类型。要在参数列表中,需要返回的pojo类前,使用@RequestBody。其作用是完成json格式字符串的装箱为pojo类,以及返回类转换为json对象。
如:
@RequestMapping("/ajaxTest")
@ResponseBody
publicItems testjson(@RequestBody Items items){
System.out.println(items);
returnitems;
}
4. void
使用无返回值类型,将使springmvc失效。
(五) 控制器业务单元参数列表参数类型
注意基本数据类型参数名字或者引用类型参数的属性名和jsp页面name的值的对应关系。
1. 默认可选参数类型
HttpServletRequest
HttpServletResponse
Model
HttpSession
2. 基本数据类型和String类型
业务单元参数数据类型必须和用户请求的源url页面中input框的name值一致。
@RequestMapping("updateitem")
public Stringupdateitem(int id,String name,Float price,String detail){
return"demo";
}
3. pojo类型
用户请求的源url的页面中input框的name值要和业务单元的参数pojo类的属性一致。
@RequestMapping("/updateitem")
public Stringupdateitem(Items items,Model model) throws Exception{
items.setCreatetime(newDate());
itemsService.updateItems(items);
model.addAttribute("id",items.getId());
return"redirect:/items/itemEdit/";
// return"forward:/items/list.action";
}
4. vo类型
用户请求的源url的页面中input框的name值要和业务单元的参数vo类的属性一致。一般vo类的属性会是一个pojo类。所以,input中的name值需要用pojo.field来赋值。如name=”item.name”。
@RequestMapping("/queryitem")
public Stringqueryitem(QueryVo queryVo){
System.out.println(queryVo);
return"success";
}
5. 数组类型
可以直接使用数组如String[],也可以在vo中创建数组属性。
@RequestMapping("/delAll")
// public StringdelAll(QueryVo vo){
public String delAll(String[] ids){
System.out.println(ids);
return "";
}
6. 集合类型
在vo中定义集合。
@RequestMapping(value="/updateAll")
public StringupdateAll(QueryVo vo){
System.out.println(vo);
return "";
}
7. Example
@Controller
public class ItemsController {
@Autowired
private ItemService itemService;
@RequestMapping("/list")
public StringitemsList(Model model){
List<Items>itemlist=itemService.queryAllItems();
System.out.println(itemlist);
model.addAttribute("itemList",itemlist);
return"itemList";
}
}
8. 关于批量修改的传参
在应用参数Vo里面要声明对应pojo的集合的属性。在jsp页面的name里面的值为:属性[下标].属性。
如:
public classQueryVo {
private List<Items> itemlist;
……
}
Jsp页面在forEach循环里需要使用varStatus属性,获得当前迭代的下标。
<c:forEach items="${itemlist }"var="item"varStatus="status">
<input type="hidden"name="itemlist[${status.index}].id"value="${item.id }"/>
……
</c:forEach>
四、 异常处理
Java中异常分为运行期异常和编译期异常。
(一) 自定义异常类
public class MyException extends Exception{
private Stringmessage;
public String getMessage() {
return message;
}
public voidsetMessage(String message){
this.message =message;
}
}
(二) 自定义异常处理器
public class MyExceptionResultor implementsHandlerExceptionResolver {
public ModelAndView resolveException(HttpServletRequestreq, HttpServletResponseres, Object arg2,
Exception exception) {
String msg="";
if(exceptioninstanceofMyException){
msg=((MyException)exception).getMessage();
}else{
msg="系统异常,请联系管理员。";
}
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("msg",msg);
modelAndView.setViewName("errorpage");
return modelAndView;
}
}
(三) 在springmvc.xml中配置全局异常的处理器
<!-- 配置全局异常处理器 -->
<bean class="com.***.***.exception.MyExceptionResultor"></bean>
(四) 测试
@RequestMapping(value="/itemsList")
public ModelAndView itemsList()throws Exception{
int a=1;
if(a==1){
//throw new Exception();
MyException myException=new MyException();
myException.setMessage("资源不见了。");
throwmyException;
}
List<Items> ilist=itemService.queryItems();
ModelAndView mv=new ModelAndView();
mv.addObject("itemlist",ilist);
mv.setViewName("itemList");
return mv;
}
五、 上传图片
(一) 配置tomcat虚拟服务器
在tomcat的conf文件夹中找到server.xml。
在<host></host>标签中,添加配置。
<Hostname="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<ContextdocBase="e:\virtualServer" path="/images"reloadable="false" />
……
</Host>
(二) 导入jar包
(三) 在前端的jsp页面的form表单中,需要添加属性。enctype="multipart/form-data"
<form action="…" enctype="multipart/form-data"method="post">
(四) 配置springmvc.xml的文件上传解析器。
如前所述。
<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传的尺寸 5M=5*1024KB*1024Byte-->
<propertyname="maxUploadSize">
<value>5242880</value>
</property>
</bean>
(五) 编写业务处理单元
@RequestMapping("/updateitem")
public String updateItem(MultipartFilepictureFile,Itemsitem,Modelmodel)throwsException{
//参数MultipartFile的名字要和jsp页面中上传文件的input框中的name值一致。
//1,获取图片的抽象路径名称的String
String oriFileName=pictureFile.getOriginalFilename();
//2,使用随机字符串加上上传文件的扩展名组成传入的文件的新名称。
String newFileName=UUID.randomUUID().toString()+oriFileName.lastIndexOf(".");
//3,将文件保存到tomcat虚拟服务器端
pictureFile.transferTo(newFile("e:\\virtualServer\\"+newFileName));
//4,将图片路径保存到数据库
item.setPic(newFileName);
//item.setCreatetime(newDate());
itemService.updateItem(item);
//model.addAttribute("id",item.getId());
//return"redirect:itemEdit.action";
return "forward:itemEdit.action";
}
六、 Json的使用
(一) 配置springmvc.xml的json注解。
<mvc:annotation-drivenconversion-service="convertService" />
开启mvc的注解驱动包含了开启json注解支持。
(二) Jsp端juery的ajax方法传值
function testJson(){
$.ajax({
type:"post",
url:"${pageContext.request.contextPath}/items/jsonAjax.action",
contentType:"application/json;charset='utf-8'",
data:'{"name":"哈哈","id":"99"}',
success:function(data){
alert(data.name+data.id);
}
});
}
(三) 处理器业务单元
@RequestMapping("/jsonAjax")
//@ResponseBydy将pojo对象转换成json对象发送到前端页面
@ResponseBody
public Items testJson(@RequestBody Items item){
//@RequestBody 将请求体中的json格式的内容转换为pojo类型。
System.out.println(item);
returnitem;
}
七、 Springmvc实现restful
(一) 设置web.xml的前端控制器
将前端控制器的映射层次设置为/
<url-pattern>/</url-pattern>
(二) 设置业务单元中的@RequestMapping的地址以及参数对应形式和开启参数restful风格需要的注解
@RequestMapping("/itemEdit/{aa}/{bb}")
//url路径中参数的形参要和业务单元传入的参数的注解值保持一致,不需要和前端url实际路径中的参数名字一致,但多个传值情况要保证值的对应关系。多个参数值,则设置多个{}和对应的业务单元参数。
//@RequestMapping("/itemEdit/{aa}/{bb}
//@PathVariable("aa")int aa,@PathVariable("bb") Stringbb......
public String itemEdit(@PathVariable("aa")Integeraa,@PathVariable("bb") Stringbb,HttpServletRequest request,HttpServletResponse response,Modelmodel,HttpSessionhttpSession) throws Exception{
Items item=itemService.findItemById(aa);
model.addAttribute("item",item);
return "editItem";
}
(三) 解决实现restful风格后,静态资源无法加载问题
1. 简单的方法。首先,将静态资源,如css、js、images等放到WEB-INF下面一个文件夹中。然后,在springmvc.xml中配置静态资源路径。
<!-- restful风格下设置静态资源路径 -->
<mvc:resourcesmapping="/static/**"location="/WEB-INF/static/"cache-period="31556926"/>
2. 复杂的方法。使用默认的servlet
1) 在web.xml中配置需要加载的静态资源的url路径。
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
<url-pattern>*.jss</url-pattern>
<url-pattern>*.png</url-pattern>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
2) 在springmvc.xml中开启默认servlet的处理器,获得对于相应静态资源的访问。
<mvc:default-servlet-handler/>
3) 采用这种方式,需要将静态资源放在webroot根目录下或根目录下的文件夹(非WEB-INF)中。
八、 拦截器
(一) 建立用于创建拦截器的结构化包
Com.***.***.interceptor
(二) 自定义interceptor
public class MyInterceptor1 implements HandlerInterceptor{
//执行时机,controller执行ModelAndView并且已经返回
//场景,记录用户操作日志,记录用户登录的ip和时间
public voidafterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,Exception arg3)
throws Exception {
System.out.println("afterCompletion");
}
//执行时机,controller已经执行,ModelAndView还没有返回。
//场景,一般用于设置全局的数据处理。
public voidpostHandle(HttpServletRequest arg0, HttpServletResponsearg1, Objectarg2,ModelAndViewarg3)
throws Exception {
System.out.println("postHandle");
}
//返回boolean类型,如果为false,则拦截,否则放行。
//执行时机,在controller方法还没有执行,ModelAndView还没有返回的时候。
//使用场景,权限验证,用户登录。
public booleanpreHandle(HttpServletRequest arg0, HttpServletResponsearg1, Objectarg2)throwsException {
System.out.println("preHandle");
return true;
}
}
(三) 在springmvc.xml配置拦截器
<!-- 配置拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 配置拦截路径 -->
<mvc:mappingpath="/**"></mvc:mapping>
<beanclass="com.***.***.intercepter.MyInterceptor1"></bean>
</mvc:interceptor>
</mvc:interceptors>
多个拦截器的情况下,preHandle的执行顺序按照springmvc.xml配置顺序执行。
(四) 用户登录案例
1. 编写用户登录业务单元
@RequestMapping("/checklogin")
public String checkLogin(UserjspUser,Modelmodel,HttpServletRequestrequest){
User user=userService.findUser(jspUser);
System.out.println(user);
if(user==null){
model.addAttribute("msg","用户名或密码错误");
return"login";
}else{
HttpSession session=request.getSession();
if(user.getUsername()!=null){
session.setAttribute("username",user.getUsername());
return"redirect:../items/itemsList";
}else{
model.addAttribute("msg","用户名不能为空");
return"login";
}
}
}
2. 自定义LoginInterceptor
public class LoginInterceptor implements HandlerInterceptor{
public voidafterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,Exception arg3)
throws Exception {
}
public voidpostHandle(HttpServletRequest arg0, HttpServletResponsearg1, Objectarg2,ModelAndViewarg3)
throws Exception {
}
public booleanpreHandle(HttpServletRequest request, HttpServletResponseresponse, Objectarg2)throwsException {
if(request.getRequestURI().indexOf("login")>0){
return true;
}
if(request.getSession().getAttribute("username")!=null){
return true;
}
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
return false;
}
}
3. 配置springmvc.xml用户登录拦截器
<mvc:interceptor>
<!-- 配置拦截路径 -->
<mvc:mappingpath="/**"></mvc:mapping>
<beanclass="com.***.***.intercepter.LoginInterceptor"></bean>
</mvc:interceptor>
4. 关于用户退出的设置
1) 做鼠标点击退出事件
<script>
function loginout(){
window.location.href="../user/loginout";
}
</script>
2) 编写退出业务单元
@RequestMapping("/loginout")
public String loginout(HttpServletRequestrequest,HttpServletResponseresponse){
// 销毁session
request.getSession().invalidate();
// 跳转到登录页面
return "redirect:login";
}