Springmvc
1.概念
- springmvc是spring framework一个模块,不需要与spring框架整合
2.框架原理(掌握)
2.1 执行流程
第一步:发起请求到前端控制器(DispatcherServlet)
第二步:前端控制器请求HandlerMapping查找 Handler
可以根据xml配置、注解进行查找
第三步:处理器映射器HandlerMapping向前端控制器返回Handler
第四步:前端控制器调用处理器适配器去执行Handler
第五步:处理器适配器去执行Handler
第六步:Handler执行完成给适配器返回ModelAndView
第七步:处理器适配器向前端控制器返回ModelAndView
ModelAndView是springmvc框架的一个底层对象,包括Model和view
第八步:前端控制器请求视图解析器去进行视图解析
根据逻辑视图名解析成真正的视图(jsp)
第九步:视图解析器向前端控制器返回View
第十步:前端控制器进行视图渲染
视图渲染将模型数据(在ModelAndView对象中)填充到request域
第十一步:前端控制器向用户响应结果
2.2组件
- 一大核心:前端控制器 核心控制器(接受request,产生response响应)
- 三大组件:处理器映射器,处理器适配器,视图解析器
- DispatcherServlet(不需要程序员开发)
- 接受请求,响应结果,*处理器;作用:降低各个组件之间的耦合度
- 处理器映射器HandlerMapping(不需要程序员开发)
- 根据请求的url地址查找handler(注解方法,xml配置发式)
- 处理器适配器(HandlerAdapter)(默认有转换器eg:整数,客户端传的数据都是String格式)
- 按照特定规则(传入参数及返回值类型不同)去执行handler,
- 处理器(Handler 需要程序员开发)——后端控制器
- 按照一定的规则开(HandlerAdapter)发,根据业务需求,使用注解开发
- 视图解析器(ViewResolver)
- 进行视图解析(将逻辑视图名称转为真正的访问的视图地址(jsp页面))
- 视图view(程序员)——写jsp页面,数据的展示
- 支持不同视图(JSP)
3. springmvc入门程序
3.1 开发流程
3.11 在web.xml配置前端控制器
目的是配置前端控制器,配置初始化参数,目的配置springmvc文件路径
由于springmvc只有controler层,只需要以下配置
-
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <!--springmvc前端控制器--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--配置初始化参数 contextConfigLocation:配置springmvc的配置文件的路径 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <!--配置前端控制器的访问路径--> <!--1.扩展名配置 *。action 访问路径以action结尾的请求到达DispatcherServlet处理 2. /* 所有的请求到达DispatcherServlet处理器 不能这样配置 3. / 所有请求到达DispatcherServlet处理器进行解析,处理jsp页面 RESTFUI风格的url --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
3.12 创建springmvc.xml配置文件(注解简化开发)
<!--组件扫描 controller 目的:扫描controller层 -->
<context:component-scan base-package="com.yunhe.controller"></context:component-scan>
//开启注解驱动扫描
<mvc:annotation-driven></mvc:annotation-driven>
<!--将逻辑视图名转为视图地址 视图解析器的配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
```
3.13 在controller层 创建ItemsController类
-
@Controller//注解必须有,相当于当前类是一个Handler处理器 public class ItemsController { //查询商品列表处理器 //RequestMapping:将方法和url进行映射,。一个方法对应一个url地址。一般建议url地址与方法一致 @RequestMapping("/findAll") public ModelAndView findAll(){ //调用业务层进行商品数据查询 List<Items> itemsList = new ArrayList<Items>(); Items items1 = new Items(1,"电动车",4000d,null,new Date(),"心动不如行动"); itemsList.add(items1); //创建ModelAndView ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("itemsList",itemsList); System.out.println(itemsList); //设置视图 modelAndView.setViewName("itemList"); return modelAndView; } }
4.springmvc与mybatis,Spring整合
4.1 pom.xml配置
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring-version>5.0.8.RELEASE</spring-version>
<mybatis-version>3.4.1</mybatis-version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- spring核心包 start-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- spring核心包 end-->
<!--导入数据库驱动jar,数据库连接池-->
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- C3P0数据库连接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!--导入jstl-->
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!--json解析包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
<!--导入mybatis 和 mybatis与spring整合jar-->
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis-version}</version>
</dependency>
<!-- mybatis-spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<!--配置访问路径-->
<path>/</path>
<!--配置访问的端口号-->
<port>8899</port>
<server>tomcat7</server>
</configuration>
</plugin>
4.2 web.xml文件配置
- 配置前端控制器
- 配置springmvc.xml文件
- 配置spring容器
- 配置监听器
- 通过全局化参数配置spring配置文件路径
<?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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Archetype Created Web Application</display-name>
<!-- 配置spring文件路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml</param-value>
</context-param>
<!--配置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>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
4.3 dao层
4.3.1创建SqlMapConfig.xml
- 配置类型别名,或者其他配置
<?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>
<!--配置别名-->
<typeAliases>
<package name="com.yunhe.entity"/>
</typeAliases>
</configuration>
4.3.2 创建spring-dao.xml
1.加载属性集文件db.properties
2.配置数据源
3.配置SqlSessionFactoryBean对象,注入数据源
4.通过扫描器扫描指定包下的接口和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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!--加载db.properties-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!--配置数据源文件-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="jdbcUrl" value="${jdbc.Url}"></property>
</bean>
<!--配置sqlSessionFactory-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
<!--注入SqlMapperConfig.xml-->
<property name="configLocation" value="classpath:SqlMapperConfig.xml"></property>
</bean>
<!--扫描mapper接口和xml文件-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.yunhe.dao"></property>
</bean>
</beans>
4.3.3 代码
4.3.3.1写Mapper接口
package com.yunhe.dao;
import com.yunhe.entity.Items;
import java.util.List;
public interface ItemsMapper {
/**
* 通过id查询商品
* @param id
* @return Items
*/
public Items findItemsById(Integer id);
/**
* 查询所有商品信息
* @return 商品集合
*/
public List<Items> findAll();
/**
* 修改账户信息
* @param items
*/
public void updateItem(Items items);
}
4.3.3.2写MapperXML文件(符合mapper代理开发原则)
mapp.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="com.yunhe.dao.ItemsMapper">
<select id="findItemsById" resultType="items">
select * from items where id=#{id}
</select>
<select id="findAll" resultType="items">
select * from items
</select>
<update id="updateItem" parameterType="items">
update items set name=#{name}, price=#{price},detail=#{detail} where id=#{id}
</update>
</mapper>
4.4 service层
4.4.1创建spring-service.xml
- 组件扫描(所有业务层组件@Service)
- 配置事务管理器(注入dataSource)
- 配置事务通知(引用事务管理器)
- 配置事务属性(隔离性,传播性,是否只读)
- 通过aop配置切面
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!--扫描业务层组件-->
<context:component-scan base-package="com.yunhe.service"></context:component-scan>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事务通知-->
<tx:advice id="myAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" propagation="REQUIRED" isolation="REPEATABLE_READ" read-only="true"/>
<tx:method name="delete*" propagation="REQUIRED" isolation="REPEATABLE_READ" read-only="false"/>
<tx:method name="update*" propagation="REQUIRED" isolation="REPEATABLE_READ" read-only="false"/>
</tx:attributes>
</tx:advice>
<!--配置事务-->
<aop:config>
<aop:pointcut id="pc" expression="execution(* com.yunhe.service..*ServiceIml.*(..))"/>
<aop:advisor advice-ref="myAdvice" pointcut-ref="pc"></aop:advisor>
</aop:config>
</beans>
4.4.2 Service层接口
package com.yunhe.service;
import com.yunhe.entity.Items;
import java.util.List;
public interface ItemsService {
public Items findItemsById(Integer id);
public List<Items> findAll();
public void updateItem(Items items);
}
4.4.3 Service接口实现类
package com.yunhe.service;
import com.yunhe.dao.ItemsMapper;
import com.yunhe.entity.Items;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ItemsServiceImpl implements ItemsService {
@Autowired
private ItemsMapper mapper;
@Override
public Items findItemsById(Integer id) {
return mapper.findItemsById(id);
}
@Override
public List<Items> findAll() {
return mapper.findAll();
}
@Override
public void updateItem(Items items) {
mapper.updateItem(items);
}
}
4.5 controller层
4.5.1 创建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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!--组件扫描-->
<context:component-scan base-package="com.yunhe.controller"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<!--扫描注解驱动-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
4.5.2 Controller层代码
package com.yunhe.controller;
import com.yunhe.entity.Items;
import com.yunhe.service.ItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("items1")//给当前类所有处理器的url加前缀
public class ItemsController {
@Autowired
ItemsService is;
@RequestMapping("findById")
public ModelAndView findById(Integer id){
Items items=is.findItemsById(id);
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("item",items);
modelAndView.setViewName("editItem");
return modelAndView;
}
/**
*
* @return
*/
@RequestMapping("findAll")
public ModelAndView findAll(){
List<Items> itemsList=is.findAll();
System.out.println(itemsList);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("itemsList",itemsList);
modelAndView.setViewName("itemList");
return modelAndView;
}
@RequestMapping("editItem")
public String editItem(Items items){
is.updateItem(items);
//修改后需要查看信息,需要把页面转发到查看全部位置
return "redirect:/items/findAll";
}
}
5. @RequestMapping
5.1 写在类上
-
@RequestMapping("items") //给当前类所有处理器的url加前缀
@Controller
@RequestMapping("items1")//给当前类所有处理器的url加前缀
public class ItemsController {
@Autowired
ItemsService is;
@RequestMapping("findById")
public ModelAndView findById(Integer id){
Items items=is.findItemsById(id);
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("item",items);
modelAndView.setViewName("editItem");
return modelAndView;
}
5.2 写在方法上
- 设置当前处理器映射url地址
@Controller
@RequestMapping("items1")//给当前类所有处理器的url加前缀
public class ItemsController {
@Autowired
ItemsService is;
@RequestMapping("findById")
public ModelAndView findById(Integer id){
Items items=is.findItemsById(id);
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("item",items);
modelAndView.setViewName("editItem");
return modelAndView;
}
/**
*
* @return
*/
@RequestMapping("findAll")
public ModelAndView findAll(){
List<Items> itemsList=is.findAll();
System.out.println(itemsList);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("itemsList",itemsList);
modelAndView.setViewName("itemList");
return modelAndView;
}
-
对http请求方式进行限制
要求方法必须是post请求
-
@RequestMapping(value="/findById",method = RequestMethod.POST)
-
6. Springmvc处理器返回值类型
6.1 返回类型是ModelAndView
- 需要封装数据模型和页面信息(传递数据,默认使用的是request域对象)
@Controller
@RequestMapping("items")//给当前类所有处理器的url加前缀
public class ItemsController1 {
@Autowired
ItemsService is;
/**
* 访问地址:items/findById?id=1
*访问的时候需要传递参数
* @param id
* @return
*/
@RequestMapping(value="findById")//@RequestMapping("findById")
public ModelAndView findById(Integer id){
Items items=is.findItemsById(id);
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("item",items);
modelAndView.setViewName("editItem");
return modelAndView;
}
6.2 返回值类型string
6.2.1表示的是逻辑视图的地址
-
通过视图解析器加上前缀后后缀
-
/jsp/itemsList.jsp
-
6.2.2 表示重定向 redirect (跳转到其他处理器)
-
"redirect:/items/findAll"
@RequestMapping("editItem")
public void editItem(Items items, HttpServletRequest request, HttpServletResponse response) throws Exception {
is.updateItem(items);
//实现重定向
response.sendRedirect("/items/findAll");
//请求转发
request.getRequestDispatcher("/items/findAll").forward(request,response);
// return "redirect:/items/findAll";
// return "forword:/items/findAll";
}
6.2.3 代表转发 forawrd
-
return "forward:/items/findAll"
6.3 返回值void
- 在处理器上定义request和response对象,使用这两个对象完成转发和重定向
- 使用response对象向客户端响应json字符串
@RequestMapping("test")
public void test(HttpServletResponse response) throws IOException {
response.setContentType("application/json;charset=utf-8");
response.setCharacterEncoding("utf-8");
Items items=new Items(1,"手机",4000f,null,null,"流畅");
//转成json对象,打印到页面
PrintWriter out = response.getWriter();
String s = JSONObject.toJSONString(items);
out.write(s);
}
7. Springmvc处理器的参数类型(参数绑定)
- 概念
- 从客户端发送的key/value形式,经过springmvc参数绑定,将key/value参数绑定给处理器的方法的形参上。
7.1默认支持的参数类型
- HttpServlteRequest,HttpServletResponse,HttpSession,Model/ModelMap(主要向request域对象存值)
直接可以调用
7.2 简单类型
7.2.1客户端发送参数名与处理器形参名保持一致
客户端请求数据与处理器的参数相同
7.2.2客户端发送参数名与处理器形参名不一致
-
使用@RequestParam指定参数名,就可以绑定成功
-
@RequestParam(value = "pid",required = true)//表示必须传递参数,不能为空 @RequestParam(value = "pid")//表示可以不传入参数,可以为空
//请求参数商品id 简单类型
@RequestMapping(value="/findById")//items/findById?id=1
<--public ModelAndView findById(@RequestParam(value = "pid") Integer id){}
url地址的id值可以为空 例如://items/findById?id= -->
public ModelAndView findById(@RequestParam(value = "pid",required = true) Integer id){//url地址必须:findById?id=1,id必须赋值
Items items = is.findItemsById(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("item",items);
modelAndView.setViewName("editItem");
return modelAndView;
}
7.3 pojo类型绑定
- 页面上input标签的name属性值与pojo中成员变量名保持一致。
@RequestMapping("test")
public void test(HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
Items items = new Items(1,"手机",3000.0,null,null,"好啊");
//转成json对象
response.getWriter().write(JSONObject.toJSON(items).toString());
}
7.4 复杂实体类
自定义一个类,把实体类、集合、数组封装在类中,通过类及属性来调用
package com.yunhe.entity;
import java.util.List;
import java.util.Map;
public class ItemsVo {
/**
* items对象
*/
private Items items1;
/**
* 批量管理id
*/
private Integer [] ids;
/**
* 批量添加items
*/
private List<Items> items;
/**
*Map集合
*/
private Map<String,String > map;
public Items getItems1() {
return items1;
}
public void setItems1(Items items1) {
this.items1 = items1;
}
public Integer[] getIds() {
return ids;
}
public void setIds(Integer[] ids) {
this.ids = ids;
}
public List<Items> getItems() {
return items;
}
public void setItems(List<Items> items) {
this.items = items;
}
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
}
- ItemsVo{Items items}
- form表单中name属性(属性名.属性名)
<c:forEach items="${itemsList}" var="item" varStatus="s">
<tr>
<td><input type="checkbox" name="ids" value="${item.id }"></td>
<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>
<td>
<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>
</td>
<td>${item.detail }</td>
<td><a href="${pageContext.request.contextPath }/items/findById?id=${item.id}">修改</a></td>
</tr>
</c:forEach>
Conroller层
例如:删除多个Id对应的商品,把id数组封装在类中,通过创建对象传入参数,进行批量的删除
/**
* 批量删除
* @param ids
*/
@RequestMapping("deleteByIds")
public void deleteById(Integer []ids){
ItemsVo vo=new ItemsVo();
vo.setIds(ids);
is.deleteById(vo);
}
7.5 集合参数绑定
Conroller层
例如:批量修改信息。
/**
* 批量修改数据
* @param vo
* 把数据封装在list集合中,把list集合封装在类中,通过调用类.属性来调用集合
*/
@RequestMapping("updateItems")
public void updateItems(ItemsVo vo){
is.updateItems(vo.getItems());
}
}