标签:
第一天:注解开发基础(springmvc入门)1、管理员维护商品信息
<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> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping>
<init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param>
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
public class ItemList1 implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { //商品列表 List<Items> itemsList = new ArrayList<Items>(); Items items_1 = new Items(); items_1.setName("联想笔记本"); items_1.setPrice(6000f); items_1.setDetail("ThinkPad T430 联想笔记本电脑!"); Items items_2 = new Items(); items_2.setName("苹果手机"); items_2.setPrice(5000f); items_2.setDetail("iphone6苹果手机!"); itemsList.add(items_1); itemsList.add(items_2); //创建modelAndView准备填充数据、设置视图 ModelAndView modelAndView = new ModelAndView(); //填充数据 modelAndView.addObject("itemsList", itemsList); //视图 modelAndView.setViewName("order/itemsList"); return modelAndView; } }
<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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 处理器映射器 --> <!-- 根据bean的name进行查找Handler 将action的url配置在bean的name中 --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<!-- controller配置 --> <bean name="/items1.action" id="itemList1" class="cn.itcast.springmvc.controller.first.ItemList1"/>
<!-- ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>查询商品列表</title> </head> <body> 商品列表: <table width="100%" border=1> <tr> <td>商品名称</td> <td>商品价格</td> <td>商品描述</td> </tr> <c:forEach items="${itemsList }" var="item"> <tr> <td>${item.name }</td> <td>${item.price }</td> <td>${item.detail }</td> </tr> </c:forEach> </table> </body> </html>
<!—beanName Url映射器 --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!—简单url映射 --> <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/items1.action">controller的bean id</prop> <prop key="/items2.action">controller的bean id</prop> </props> </property> </bean>
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/>
public class ItemList2 implements HttpRequestHandler { @Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 商品列表 List<Items> itemsList = new ArrayList<Items>(); Items items_1 = new Items(); items_1.setName("联想笔记本"); items_1.setPrice(6000f); items_1.setDetail("ThinkPad T430 联想笔记本电脑!"); Items items_2 = new Items(); items_2.setName("苹果手机"); items_2.setPrice(5000f); items_2.setDetail("iphone5 苹果手机!"); itemsList.add(items_1); itemsList.add(items_2); // 填充数据 request.setAttribute("itemsList", itemsList); // 视图 request.getRequestDispatcher("/WEB-INF/jsp/order/itemsList.jsp").forward(request, response); } }
<!--注解映射器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<!--注解适配器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
@Controller public class ItemList3 { @RequestMapping("/queryItem.action") public ModelAndView queryItem() { // 商品列表 List<Items> itemsList = new ArrayList<Items>(); Items items_1 = new Items(); items_1.setName("联想笔记本"); items_1.setPrice(6000f); items_1.setDetail("ThinkPad T430 联想笔记本电脑!"); Items items_2 = new Items(); items_2.setName("苹果手机"); items_2.setPrice(5000f); items_2.setDetail("iphone6苹果手机!"); itemsList.add(items_1); itemsList.add(items_2); // 创建modelAndView准备填充数据、设置视图 ModelAndView modelAndView = new ModelAndView(); // 填充数据 modelAndView.addObject("itemsList", itemsList); // 视图 modelAndView.setViewName("order/itemsList"); return modelAndView; } }
<!-- 扫描controller注解,多个包中间使用半角逗号分隔 --> <context:component-scan base-package="cn.itcast.springmvc.controller.first"/>
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!—使用自动扫描器时,mapper.xml文件如果和mapper.java接口在一个目录则此处不用定义mappers --> <mappers> <package name="cn.itcast.ssm.mapper" /> </mappers> </configuration>
<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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.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="30"/> <property name="maxIdle" value="5"/> </bean> <!-- 让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.itcast.springmvc.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> </beans>
4.3.5 ItemsMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.itcast.ssm.mapper.ItemsMapper"> <!-- sql片段 --> <!-- 商品查询条件 --> <sql id="query_items_where"> <if test="items!=null"> <if test="items.name!=null and items.name!=''"> and items.name like '%${items.name}%' </if> </if> </sql> <!-- 查询商品信息 --> <select id="findItemsList" parameterType="queryVo" resultType="items"> select * from items <where> <include refid="query_items_where"/> </where> </select> </mapper>
public interface ItemsMapper { //商品列表 public List<Items> findItemsList(QueryVo queryVo) throws Exception; }
<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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.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(* cn.itcast.springmvc.service.impl.*.*(..))"/> </aop:config> </beans>
public interface OrderService { //商品查询列表 public List<Items> findItemsList(QueryVo queryVo)throws Exception; }
@Autowired private ItemsMapper itemsMapper;
@Override public List<Items> findItemsList(QueryVo queryVo) throws Exception { //查询商品信息 return itemsMapper.findItemsList(queryVo); } }
<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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 扫描controller注解,多个包中间使用半角逗号分隔 --> <context:component-scan base-package="cn.itcast.ssm.controller"/> <!--注解映射器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> <!--注解适配器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> <!-- ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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</display-name> <!-- 加载spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/spring/applicationContext.xml,/WEB-INF/classes/spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 解决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> <!-- springmvc的前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <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> </web-app>
@Controller public class OrderController { @Autowired private OrderService orderService; @RequestMapping("/queryItem.action") public ModelAndView queryItem() throws Exception { // 商品列表 List<Items> itemsList = orderService.findItemsList(null); // 创建modelAndView准备填充数据、设置视图 ModelAndView modelAndView = new ModelAndView(); // 填充数据 modelAndView.addObject("itemsList", itemsList); // 视图 modelAndView.setViewName("order/itemsList"); return modelAndView; } }
http://localhost:8080/springmvc_mybatis/queryItem.action
5.2.2 service
//根据id查询商品信息 public Items findItemById(int id) throws Exception; //修改商品信息 public void saveItem(Items items)throws Exception;
@RequestMapping(value="/editItem") public String editItem(Model model, Integer id) throws Exception{ //调用service查询商品信息 Items item = itemService.findItemById(id); model.addAttribute("item", item); return "item/editItem"; } 修改商品信息提交: //商品修改提交 @RequestMapping("/editItemSubmit") public String editItemSubmit(Items items)throws Exception{ System.out.println(items); itemService.saveItem(items); return "success"; }
//调用service查询商品信息 Items item = itemService.findItemById(id); model.addAttribute("item", item);
使用Model和ModelMap的效果一样,如果直接使用Model,springmvc会实例化ModelMap。
当请求的参数名称和处理器形参名称一致时会将请求参数与形参进行绑定。
定义如下:
public String editItem(@RequestParam(value="item_id",required=true) String id) { }
<input type="text" name="name"/> <input type="text" name="price"/>
@RequestMapping("/editItemSubmit") public String editItemSubmit(Items items)throws Exception{ System.out.println(items);
Public class QueryVo { private Items items; }
<input type="text" name="items.name" /> <input type="text" name="items.price" />
public String useraddsubmit(Model model,QueryVo queryVo)throws Exception{ System.out.println(queryVo.getItems());
public class CustomDateConverter implements Converter<String, Date> { @Override public Date convert(String source) { try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return simpleDateFormat.parse(source); } catch (Exception e) { e.printStackTrace(); } return null; } }
<mvc:annotation-driven conversion-service="conversionService"> </mvc:annotation-driven> <!-- conversionService --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <!-- 转换器 --> <property name="converters"> <list> <bean class="cn.itcast.ssm.controller.converter.CustomDateConverter"/> </list> </property> </bean>
<!--注解适配器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="webBindingInitializer" ref="customBinder"></property> </bean> <!-- 自定义webBinder --> <bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> <property name="conversionService" ref="conversionService" /> </bean> <!-- conversionService --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <!-- 转换器 --> <property name="converters"> <list> <bean class="cn.itcast.ssm.controller.converter.CustomDateConverter"/> </list> </property> </bean>
Controller方法中可以用String[]接收,定义如下:
List中对象:
Public class QueryVo { Private List<Items> itemList;//商品列表 //get/set方法.. }
<tr> <td> <input type="text" name=" itemsList[0].id" value="${item.id}"/> </td> <td> <input type="text" name=" itemsList[0].name" value="${item.name }"/> </td> <td> <input type="text" name=" itemsList[0].price" value="${item.price}"/> </td> </tr> <tr> <td> <input type="text" name=" itemsList[1].id" value="${item.id}"/> </td> <td> <input type="text" name=" itemsList[1].name" value="${item.name }"/> </td> <td> <input type="text" name=" itemsList[1].price" value="${item.price}"/> </td> </tr>
<c:forEach items="${itemsList }" var="item" varStatus="s"> <tr> <td><input type="text" name="itemsList[${s.index }].name" value="${item.name }"/></td> <td><input type="text" name="itemsList[${s.index }].price" value="${item.price }"/></td> ..... ..... </tr> </c:forEach>
框架 day68 SpringMVC入门(框架原理,springmvc和mybatis整合)
标签:
原文地址:http://blog.csdn.net/opopopwqwqwq/article/details/51884742