springmvc的简单使用以及ssm框架的整合
Spring web mvc是基于servlet的一个表现层框架
首先创建一个简单的web工程了解它的使用
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_demo</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> <!--配置springmvc前端的控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置spring配置文件的位置
如果不配,默认在/WEB-INF目录下,
名称为上面<servlet-name>springmvc</servlet-name>的值-servlet.xml,如现在:默认:/WEB-INF/springmvc-servlet.xml
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--配置拦截的方式
/ 为包括所有如(css等) 但是不包括 jsp
/* 为所有包括所有如(css等),并且包括jsp
-->
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- 扫描控制器所在的包下的所有的类 -->
<context:component-scan base-package="com.springmvc.controller"/> <!--配置式处理器映射器,对类中标记@ResquestMapping的方法进行映射,
根据ResquestMapping定义的url匹配ResquestMapping标记的方法
,匹配成功返回HandlerMethod对象给前端控制器,HandlerMethod对象中封装url对应的方法Method。
不配置的会用默认的org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
但是从spring3.1版本开始已经被废除了,官方推荐使用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
-->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> --> <!--
注解式处理器适配器,对标记@ResquestMapping的方法进行适配。
不配置会用默认的org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
从spring3.1版本开始,废除了AnnotationMethodHandlerAdapter的使用,
推荐使用RequestMappingHandlerAdapter完成注解式处理器适配。
-->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> -->
<!--
注意这两个必须一起配置,不然会报错
HTTP Status - No adapter for handler [public
org.springframework.web.servlet.ModelAndView com.springmvc.controller.HelloAction.sayHello()]:
The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler
--> <!--使用这种方式据不需要配上面的两个bean,springmvc自动加载
springmvc使用<mvc:annotation-driven>自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter,
可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。并且默认加载了JSON数据格式转换器。
-->
<mvc:annotation-driven/> <!--
配置视图解析器,表示在action中调用setViewName("/WEB-INF/hello.jsp")时,
只需要setViewName("hello");就可以了,框架自动加上前缀和后缀变成/WEB-INF/hello.jsp
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀 -->
<property name="prefix" value="/WEB-INF/" />
<!--后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
前端jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
${message }
</body>
</html>
执行流程
1、 用户发送请求至前端控制器DispatcherServlet
2、 DispatcherServlet收到请求URL调用HandlerMapping处理器映射器。
3、 处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。
4、 DispatcherServlet通过HandlerAdapter处理器适配器调用处理器
5、 执行处理器(Controller,也叫后端控制器)。
6、 Controller执行完成返回ModelAndView
7、 HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet
8、 DispatcherServlet将ModelAndView传给ViewReslover视图解析器
9、 ViewReslover解析后返回具体View
10、 DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)。
DispatcherServlet响应用户
自定义的controller
package com.springmvc.controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; @Controller
public class HelloController {
//未配置视图解析器前
//注解映射,就是访问路径,执行这个方法,相当于访问http://localhost:8080/springmvc_demo/hello.action执行这个方法
// @RequestMapping("/hello.action")
// public ModelAndView sayHello(){
// //创建一个模型视图对象
// ModelAndView modelAndView = new ModelAndView();
// //添加一个数据,相当于 request.setAttribute("message", "hello");
// modelAndView.addObject("message", "hello");
// //转发一个页面,相当于request.getRequestDispatcher("/WEB-INF/hello.jsp").forward();
// modelAndView.setViewName("/WEB-INF/hello.jsp");
// return modelAndView;
// } //注解映射,就是访问路径,执行这个方法,相当于访问http://localhost:8080/springmvc_demo/hello.action执行这个方法
@RequestMapping("/hello.action") //action的后缀也可以去掉
public ModelAndView sayHello(){
//创建一个模型视图对象
ModelAndView modelAndView = new ModelAndView();
//添加一个数据,相当于 request.setAttribute("message", "hello");
modelAndView.addObject("message", "hello");
//转发一个页面,相当于request.getRequestDispatcher("/WEB-INF/hello.jsp").forward();
modelAndView.setViewName("hello");
return modelAndView;
}
}
springMVC-spring-myBatis的整合
数据库环境的搭建
创建数据库;执行sql
/*
Navicat MySQL Data Transfer Source Server : localhost_3306
Source Server Version : 50611
Source Host : localhost:3306
Source Database : springmvc Target Server Type : MYSQL
Target Server Version : 50611
File Encoding : 65001 Date: 2016-05-09 19:45:13
*/ SET FOREIGN_KEY_CHECKS=0; -- ----------------------------
-- Table structure for items
-- ----------------------------
DROP TABLE IF EXISTS `item`;
CREATE TABLE `item` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL COMMENT '商品名称',
`price` float(10,1) NOT NULL COMMENT '商品定价',
`detail` varchar(5000) COMMENT '商品描述',
`pic` varchar(64) DEFAULT NULL COMMENT '商品图片',
`createtime` datetime NOT NULL COMMENT '生产日期',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of items
-- ----------------------------
INSERT INTO `item` VALUES ('', '台式机', '3000.0', '该电脑质量非常好!!!!', null, '2016-02-03 13:22:53');
INSERT INTO `item` VALUES ('', '笔记本', '6000.0', '笔记本性能好,质量好!!!!!', null, '2015-02-09 13:22:57');
INSERT INTO `item` VALUES ('', '背包', '200.0', '名牌背包,容量大质量好!!!!', null, '2015-02-06 13:23:02'); -- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('', '王五', null, '', null);
INSERT INTO `user` VALUES ('', '张三', '2014-07-10', '', '北京市');
INSERT INTO `user` VALUES ('', '张小明', null, '', '河南郑州');
INSERT INTO `user` VALUES ('', '陈小明', null, '', '河南郑州');
INSERT INTO `user` VALUES ('', '张三丰', null, '', '河南郑州');
INSERT INTO `user` VALUES ('', '陈小明', null, '', '河南郑州');
INSERT INTO `user` VALUES ('', '王五', null, null, null);
首先创建web工程
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>spring_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> <!--配置springmvc前端的控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置spring配置文件的位置
如果不配,默认在/WEB-INF目录下,
名称为上面<servlet-name>springmvc</servlet-name>的值-servlet.xml,如现在:默认:/WEB-INF/springmvc-servlet.xml
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--配置拦截的方式
/ 为包括所有如(css等) 但是不包括 jsp
/* 为所有包括所有如(css等),并且包括jsp
-->
<url-pattern>*.action</url-pattern>
</servlet-mapping> <!--设置spring初始化的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!--*匹配所有 -->
<param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param> <!--初始化spring容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!--spring提供的结局post乱码的过滤器 -->
<filter>
<filter-name>characterEncoding</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>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
相关的配置文件,这里spring分开配置,写成了4个配置文件,亦可以用一个配置文件即可
springmvc的配置文件,由于springmvc本身就是spring的一部分,所以无需整合,只需要配置
<?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.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- 扫描控制器所在的包下的所有的类 -->
<context:component-scan base-package="com.ssm.controller"/> <!--配置式处理器映射器,对类中标记@ResquestMapping的方法进行映射,
根据ResquestMapping定义的url匹配ResquestMapping标记的方法
,匹配成功返回HandlerMethod对象给前端控制器,HandlerMethod对象中封装url对应的方法Method。
不配置的会用默认的org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
但是从spring3.1版本开始已经被废除了,官方推荐使用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
-->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> --> <!--
注解式处理器适配器,对标记@ResquestMapping的方法进行适配。
不配置会用默认的org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
从spring3.1版本开始,废除了AnnotationMethodHandlerAdapter的使用,
推荐使用RequestMappingHandlerAdapter完成注解式处理器适配。
-->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> -->
<!--
注意这两个必须一起配置,不然会报错
HTTP Status 500 - No adapter for handler [public
org.springframework.web.servlet.ModelAndView com.springmvc.controller.HelloAction.sayHello()]:
The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler
--> <!--使用这种方式据不需要配上面的两个bean,springmvc自动加载
springmvc使用<mvc:annotation-driven>自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter,
可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。并且默认加载了JSON数据格式转换器。
-->
<mvc:annotation-driven conversion-service="conversionService"/> <!--
配置视图解析器,表示在action中调用setViewName("/WEB-INF/hello.jsp")时,
只需要setViewName("hello");就可以了,框架自动加上前缀和后缀变成/WEB-INF/hello.jsp
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!--后缀 -->
<property name="suffix" value=".jsp" />
</bean> <!--定义转换器的工厂bean -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<!--将自定义的转换器添加进来 -->
<bean class="com.ssm.converter.DateConverter"></bean>
</set>
</property>
</bean> </beans>
dao层的spring配置文件,整合了mybatis
<?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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.2.xsd"> <!--配置数据源 -->
<!-- 加载连接的配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- dbcp数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<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> <!--配置sqlSessionFactory -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!--name必须和 org.mybatis.spring.SqlSessionFactoryBean类中的bean属性名字一致
value:mybatis的全局配置文件SqlMapConfig.xml的位置
--> <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
<!--name必须和 org.mybatis.spring.SqlSessionFactoryBean类中的bean属性名字一致
ref:和上面定义的数据源id一致
-->
<property name="dataSource" ref="dataSource"></property>
</bean> <!--配置mapper扫描器
使用扫描包的形式来创建mapper代理对象 , 每个mapper代理对象的id就是类名,首字母小写
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.dao.mapper"></property>
</bean>
</beans>
service的spring配置文件,主要是配置service层的包扫描
<?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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.2.xsd">
<!--配置service扫描 -->
<context:component-scan base-package="com.ssm.service"/> </beans>
事务的控制的spring配置文件
<?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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.2.xsd">
<!--配置事务管理器 -->
<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>
<!-- 事务传播行为
REQUIRED:表示如果有事务就是同一个事务,不重新开启新的事务,如果没有事务就开启新事务
read-only:只读
-->
<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>
<!--第一种方式
pointcut:
第一个"*" : 表示任意返回值
com.itheima.ssm.service.impl:表示包
第二个"*":表示任意的包
第三个"*":表示任意的方法
(..):表示任意的参数
这个总体表示:com.itheima.ssm.service.impl这个包下面的任意包的任意方法
可以配置到接口,不一定到实现类
-->
<aop:advisor advice-ref="myAdvice" pointcut="execution(* com.ssm.service.impl.*.*(..))"/> <!--第二种方式 表示所有以Service结尾的类,如:IItemService -->
<!-- <aop:pointcut expression="bean(*Service)" id="myPointcut"/>
<aop:advisor advice-ref="myAdvice" advice-ref="myPointcut"/> -->
</aop:config> </beans>
mybatis的全局配置文件SqlConfig.xml这是mybatis必须的,其中只是配了别名,其余的都交给sprig管理
<?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.ssm"/>
</typeAliases> </configuration>
dao层带码通过mybatis的逆向工程创建出来,只有queryVo是自己定义的
itemMapper代码
package com.ssm.dao.mapper; import com.ssm.pojo.Item;
import com.ssm.pojo.ItemExample;
import java.util.List;
import org.apache.ibatis.annotations.Param; public interface ItemMapper {
int countByExample(ItemExample example); int deleteByExample(ItemExample example); int deleteByPrimaryKey(Integer id); int insert(Item record); int insertSelective(Item record); List<Item> selectByExample(ItemExample example); Item selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") Item record, @Param("example") ItemExample example); int updateByExample(@Param("record") Item record, @Param("example") ItemExample example); int updateByPrimaryKeySelective(Item record); int updateByPrimaryKey(Item record);
}
itemMapper.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.ssm.dao.mapper.ItemMapper" >
<resultMap id="BaseResultMap" type="com.ssm.pojo.Item" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="price" property="price" jdbcType="REAL" />
<result column="detail" property="detail" jdbcType="VARCHAR" />
<result column="pic" property="pic" jdbcType="VARCHAR" />
<result column="createtime" property="createtime" jdbcType="TIMESTAMP" />
</resultMap>
<sql id="Example_Where_Clause" >
<where >
<foreach collection="oredCriteria" item="criteria" separator="or" >
<if test="criteria.valid" >
<trim prefix="(" suffix=")" prefixOverrides="and" >
<foreach collection="criteria.criteria" item="criterion" >
<choose >
<when test="criterion.noValue" >
and ${criterion.condition}
</when>
<when test="criterion.singleValue" >
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue" >
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue" >
and ${criterion.condition}
<foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause" >
<where >
<foreach collection="example.oredCriteria" item="criteria" separator="or" >
<if test="criteria.valid" >
<trim prefix="(" suffix=")" prefixOverrides="and" >
<foreach collection="criteria.criteria" item="criterion" >
<choose >
<when test="criterion.noValue" >
and ${criterion.condition}
</when>
<when test="criterion.singleValue" >
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue" >
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue" >
and ${criterion.condition}
<foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List" >
id, name, price, detail, pic, createtime
</sql>
<select id="selectByExample" resultMap="BaseResultMap" parameterType="com.ssm.pojo.ItemExample" >
select
<if test="distinct" >
distinct
</if>
<include refid="Base_Column_List" />
from item
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null" >
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from item
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from item
where id = #{id,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="com.ssm.pojo.ItemExample" >
delete from item
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.ssm.pojo.Item" >
insert into item (id, name, price,
detail, pic, createtime
)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{price,jdbcType=REAL},
#{detail,jdbcType=VARCHAR}, #{pic,jdbcType=VARCHAR}, #{createtime,jdbcType=TIMESTAMP}
)
</insert>
<insert id="insertSelective" parameterType="com.ssm.pojo.Item" >
insert into item
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="name != null" >
name,
</if>
<if test="price != null" >
price,
</if>
<if test="detail != null" >
detail,
</if>
<if test="pic != null" >
pic,
</if>
<if test="createtime != null" >
createtime,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="name != null" >
#{name,jdbcType=VARCHAR},
</if>
<if test="price != null" >
#{price,jdbcType=REAL},
</if>
<if test="detail != null" >
#{detail,jdbcType=VARCHAR},
</if>
<if test="pic != null" >
#{pic,jdbcType=VARCHAR},
</if>
<if test="createtime != null" >
#{createtime,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.ssm.pojo.ItemExample" resultType="java.lang.Integer" >
select count(*) from item
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map" >
update item
<set >
<if test="record.id != null" >
id = #{record.id,jdbcType=INTEGER},
</if>
<if test="record.name != null" >
name = #{record.name,jdbcType=VARCHAR},
</if>
<if test="record.price != null" >
price = #{record.price,jdbcType=REAL},
</if>
<if test="record.detail != null" >
detail = #{record.detail,jdbcType=VARCHAR},
</if>
<if test="record.pic != null" >
pic = #{record.pic,jdbcType=VARCHAR},
</if>
<if test="record.createtime != null" >
createtime = #{record.createtime,jdbcType=TIMESTAMP},
</if>
</set>
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map" >
update item
set id = #{record.id,jdbcType=INTEGER},
name = #{record.name,jdbcType=VARCHAR},
price = #{record.price,jdbcType=REAL},
detail = #{record.detail,jdbcType=VARCHAR},
pic = #{record.pic,jdbcType=VARCHAR},
createtime = #{record.createtime,jdbcType=TIMESTAMP}
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.ssm.pojo.Item" >
update item
<set >
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
</if>
<if test="price != null" >
price = #{price,jdbcType=REAL},
</if>
<if test="detail != null" >
detail = #{detail,jdbcType=VARCHAR},
</if>
<if test="pic != null" >
pic = #{pic,jdbcType=VARCHAR},
</if>
<if test="createtime != null" >
createtime = #{createtime,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.ssm.pojo.Item" >
update item
set name = #{name,jdbcType=VARCHAR},
price = #{price,jdbcType=REAL},
detail = #{detail,jdbcType=VARCHAR},
pic = #{pic,jdbcType=VARCHAR},
createtime = #{createtime,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
item的pojo类
package com.ssm.pojo; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; public class Item {
private Integer id; private String name; private Float price; private String detail; private String pic; @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date createtime; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name == null ? null : name.trim();
} public Float getPrice() {
return price;
} public void setPrice(Float price) {
this.price = price;
} public String getDetail() {
return detail;
} public void setDetail(String detail) {
this.detail = detail == null ? null : detail.trim();
} public String getPic() {
return pic;
} public void setPic(String pic) {
this.pic = pic == null ? null : pic.trim();
} public Date getCreatetime() {
return createtime;
} public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
}
itemExample的pojo
package com.ssm.pojo; import java.util.ArrayList;
import java.util.Date;
import java.util.List; public class ItemExample {
protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public ItemExample() {
oredCriteria = new ArrayList<Criteria>();
} public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
} public String getOrderByClause() {
return orderByClause;
} public void setDistinct(boolean distinct) {
this.distinct = distinct;
} public boolean isDistinct() {
return distinct;
} public List<Criteria> getOredCriteria() {
return oredCriteria;
} public void or(Criteria criteria) {
oredCriteria.add(criteria);
} public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
} public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
} protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
} public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
} protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria; protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
} public boolean isValid() {
return criteria.size() > 0;
} public List<Criterion> getAllCriteria() {
return criteria;
} public List<Criterion> getCriteria() {
return criteria;
} protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
} protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
} protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
} public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
} public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
} public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
} public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
} public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
} public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
} public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
} public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
} public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
} public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
} public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
} public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
} public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
} public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return (Criteria) this;
} public Criteria andNameEqualTo(String value) {
addCriterion("name =", value, "name");
return (Criteria) this;
} public Criteria andNameNotEqualTo(String value) {
addCriterion("name <>", value, "name");
return (Criteria) this;
} public Criteria andNameGreaterThan(String value) {
addCriterion("name >", value, "name");
return (Criteria) this;
} public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("name >=", value, "name");
return (Criteria) this;
} public Criteria andNameLessThan(String value) {
addCriterion("name <", value, "name");
return (Criteria) this;
} public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("name <=", value, "name");
return (Criteria) this;
} public Criteria andNameLike(String value) {
addCriterion("name like", value, "name");
return (Criteria) this;
} public Criteria andNameNotLike(String value) {
addCriterion("name not like", value, "name");
return (Criteria) this;
} public Criteria andNameIn(List<String> values) {
addCriterion("name in", values, "name");
return (Criteria) this;
} public Criteria andNameNotIn(List<String> values) {
addCriterion("name not in", values, "name");
return (Criteria) this;
} public Criteria andNameBetween(String value1, String value2) {
addCriterion("name between", value1, value2, "name");
return (Criteria) this;
} public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("name not between", value1, value2, "name");
return (Criteria) this;
} public Criteria andPriceIsNull() {
addCriterion("price is null");
return (Criteria) this;
} public Criteria andPriceIsNotNull() {
addCriterion("price is not null");
return (Criteria) this;
} public Criteria andPriceEqualTo(Float value) {
addCriterion("price =", value, "price");
return (Criteria) this;
} public Criteria andPriceNotEqualTo(Float value) {
addCriterion("price <>", value, "price");
return (Criteria) this;
} public Criteria andPriceGreaterThan(Float value) {
addCriterion("price >", value, "price");
return (Criteria) this;
} public Criteria andPriceGreaterThanOrEqualTo(Float value) {
addCriterion("price >=", value, "price");
return (Criteria) this;
} public Criteria andPriceLessThan(Float value) {
addCriterion("price <", value, "price");
return (Criteria) this;
} public Criteria andPriceLessThanOrEqualTo(Float value) {
addCriterion("price <=", value, "price");
return (Criteria) this;
} public Criteria andPriceIn(List<Float> values) {
addCriterion("price in", values, "price");
return (Criteria) this;
} public Criteria andPriceNotIn(List<Float> values) {
addCriterion("price not in", values, "price");
return (Criteria) this;
} public Criteria andPriceBetween(Float value1, Float value2) {
addCriterion("price between", value1, value2, "price");
return (Criteria) this;
} public Criteria andPriceNotBetween(Float value1, Float value2) {
addCriterion("price not between", value1, value2, "price");
return (Criteria) this;
} public Criteria andDetailIsNull() {
addCriterion("detail is null");
return (Criteria) this;
} public Criteria andDetailIsNotNull() {
addCriterion("detail is not null");
return (Criteria) this;
} public Criteria andDetailEqualTo(String value) {
addCriterion("detail =", value, "detail");
return (Criteria) this;
} public Criteria andDetailNotEqualTo(String value) {
addCriterion("detail <>", value, "detail");
return (Criteria) this;
} public Criteria andDetailGreaterThan(String value) {
addCriterion("detail >", value, "detail");
return (Criteria) this;
} public Criteria andDetailGreaterThanOrEqualTo(String value) {
addCriterion("detail >=", value, "detail");
return (Criteria) this;
} public Criteria andDetailLessThan(String value) {
addCriterion("detail <", value, "detail");
return (Criteria) this;
} public Criteria andDetailLessThanOrEqualTo(String value) {
addCriterion("detail <=", value, "detail");
return (Criteria) this;
} public Criteria andDetailLike(String value) {
addCriterion("detail like", value, "detail");
return (Criteria) this;
} public Criteria andDetailNotLike(String value) {
addCriterion("detail not like", value, "detail");
return (Criteria) this;
} public Criteria andDetailIn(List<String> values) {
addCriterion("detail in", values, "detail");
return (Criteria) this;
} public Criteria andDetailNotIn(List<String> values) {
addCriterion("detail not in", values, "detail");
return (Criteria) this;
} public Criteria andDetailBetween(String value1, String value2) {
addCriterion("detail between", value1, value2, "detail");
return (Criteria) this;
} public Criteria andDetailNotBetween(String value1, String value2) {
addCriterion("detail not between", value1, value2, "detail");
return (Criteria) this;
} public Criteria andPicIsNull() {
addCriterion("pic is null");
return (Criteria) this;
} public Criteria andPicIsNotNull() {
addCriterion("pic is not null");
return (Criteria) this;
} public Criteria andPicEqualTo(String value) {
addCriterion("pic =", value, "pic");
return (Criteria) this;
} public Criteria andPicNotEqualTo(String value) {
addCriterion("pic <>", value, "pic");
return (Criteria) this;
} public Criteria andPicGreaterThan(String value) {
addCriterion("pic >", value, "pic");
return (Criteria) this;
} public Criteria andPicGreaterThanOrEqualTo(String value) {
addCriterion("pic >=", value, "pic");
return (Criteria) this;
} public Criteria andPicLessThan(String value) {
addCriterion("pic <", value, "pic");
return (Criteria) this;
} public Criteria andPicLessThanOrEqualTo(String value) {
addCriterion("pic <=", value, "pic");
return (Criteria) this;
} public Criteria andPicLike(String value) {
addCriterion("pic like", value, "pic");
return (Criteria) this;
} public Criteria andPicNotLike(String value) {
addCriterion("pic not like", value, "pic");
return (Criteria) this;
} public Criteria andPicIn(List<String> values) {
addCriterion("pic in", values, "pic");
return (Criteria) this;
} public Criteria andPicNotIn(List<String> values) {
addCriterion("pic not in", values, "pic");
return (Criteria) this;
} public Criteria andPicBetween(String value1, String value2) {
addCriterion("pic between", value1, value2, "pic");
return (Criteria) this;
} public Criteria andPicNotBetween(String value1, String value2) {
addCriterion("pic not between", value1, value2, "pic");
return (Criteria) this;
} public Criteria andCreatetimeIsNull() {
addCriterion("createtime is null");
return (Criteria) this;
} public Criteria andCreatetimeIsNotNull() {
addCriterion("createtime is not null");
return (Criteria) this;
} public Criteria andCreatetimeEqualTo(Date value) {
addCriterion("createtime =", value, "createtime");
return (Criteria) this;
} public Criteria andCreatetimeNotEqualTo(Date value) {
addCriterion("createtime <>", value, "createtime");
return (Criteria) this;
} public Criteria andCreatetimeGreaterThan(Date value) {
addCriterion("createtime >", value, "createtime");
return (Criteria) this;
} public Criteria andCreatetimeGreaterThanOrEqualTo(Date value) {
addCriterion("createtime >=", value, "createtime");
return (Criteria) this;
} public Criteria andCreatetimeLessThan(Date value) {
addCriterion("createtime <", value, "createtime");
return (Criteria) this;
} public Criteria andCreatetimeLessThanOrEqualTo(Date value) {
addCriterion("createtime <=", value, "createtime");
return (Criteria) this;
} public Criteria andCreatetimeIn(List<Date> values) {
addCriterion("createtime in", values, "createtime");
return (Criteria) this;
} public Criteria andCreatetimeNotIn(List<Date> values) {
addCriterion("createtime not in", values, "createtime");
return (Criteria) this;
} public Criteria andCreatetimeBetween(Date value1, Date value2) {
addCriterion("createtime between", value1, value2, "createtime");
return (Criteria) this;
} public Criteria andCreatetimeNotBetween(Date value1, Date value2) {
addCriterion("createtime not between", value1, value2, "createtime");
return (Criteria) this;
}
} public static class Criteria extends GeneratedCriteria { protected Criteria() {
super();
}
} public static class Criterion {
private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() {
return condition;
} public Object getValue() {
return value;
} public Object getSecondValue() {
return secondValue;
} public boolean isNoValue() {
return noValue;
} public boolean isSingleValue() {
return singleValue;
} public boolean isBetweenValue() {
return betweenValue;
} public boolean isListValue() {
return listValue;
} public String getTypeHandler() {
return typeHandler;
} protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
} protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
} protected Criterion(String condition, Object value) {
this(condition, value, null);
} protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
} protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
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 }/queryItem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td>商品名称:</td>
<td><input type="text" name="item.name"/></td>
</tr>
<tr>
<td>商品id:</td>
<td><input type="text" name="item.id"/></td>
</tr>
<tr>
<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>${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>
itemEdit.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>
<!-- 上传图片是需要指定属性 enctype="multipart/form-data" -->
<!-- <form id="itemForm" action="" method="post" 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>
<c:if test="${item.pic !=null}">
<img src="/pic/${item.pic}" width=100 height=100/>
<br/>
</c:if>
<input type="file" name="pictureFile"/>
</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>
</body> </html>
将自定义的 Date 转换器DateConveter,导入
package com.ssm.converter; import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; import org.springframework.core.convert.converter.Converter;
/**
* 时间Date的转换器
* @author Administrator
*
*/
//泛型:第一个参数表示:数据源数据,也就是传进来的数据类型
//第二个参数表示:转换后的数据类型
public class DateConverter implements Converter<String, Date> { @Override
public Date convert(String source) {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(source);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
} }
然后开始写springMVC代码,自定义一个Controller
框架默认支持的参数类型
处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值。
1 HttpServletRequest 通过request对象获取请求信息
2 HttpServletResponse 通过response处理响应信息
3 HttpSession 通过session对象得到session中存放的对象
4 Model/ModelMap ModelMap是Model接口的实现类,通过Model或ModelMap向页面传递数据,
注意:如果使用Model则可以不使用ModelAndView对象,Model对象可以向页面传递数据,View对象则可以使用String返回值替代。不管是Model还是ModelAndView,其本质都是使用Request对象向jsp传递数据。
package com.ssm.controller; import java.util.List; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; import com.ssm.pojo.Item;
import com.ssm.pojo.QueryVo;
import com.ssm.service.IItemService; @Controller
public class ItemController {
@Resource
private IItemService itemService; //查询所有商品
@RequestMapping("/list.action")
public ModelAndView findItemByAll(){
ModelAndView modelAndView = new ModelAndView();
List<Item> list = itemService.findItemByAll();
modelAndView.addObject("itemList", list);
modelAndView.setViewName("itemList");
return modelAndView;
} //根据Id查询商品 :通过id查询商品第一种方式:通过原始的request获取参数
// @RequestMapping("/itemEdit")
// public ModelAndView findItemById(HttpServletRequest request){
// ModelAndView modelAndView = new ModelAndView();
// String string = request.getParameter("id");
// if(string.matches("[0-9]+")){
// Item item = itemService.findItemById(Integer.parseInt(string));
// modelAndView.addObject("item",item);
// }
// modelAndView.setViewName("itemEdit");
// return modelAndView;
// } //根据Id查询商品 :第二种方式:框架直接会会给我们传过来的参数赋值,名字必须一样,
//必须是简单类型的,复杂类型要配置
// @RequestMapping("/itemEdit")
// public ModelAndView findItemById(Integer id){
// ModelAndView modelAndView = new ModelAndView();
// Item item = itemService.findItemById(id);
// modelAndView.addObject("item",item);
// modelAndView.setViewName("itemEdit");
// return modelAndView;
// } //根据Id查询商品 :第三种方式:当参数名字与页面传过来的参数名不一致时,通过注解来配置映射关系
//@RequestParam,常常用于简单类型的映射
//value:表示映射的字段名,就是页面传递的name值
//required:是否是必须的
//defaultValue:默认值
// @RequestMapping("/itemEdit")
// public ModelAndView findItemById(@RequestParam(value="id",required=true,defaultValue="1")Integer itemId){
// ModelAndView modelAndView = new ModelAndView();
// Item item = itemService.findItemById(itemId);
// modelAndView.addObject("item",item);
// modelAndView.setViewName("itemEdit");
// return modelAndView;
// } //根据Id查询商品 :第四种方式:通过model或者modelMap,返回值就可以撒设成String,返回的是视图的名称
@RequestMapping("/itemEdit")
public String findItemById(Integer id,Model model,ModelMap modelMap){
Item item = itemService.findItemById(id);
//model.addAttribute("item", item);
modelMap.addAttribute("item", item);
return "itemEdit";
} //修改商品 注意:item这个pojo类中的birthday是data类型的,复杂数据类型 pattern表示转换的格式
//框架不能自动封装,会报错;
//解决方案1:在这个pojo的birthday属性上加上@DateTimeFormat(pattern="yyyy-MM-dd HH-ss-mm")注意:加这个注解:springmvc的配置文件中必须配置了"<mvc:annotation-driven/>"
//解决方案2:自定义转换器,配置全局
@RequestMapping("/updateItem")
public String updateItem(Item item){
itemService.updateItem(item);
return "itemList";
} //条件查询
@RequestMapping("/queryItem")
//这里使用queryVo查询条件的封装类,在页面的namey要写成item.id,item.name,item要与queryVo类中的属性名一致,
//Id和那么与item中的属性名一致
public String findItemByWhere(QueryVo vo,Model model){
List<Item> list=itemService.findItemByWhere(vo);
model.addAttribute("itemList", list);
return "itemList";
}
}
然后编写service层的代码
service的接口
package com.ssm.service; import java.util.List; import com.ssm.pojo.Item;
import com.ssm.pojo.QueryVo; /**
* item的业务层接口
* @author Administrator
*
*/
public interface IItemService {
//通过Id查询商品
public Item findItemById(Integer id); //查询所有商品
public List<Item> findItemByAll();
//修改商品
public void updateItem(Item item);
//条件查询
public List<Item> findItemByWhere(QueryVo vo);
}
service层的实现类
package com.ssm.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.ssm.dao.mapper.ItemMapper;
import com.ssm.pojo.Item;
import com.ssm.pojo.ItemExample;
import com.ssm.pojo.ItemExample.Criteria;
import com.ssm.pojo.QueryVo;
import com.ssm.service.IItemService;
@Service
public class ItemServiceImpl implements IItemService { @Resource
private ItemMapper itemMapper; //通过id查询
@Override
public Item findItemById(Integer id) { return itemMapper.selectByPrimaryKey(id);
}
//查询所有
@Override
public List<Item> findItemByAll() {
ItemExample example=new ItemExample(); return itemMapper.selectByExample(example);
} //更新商品
@Override
public void updateItem(Item item) {
//第一种方式
// ItemExample example=new ItemExample();
// itemMapper.updateByExample(item, example);
//第二种方式
itemMapper.updateByPrimaryKey(item); //这表示如果这个字段为空""或null这个字段就不更新
//itemMapper.updateByPrimaryKeySelective(item);
} //条件查询
@Override
public List<Item> findItemByWhere(QueryVo vo) {
Item item=vo.getItem();
ItemExample example=new ItemExample();
Criteria criteria = example.createCriteria();
if(item.getId()!=null){
criteria.andIdEqualTo(item.getId());
}
if(item.getName()!=null&&!"".equals(item.getName())){
criteria.andNameLike("%"+item.getName()+"%");
}
return itemMapper.selectByExample(example);
} }
springmvc的简单使用以及ssm框架的整合的更多相关文章
- 【转】SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
原文地址:http://blog.csdn.net/zhshulin/article/details/37956105 使用SSM(Spring.SpringMVC和Mybatis)已经有三个多月了, ...
- Maven整合SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
使用SSM(Spring.SpringMVC和Mybatis)已经有三个多月了,项目在技术上已经没有什么难点了,基于现有的技术就可以实现想要的功能,当然肯定有很多可以改进的地方.之前没有记录SSM整合 ...
- SSM框架的整合与使用——实现简单的转账系统
一.整合思路 SSM框架即SpringMVC + Spring + MyBati框架集,是一种轻量级的Web开源框架.它们各自在JAVA三层架构中负责的模块如下图所示: 其中,SpringMVC与Sp ...
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)【申明:来源于网络】
SSM框架--详细整合教程(Spring+SpringMVC+MyBatis)[申明:来源于网络] 地址:http://blog.csdn.net/u014662268/article/details ...
- SSM框架的整合思路&功能实现
这是我第一篇博客,关于SSM框架的整合思路以及简单功能实现. 首先,最近刚刚学习Spring+SpringMVC+Mybatis,在开发时遇到形形色色的问题,周遭人也为我提供了一些思路,我会一点点整理 ...
- SSM框架快速整合实例——学生查询
一.快速准备 SSM 框架即 Spring 框架.SpringMVC 框架.MyBatis 框架,关于这几个框架的基础和入门程序,我前面已经写过几篇文章作为基础和入门介绍了.这里再简单的介绍一下: 1 ...
- SSM框架——详细整合教程
SSM框架——详细整合教程(Spring+SpringMVC+MyBatis) 1.基本概念 1.1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Jav ...
- SSM 框架快速整合实例--学生查询
一.快速准备 SSM 框架即 Spring 框架.SpringMVC 框架.MyBatis 框架,关于这几个框架的基础和入门程序,我前面已经写过几篇文章作为基础和入门介绍了.对于这 3 个框架还不熟悉 ...
- springmvc文件上传下载简单实现案例(ssm框架使用)
springmvc文件上传下载实现起来非常简单,此springmvc上传下载案例适合已经搭建好的ssm框架(spring+springmvc+mybatis)使用,ssm框架项目的搭建我相信你们已经搭 ...
随机推荐
- Makefile 系统论述
该篇文章为转载,是对原作者系列文章的总汇加上标注. 支持原创,请移步陈浩大神博客: http://blog.csdn.net/haoel/article/details/2886 概述 什么是make ...
- ansible批量管理工具的搭建与简单的操作
ansible的安装 # [root@localhost ~]# cat /etc/redhat-release CentOS Linux release (Core) [root@localhost ...
- 错误:Bean property 'sessionFactory' is not writable or has an invalid setter method.
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'sessionFactory' ...
- vuex-Mutation(同步)
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation.Vuex 中的 mutation 非常类似于事件: 每个 mutation 都有一个字符串的 事件类型 (type) 和 一 ...
- dede织梦 dede:arclist当前索引值
{dede:arclist row='10' titlelen='50' flag='c'} <li class="rank[field:global name='autoindex' ...
- 四:(之八_Linux压力测试工具stress)Dockerfile语法梳理和实践
8.1 安装stress stress目前是在该目录下的可执行文件 --vm 创建几个进程 --vm-bytes 为每个进程分配多少内存 8.2 debug输出stress创建进程的过程 一直在创建有 ...
- Hashmap的学习整理
这是我大致了解Hashmap的第一个博客:https://www.cnblogs.com/chengxiao/p/6059914.html 我将摘录里面的重点: 哈希表的主干就是数组 存储位置 = f ...
- web.xml配置以及一些详解
web.xml的根元素定义如下所示(代表当前使用哪个模版): <?xml version="1.0" encoding="UTF-8"?> < ...
- 高级数据类型-- 字符串(str),切片
一.字符串 字符串 就是 一串字符,是编程语言中表示文本的数据类型 在 Python 中可以使用 一对双引号" 或者 一对单引号' 定义一个字符串 虽然可以使用 \" 或者 \' ...
- dos脚本2
一.简单批处理内部命令简介 1.Echo 命令 打开回显或关闭请求回显功能,或显示消息.如果没有任何参数,echo 命令将显示当 前回显设置. 语法 echo [{on off}] [mess ...