1.springmvc与mybatis整合配置文件目录及web.xml中配置
<?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/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>springmvc-web</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:spring/applicationContext*.xml</param-value>
</context-param>
<!-- 配置修复乱码 -->
<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>
<!-- 使用监听器加载spring -->
<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>
<!-- 指定springMVC的配置文件 -->
<!-- 如果不指定,则为/WEB-INF/${servlet-name}-servlet.xml -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<!-- <servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping> -->
<!-- 配置支持restful -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2. sapplicationContext-dao.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">
<!-- 加载配置文件 -->
<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:mybatis/SqlMapConfig.xml" />
</bean>
<!-- 配置Mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.xiaoge.mapper" />
</bean>
</beans>
3.业务层及事务管理配置
<?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">
<!-- 配置service扫描包 -->
<context:component-scan base-package="cn.xiaoge.service" />
</beans>
<?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:method name="query*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.xiaoge.service.*.*(..))" />
</aop:config>
</beans>
4.配置表现层
<?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: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://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配置controller扫描包 -->
<context:component-scan base-package="cn.xiaoge.controller" />
<!-- 配置注解驱动 -->
<!-- <mvc:annotation-driven /> -->
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:annotation-driven conversion-service="conversionService" />
<!-- 转换器配置 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="cn.xiaoge.converter.DateConverter" />
</set>
</property>
</bean>
<!-- 异常处理器 -->
<bean id="handlerExceptionResolver" class="cn.xiaoge.exception.CustomExceptionResolver" />
<!-- 文件上传,id必须设置为multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize" value="1048576" />
</bean>
<!--注解适配器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
</list>
</property>
</bean> -->
<mvc:default-servlet-handler/>
<!-- <mvc:resources location="/js/" mapping="/js/**"/> -->
<!-- 配置拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="cn.xiaoge.interceptor.HandlerInterceptor1"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="cn.xiaoge.interceptor.HandlerInterceptor2"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/item/**"/>
<bean class="cn.xiaoge.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>
5. web层处理数据 demo
package cn.xiaoge.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import cn.xiaoge.domain.Item;
import cn.xiaoge.domain.QueryVo;
import cn.xiaoge.exception.CustomerException;
import cn.xiaoge.service.ItemService;
@Controller
@RequestMapping("item")
public class ItemController {
@Autowired
private ItemService itemService;
/***
* 查询所有项目
*
* @return
* @throws Exception
*/
@RequestMapping(value = "/itemList.action", method = { RequestMethod.POST, RequestMethod.GET })
public ModelAndView itemList() throws Exception {
/*if(true){
throw new CustomerException("这是自定义异常");
}*/
//设置运行时异常
/*int i = 1/0;*/
List<Item> list = itemService.queryItemList();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("itemList", list);
modelAndView.setViewName("itemList");
return modelAndView;
}
/***
* 修改指定的项目
*
*/
@RequestMapping("/itemEdit.action")
public ModelAndView itemEdit(@RequestParam(value = "itemId", defaultValue = "2", required = true) Integer id) {
// 根据项目id查询项目
Item item = itemService.queryItemById(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("item", item);
modelAndView.setViewName("itemEdit");
return modelAndView;
}
/*
* //根据条件查询,根据字符串数组接收参数
*
* @RequestMapping("/queryItem.action") public ModelAndView queryItem(Item
* item,String[] ids){ List<Item> list =
* itemService.queryItemByCondition(item); ModelAndView modelAndView = new
* ModelAndView(); modelAndView.addObject("itemList",list);
* modelAndView.setViewName("itemList2"); return modelAndView; }
*/
// 用整数数组接收参数
/*
* @RequestMapping("/queryItem.action") public ModelAndView queryItem(Item
* item,Integer[] ids){ List<Item> list =
* itemService.queryItemByCondition(item); ModelAndView modelAndView = new
* ModelAndView(); modelAndView.addObject("itemList",list);
* modelAndView.setViewName("itemList2"); return modelAndView; }
*/
/*
* @RequestMapping("/queryItem.action") public ModelAndView
* queryItem(QueryVo queryVo){ List<Item> list =
* itemService.queryItemByCondition(queryVo.getItem()); ModelAndView
* modelAndView = new ModelAndView();
* modelAndView.addObject("itemList",list);
* modelAndView.setViewName("itemList2"); return modelAndView; }
*/
@RequestMapping(value = "/queryItem.action")
public String queryItem(QueryVo queryVo) {
List<Item> list = queryVo.getItemList();
if (list != null) {
for (Item item : list) {
System.out.println(item);
}
}
return "success";
}
// 更新数据,更新数据后,返回到商品列表页面
@RequestMapping("/updateItem.action")
public String updateItem(Item item, Model model, HttpServletRequest request, HttpServletResponse response,MultipartFile pictureFile) throws Exception {
//获取随机的文件名
String filename = UUID.randomUUID().toString();
//获取原始文件名
String realname = pictureFile.getOriginalFilename();
//获取原始文件的后缀名
String extname = realname.substring(realname.lastIndexOf("."));
filename += extname;
//上传文件
pictureFile.transferTo(new File("D:\\Jide\\temp\\pic\\"+filename));
//设置文件名到item中,进行更新
item.setPic(filename);
try {
itemService.updateItem(item);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return "redirect:/item/itemList.action";
}
//实现效果:完成后,重定向到商品列表界面
/*@RequestMapping("/updateItem.action")
public void updateItem(Item item, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
itemService.updateItem(item);
} catch (Exception e) {
e.printStackTrace();
}
String contextPath = request.getContextPath();
response.sendRedirect(contextPath+"/item/itemList.action");
}*/
//实现效果:修改完成后,转发到商品详情页面
/*@RequestMapping("/updateItem.action")
public void updateItem(Item item, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
itemService.updateItem(item);
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("item", item);
request.getRequestDispatcher("/WEB-INF/jsp/itemDetails.jsp").forward(request, response);
}*/
//测试json
@RequestMapping("/jsonTest.action")
@ResponseBody
public Item jsonTest(@RequestBody()Item item){
return item;
}
//测试restful
@RequestMapping("queryItem/{itemId}")
@ResponseBody
public Item queryItemById(@PathVariable(value="itemId") Integer id){
Item item = itemService.queryItemById(id);
return item;
}
}