Springmvc框架---SSM整合 (02)实训 20191031

mac2026-08-22  2

需求: 实现商品查询列表,从mysql数据库查询商品信息。

1) 整合思路–配置文件

1)Dao层

pojo和映射文件以及接口 使用逆向工程 生成

逆向工程生成会覆盖掉原来所有文件 所以要另起一个项目来做.

GeneratorSqlmap 类

public class GeneratorSqlmap { public void generator() throws Exception{ List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("generatorConfig-base.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } public static void main(String[] args) throws Exception { try { GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap(); generatorSqlmap.generator(); } catch (Exception e) { e.printStackTrace(); } } } generatorConfig-base.xml 需要改动 <!--数据库连接的信息:驱动类、连接地址、用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/springmvc" userId="root" password="root"><!-- targetProject:生成PO类的位置 --> <javaModelGenerator targetPackage="cn.atcast.pojo" targetProject=".\src"> <!-- targetPackage:mapper映射文件生成的位置 --> <sqlMapGenerator targetPackage="cn.atcast.dao" targetProject=".\src"> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- targetPackage:mapper接口的生成位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="cn.atcast.dao" targetProject=".\src"> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 指定表 --> <table schema="" tableName="items" /> <table schema="" tableName="user" /> </context>

效果:

SqlMapConfig.xml mybatis核心配置文件

SqlMapConfig.xml 目前是空的 ,但必须要有

ApplicationContext-dao.xml 整合后spring在dao层的配置

<?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:SqlMapConfig.xml" /> </bean> <!-- 配置Mapper扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.atcast.dao"/> </bean> </beans> 数据源会话工厂扫描Mapper

2)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"> <!-- 数据源 web.xml执行后具体看代码 就得到了dataSource --> <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.atcast.service.*.*(..))" /> </aop:config> </beans>

@Service注解扫描 ApplicationContext-service.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"> <!-- @Service扫描 业务类--> <context:component-scan base-package="cn.atcast.service"></context:component-scan> </beans>

3)controller层

SpringMvc.xml

<?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="cn.atcast.controller"></context:component-scan> <!-- 注解驱动: 替我们显示的配置了最新版的注解的处理器映射器和处理器适配器 <mvc:annotation-driven /> 是一种简写形式,完全可以手动配置替代这种简写形式,简写形式可以让初学都快速应用默认配置方案。 <mvc:annotation-driven /> 会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean, 是spring MVC为@Controllers分发请求所必须的。 并提供了:数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持, 读写XML的支持(JAXB),读写JSON的支持(Jackson)。 如下--> <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> <!-- 配置视图解析器 作用:在controller中指定页面路径的时候就不用写页面的完整路径名称了,可以直接写页面去掉扩展名的名称 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 真正的页面路径 = 前缀 + 去掉后缀名的页面名称 + 后缀 --> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/jsp/"></property> <!-- 后缀 --> <property name="suffix" value=".jsp"></property> </bean> <!-- 配置自定义转换器 注意: 一定要将自定义的转换器配置到注解驱动上 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="cn.atcast.controller.converter.CustomGlobalStrToDateConverter"></bean> </set> </property> </bean> </beans> 注解扫描:扫描@Controller注解注解驱动:替我们显示的配置了最新版的处理器映射器和处理器适配器视图解析器:显示的配置是为了在controller中不用每个方法都写页面的全路径

4)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>ssm0523</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> <!-- springmvc前端控制器 --> <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> <!-- 在tomcat启动的时候就加载这个servlet --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMvc</servlet-name> <url-pattern>*.action</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> springMvc前端控制器配置spring监听

编写内容–框架搭建完后的工作

cn.atcast.service.ItemsService类

public interface ItemsService { public List<Items> list() throws Exception; public Items findItemsById(Integer id) throws Exception; public void updateItems(Items items) throws Exception; }

ItemsServiceImpl

@Service public class ItemsServiceImpl implements ItemsService { @Autowired private ItemsMapper itemsMapper;//dao层 @Override//查询所有数据 public List<Items> list() throws Exception { //如果不需要任何查询条件,直接将example对象new出来即可 ItemsExample example=new ItemsExample(); //selectByExampleWithBLOBs将大文本类型detail字段查询出来。 List<Items> list=itemsMapper.selectByExampleWithBLOBs(example); return list; } @Override//根据id查 public Items findItemsById(Integer id) throws Exception { Items items=itemsMapper.selectByPrimaryKey(id); return items; } @Override//修改 public void updateItems(Items items) throws Exception { itemsMapper.updateByPrimaryKeyWithBLOBs(items); } }

测试类

/** * 测试共公类 *在使用所有注释前必须使用@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:ApplicationContext-*.xml") public class SpringJunitTest { } public class DemoTest extends SpringJunitTest{ @Autowired private ItemsService itemsService; @Test //测试是否有用户存在 public void run1(){ try { List<Items> list=itemsService.list(); System.out.println(list); } catch (Exception e) { e.printStackTrace(); } } }

商品显示控制层

ItemsController

@Controller public class ItemsController { @Autowired private ItemsService itemsService; @RequestMapping("/list")//显示所有内容 public ModelAndView itemsList() throws Exception{ List<Items> list=itemsService.list(); ModelAndView modelAndView=new ModelAndView(); modelAndView.addObject("itemList", list); modelAndView.setViewName("itemList"); return modelAndView; } //${pageContext.request.contextPath}/itemEdit.cation?id=${item.id} //写了从前台拿数据的方式一 @RequestMapping("/itemEdit")// 修改--传过来一个id public String itemEdit(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model model) throws Exception{ String idStr=request.getParameter("id");//可以从Request对象中取id。 Items items=itemsService.findItemsById(Integer.parseInt(idStr)); model.addAttribute("item", items); //类似于request.setAttribute("item", items)效果一样。 return "editItem"; } //返回一个String 而不是ModelAndView //写了从前台拿数据的方式一之简化后的版本 -- 支持的数据类型有限 //当请求的参数名称和处理器形参名称一致时会将请求参数与形参进行绑定。从Request取参数的方法可以进一步简化。 @RequestMapping("/itemEdit") public String itemEdit(Integer id, Model model) throws Exception{ Items items = itmesService.findItemsById(id); //向jsp传递数据 model.addAttribute("item", items); //设置跳转的jsp页面 return"editItem"; } //写了从前台拿数据的方式二 @RequestMapping("/itemEdit") public String editItem(@RequestParam(value="id",required=true)Integer id,Model model) throws Exception{ Items items=itemsService.findItemsById(id); model.addAttribute("item", items); //springmvc方法如果返回一个string字符串,认为这个字符串是一个页面名 return "editItem"; } //写了从前台拿数据的方式三--绑定pojo类型 @RequestMapping("/updateite m") //修改页面 上传图片 public String itemEdit(Items items) throws Exception{//下面注解 6 System.out.println(items);//把对象传过来 被自动封装 注意时间需要自己指定 否则出现400错误 itemsService.updateItems(items); return "success"; } }

注解: 重要的潜规则

springMvc中默认支持的参数类型:也就是说在controller方法中可以加入这些也可以不加, 加不加看自己需不需要,都行. *HttpServletRequest *HttpServletResponse *HttpSession *Modelmodel底层其实就是用的request域来传递数据,但是对request域进行了扩展.如果springMvc方法返回一个简单的string字符串,那么springMvc就会认为这个字符串就是页面的名称springMvc可以直接接收基本数据类型,包括string.spirngMvc可以自动进行类型转换.controller方法接收的参数的变量名称必须要等于页面上input框的name属性值spirngMvc可以直接接收pojo类型:要求页面上input框的name属性名称必须等于pojo的属性名称如果Controller中接收的是Vo,那么页面上input框的name属性值要等于vo的属性.属性.属性…

使用@RequestParam常用于处理简单类型的绑定。

value:参数名字,即入参的请求参数名字,如value=“id”表示请求的参数区中的名字为id的参数的值将传入; required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报; TTP Status 400 - Required Integer parameter ‘XXXX’ is not present defaultValue:默认值,表示如果请求中没有同名参数时的默认值 形参名称为id,但是这里使用value="id"限定请求的参数名为id,所以页面传递参数的名必须为id。 注意:如果请求参数中没有id将抛出异常

写了从前台拿数据的方式三–绑定pojo类型-- 解决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> 对于get请求中文参数出现乱码解决方法有两个: 修改tomcat配置文件添加编码与工程编码一致,如下: <Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/> 另外一种方法对参数进行重新编码: String userName new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8") ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码

自定义日期转换类---->告诉springmvc.xml 我用了这个东西—>映射器 -转换器 也参与了类型转换工作 //< bean class=“cn.atcast.controller.converter.CustomGlobalStrToDateConverter”> </ bean> // < mvc:annotation-driven conversion-service=“conversionService”>< /mvc:annotation-driven> //conversion-service=“conversionService” 这一句就是了

public class CustomGlobalStrToDateConverter implements Converter<String, Date> { @Override public Date convert(String source) {//2019-09-20 05:03:08 try { Date date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(source); return date; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } <!-- 配置自定义转换器 注意: 一定要将自定义的转换器配置到注解驱动上 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="cn.atcast.controller.converter.CustomGlobalStrToDateConverter"> </bean> </set> </property> </bean>

修改jsp

<title>修改商品信息</title> </head> <body> <!-- 上传图片是需要指定属性 enctype="multipart/form-data" --> <form id="itemForm" action="${pageContext.request.contextPath }/updateitem.action" method="post"> <input type="hidden" name="id" value="${item.id }" /> 修改商品信息: <table width="100%" border=1> <tr> <td>商品名称</td> <td><input type="text" name="name" value="${item.name }" /></td> </tr> <tr> <td>商品价格</td> <td><input type="text" name="price" value="${item.price }" /></td> </tr> <tr> <td>商品生产日期</td> <td><input type="text" name="createtime" value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>" /></td> </tr> <tr> <td>商品简介</td> <td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea> </td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="提交" /> </td> </tr> </table> </form>

绑定包装pojo

使用包装的pojo接收商品信息的查询条件。 包装对象定义如下: package cn.atcast.vo;

import cn.atcast.pojo.Items; public class QueryVo { //商品对象 private Items items; //订单对象... //用户对象.... public Items getItems() { return items; } public void setItems(Items items) { this.items = items; } } 页面定义:----> name="items.name" <input type="text" name="items.name" /> <input type="text" name="items.price" /> Controller方法定义如下: //如果Controller中接收的是Vo,那么页面上input框的name属性值要等于vo的属性.属性.属性..... @RequestMapping("/search") public String search(QueryVo vo) throws Exception{ System.out.println(vo.getItems().getName()); return ""; }

绑定数组

1) 需求

在商品列表页面选中多个商品,然后删除。此功能要求商品列表页面中的每个商品前有一个checkbox,选中多个商品后点击删除 按钮把商品id传递给Controller,根据商品id删除商品信息。

2) Jsp中实现

jsp/itemList.jsp <%@ 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> <form action="${pageContext.request.contextPath }/delAll.action" method="post"> 查询条件: <table width="100%" border=1> <tr> <!-- 如果Controller中接收的是Vo,那么页面上input框的name属性值要等于vo的属性.属性.属性..... --> <td>商品名称:<input type="text" name="items.name"/></td> <td>商品价格:<input type="text" name="items.price"/></td> <td><input type="submit" value="批量删除"/></td> </tr> </table> 商品列表: <table width="100%" border=1> <tr> <td>商品名称</td> <td>商品价格</td> <td>生产日期</td> <td>商品描述</td> <td>操作</td> </tr> <c:forEach items="${itemList }" var="item"> <tr> <td><input name="ids" value="${item.id}" type="checkbox"></td> <td>${item.name }</td> <td>${item.price }</td> <td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td> <td>${item.detail }</td> <td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td> </tr> </c:forEach> </table> </form> </body> </html>

3) 修改QueryVo对象

//批量删除使用

private Integer[] ids; public Integer[] getIds() { return ids; } public void setIds(Integer[] ids) { this.ids = ids; }

4) Controller

@RequestMapping("/delAll") public String delAll(QueryVo vo) throws Exception{ //加入断点调试 System.out.println(vo); return ""; }

将表单的数据绑定到List

1) 需求

实现商品数据的批量修改。 要想实现商品数据的批量修改,需要在商品列表中可以对商品信息进行修改,并且可以 批量提交修改后的商品数据。

2) 接收商品列表的pojo

List中存放对象,并将定义的List放在包装类中,使用包装pojo对象接收。 cn.atcast.vo/QueryVo.java // 批量修改使用 private List<Items> itemsList; public List<Items> getItemsList() { return itemsList; } public void setItemsList(List<Items> itemsList) { this.itemsList = itemsList; }

3) Jsp改造

itemList.jsp <%@ 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"> <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script> <title>查询商品列表</title> </head> <body> <form action="${pageContext.request.contextPath }/updateAll.action" method="post"> 查询条件: <table width="100%" border=1> <tr> <!-- 如果Controller中接收的是Vo,那么页面上input框的name属性值要等于vo的属性.属性.属性..... --> <td>商品名称:<input type="text" name="items.name"/></td> <td>商品价格:<input type="text" name="items.price"/></td> <td><input type="submit" value="批量修改"/></td> </tr> </table> 商品列表: <table width="100%" border=1> <tr> <td></td> <td>商品名称</td> <td>商品价格</td> <td>生产日期</td> <td>商品描述</td> <td>操作</td> </tr> <c:forEach items="${itemList }" var="item" varStatus="status"> <tr> <!-- name属性名称要等于vo中的接收的属性名 --> <!-- 如果批量删除,可以用List<pojo>来接收,页面上input框的name属性值= vo中接收的集合属性名称+[list的下标]+.+list泛型的属性名称 --> <td> <input type="checkbox" name="ids" value="${item.id }"/> <input type="hidden" name="itemsList[${status.index }].id" value="${item.id }"/> </td> <td><input type="text" name="itemsList[${status.index }].name" value="${item.name }"/></td> <td><input type="text" name="itemsList[${status.index }].price" value="${item.price }"/></td> <td><input type="text" name="itemsList[${status.index }].createtime" value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td> <td><input type="text" name="itemsList[${status.index }].detail" value="${item.detail }"/></td> <td><a href="${pageContext.request.contextPath }/items/itemEdit/${item.id}">修改</a></td> </tr> </c:forEach> </table> </form> </body> </html>

varStatus属性常用参数总结下: ${status.index} 输出行号,从0开始。 ${status.count} 输出行号,从1开始。 ${status.current} 当前这次迭代的(集合中的)项 ${status.first} 判断当前项是否为集合中的第一项,返回值为true或false ${status.last} 判断当前项是否为集合中的最后一项,返回值为true或false begin、end、step分别表示:起始序号,结束序号,跳跃步伐。

4) Contrller

//批量修改

@RequestMapping("/updateAll") public String updateAll(QueryVo vo) throws Exception{ System.out.println(vo); return “”; }

注意:接收List类型的数据必须是pojo的属性,方法的形参为List类型无法正确接收到数据。

springmvc与struts2不同

1、 springmvc的入口是一个servlet即前端控制器,而struts2入口是一个filter过虑器。 2、 springmvc是基于方法开发(一个url对应一个方法),请求参数传递到方法的形参,可以设计为单例或多例(建议单例),struts2是基于类开发,传递参数是通过类的属性,只能设计为多例。 3、 Struts采用值栈存储请求和响应的数据,通过OGNL存取数据, springmvc通过参数解析器是将request请求内容解析,并给方法形参赋值,将数据和视图封装成ModelAndView对象,最后又将ModelAndView中的模型数据通过reques域传输到页面。Jsp视图解析器默认使用jstl。


大家好,我是凯凯!

大家看完觉得不错 请点个赞呗! 评论一句也可以! 整理不易, 请转发加我的名字哦!

你的支持 使我更有动力!

最新回复(0)