springMvc:是一个表现层框架,它是Spring框架的一部分.做用是从请求中接收传入的参数,及将处理后的结果数据返回给页面展现.html
架构流程前端
(处理器映射器就像一个map集合,key是用户在浏览器url中输入的地址,value是对应的方法对象.这时若是有拦截器则进行判断,符合要求则放行,不然就进行拦截) java
如下组件一般使用框架提供实现:mysql
用户请求到达前端控制器,它就至关于mvc模式中的c,dispatcherServlet是整个流程控制的中心,由它调用其它组件处理用户的请求,dispatcherServlet的存在下降了组件之间的耦合性。程序员
HandlerMapping负责根据用户请求找到Handler即处理器,springmvc提供了不一样的映射器实现不一样的映射方式,例如:配置文件方式,实现接口方式,注解方式等。web
Handler 是继DispatcherServlet前端控制器的后端控制器,在DispatcherServlet的控制下Handler对具体的用户请求进行处理。spring
因为Handler涉及到具体的用户业务请求,因此通常状况须要程序员根据业务需求开发Handler。sql
经过HandlerAdapter对处理器进行执行,这是适配器模式的应用,经过扩展适配器能够对更多类型的处理器进行执行。数据库
View Resolver负责将处理结果生成View视图,View Resolver首先根据逻辑视图名解析成物理视图名即具体的页面地址,再生成View视图对象,最后对View进行渲染将处理结果经过页面展现给用户。apache
springmvc框架提供了不少的View视图类型的支持,包括:jstlView、freemarkerView、pdfView等。咱们最经常使用的视图就是jsp。
通常状况下须要经过页面标签或页面模版技术将模型数据经过页面展现给用户,须要由程序员根据业务需求开发具体的页面。
说明:在springmvc的各个组件中,处理器映射器、处理器适配器、视图解析器称为springmvc的三大组件。 须要用户开发的组件有handler、view(即controller和jsp) |
新建工程à导入springMvc独立运行的jar包à在web.xml中配置前端控制器à编写springMvc核心配置文件,pojo,controller,jsp
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>SpringMvc0523</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>
<!-- 若是没有制定springMvc核心配置文件,那么默认会去找/WEB-INF/+<servlet-name>中的内容 + -servlet.xml配置文件 --> <!-- 指定核心配置文件位置 --> <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> </web-app> |
Tips: org.springframework.web.servlet.DispatcherServlet的位置以下:
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.itcast.controller"></context:component-scan>
<!-- 若是没有显示的配置处理器映射器和处理器适配那么springMvc会去默认的dispatcherServlet.properties中查找, 对应的处理器映射器和处理器适配器去使用,这样每一个请求都要扫描一次他的默认配置文件,效率很是低,会下降访问速度,因此要显示的配置处理器映射器和处理器适配器 -->
<!-- 注解形式的处理器映射器(已过期) --> <!--<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> --> <!-- 注解形式的处理器适配器(已过期) --> <!--<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean> -->
<!-- 配置最新版的注解的处理器映射器 --> <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> --> <!-- 配置最新版的注解的处理器适配器 --> <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> -->
<!-- 注解驱动: 做用:替咱们自动配置最新版的注解的处理器映射器和处理器适配器 --> <mvc:annotation-driven></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>
</beans> |
Tips:
1.若是没有显示的配置处理器映射器和处理器适配那么springMvc会去默认的dispatcherServlet.properties中查找
dispatcherServlet.properties:
2. org.springframework.web.servlet.view.InternalResourceViewResolver:
若是没有配置视图解析器,那么在Controller中指定要返回的页面的位置时,都要写全网页的路径名称,如:
modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
Items.java:
public class Items {
private Integer id; private String name; private Float price; private String pic; private Date createtime; private String detail;
get,set方法… } |
ItemsController:
@Controller public class ItemsController {
@RequestMapping("/list") public ModelAndView itemsList() throws Exception{
List<Items> itemList = new ArrayList<>(); //商品列表 Items items_1 = new Items(); items_1.setName("联想笔记本_3"); items_1.setPrice(6000f); items_1.setDetail("ThinkPad T430 联想笔记本电脑!");
Items items_2 = new Items(); items_2.setName("苹果手机"); items_2.setPrice(5000f); items_2.setDetail("iphone6苹果手机!");
itemList.add(items_1); itemList.add(items_2);
//模型和视图 //model模型:模型对象中存放了要返回给页面的数据 //view视图:视图对象中指定了要返回的页面的位置 ModelAndView modelAndView = new ModelAndView();
//将要返回给页面的数据放入模型和视图对象中 modelAndView.addObject("itemList", itemList);
//指定要返回的页面的位置 modelAndView.setViewName("itemList ");
return modelAndView; } } |
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 }/item/queryitem.action" method="post"> 查询条件: <table width="100%" border=1> <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> |
步骤:
1)Dao层
pojo和映射文件以及接口使用逆向工程生成
SqlMapConfig.xml mybatis核心配置文件
ApplicationContext-dao.xml 整合后spring在dao层的配置
数据源
会话工厂
扫描Mapper
2)service层
事务 ApplicationContext-trans.xml
@Service注解扫描 ApplicationContext-service.xml
3)controller层
SpringMvc.xml
注解扫描:扫描@Controller注解
注解驱动:替咱们显示的配置了最新版的处理器映射器和处理器适配器
视图解析器:显示的配置是为了在controller中不用每一个方法都写页面的全路径
4)web.xml
springMvc前端控制器配置
spring监听
建立工程,导入jar包(主要是Mybatis和Spring整合的jar包,由于SpringMvc和Spring都是Spring公司出的,不须要整合),再按整合步骤慢慢来:
Dao层:
先创建数据库(springmvc)和表:
再利用逆向工程生成pojo,映射文件以及接口:
StarServer:
public class StartServer {
public void generator() throws Exception{ List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("generator.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 { StartServer startServer = new StartServer(); startServer.generator(); } catch (Exception e) { e.printStackTrace(); } } } |
Generator.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration> <context id="testTables" targetRuntime="MyBatis3"> <commentGenerator> <!-- 是否去除自动生成的注释 true:是: false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--数据库链接的信息:驱动类、链接地址、用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/springmvc" userId="root" password="root"> </jdbcConnection> <!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver" connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" userId="yycg" password="yycg"> </jdbcConnection> -->
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver>
<!-- targetProject:生成PO类的位置 --> <javaModelGenerator targetPackage="cn.itheima.pojo" targetProject=".\src"> <!-- enableSubPackages:是否让schema做为包的后缀 --> <property name="enableSubPackages" value="false" /> <!-- 从数据库返回的值被清理先后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- targetProject:mapper映射文件生成的位置 --> <sqlMapGenerator targetPackage="cn.itheima.dao" targetProject=".\src"> <!-- enableSubPackages:是否让schema做为包的后缀 --> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- targetPackage:mapper接口生成的位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="cn.itheima.dao" targetProject=".\src"> <!-- enableSubPackages:是否让schema做为包的后缀 --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 指定数据库表 --> <!-- <table tableName="items"></table> --> <table tableName="items"></table> <!-- <table tableName="orderdetail"></table> --> <table tableName="user"></table> <!-- <table schema="" tableName="sys_user"></table> <table schema="" tableName="sys_role"></table> <table schema="" tableName="sys_permission"></table> <table schema="" tableName="sys_user_role"></table> <table schema="" tableName="sys_role_permission"></table> -->
<!-- 有些表的字段须要指定java类型 <table schema="" tableName=""> <columnOverride column="" javaType="" /> </table> --> </context> </generatorConfiguration> |
运行StarServer后:
将生成的这些文件复制到项目中.
Mybatis核心配置文件 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>
</configuration> |
ApplicationContext-dao.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 加载配置文件 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 数据库链接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="10" /> <property name="maxIdle" value="5" /> </bean>
<!-- mapper配置 --> <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据库链接池 --> <property name="dataSource" ref="dataSource" /> <!-- 加载mybatis的全局配置文件 --> <property name="configLocation" value="classpath:SqlMapConfig.xml" /> </bean>
<!-- 配置Mapper扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.itheima.dao"/> </bean> </beans> |
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"> <!-- 数据源 --> <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.itheima.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.itheima.service"></context:component-scan> </beans> |
controller层:
SpringMvc.xml:
注解扫描:扫描@Controller注解
注解驱动:替咱们显示地配置了最新版的处理器映射器和处理器适配器
视图解析器:显示的配置是为了在controller中不用每一个方法都写页面的全路径
<?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.itheima.controller"></context:component-scan>
<!-- 注解驱动: 替咱们显示的配置了最新版的注解的处理器映射器和处理器适配器 --> <mvc:annotation-driven></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> </beans> |
web.xml:
springMvc前端控制器配置
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_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> </web-app> |
新建controller,service接口及其实现类,将页面复制过来:
itemsController:
@Controller public class itemsController {
@Autowired private ItemsService itemService;
@RequestMapping("/list") public ModelAndView itemsList() throws Exception{
List<Items> itemList = itemService.list();
ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("itemList", itemList); modelAndView.setViewName("itemList");
return modelAndView; } } |
Tips: @Autowired和@Resource: @Autowired为自动装配,因此若是该接口只有一个实现类,用哪一个注解均可以,但若是该接口有多个实现类,那只能用@Resource.
ItemsServiceImpl:
@Service public class ItemsServiceImpl implements ItemsService{
@Autowired private ItemsMapper itemsMapper;
public List<Items> list() { //若是不须要任何查询条件,直接将example对象new出来便可 ItemsExample example = new ItemsExample(); List<Items> list = itemsMapper.selectByExampleWithBLOBs(example ); return list; } } |
Tips:
不用selectByExample(example)方法,是由于items中的detail是大文本类型,若用了该方法,则查询不出该字段.
需求:在商品列表页面点击"修改"按钮时,页面跳转到修改页面(将要修改的商品信息展现出来).
itemsController:
@Controller public class itemsController {
@Autowired private ItemsService itemService;
@RequestMapping("/list") public ModelAndView itemsList() throws Exception{…}
/** *springMvc中默认支持的参数类型:也就是说在controller方法中能够加入这些也能够不加, 加不加看本身需不须要,都行. *HttpServletRequest *HttpServletResponse *HttpSession *Model */ @RequestMapping("itemEdit") public String itemEdit(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws Exception{
String idStr = request.getParameter("id");
Items items = itemService.findItemsById(Integer.parseInt(idStr));
//Model模型:模型中放入了返回给页面的数据 //model底层其实就是用的request域来传递数据,可是对request域进行了扩展. model.addAttribute("item",items);
//若是springMvc方法返回一个简单的string字符串,那么springMvc就会认为这个字符串就是页面的名称 return "editItem"; } } |
Tips:由于用getParameter方法从页面接收过来的数据都会变成String类型,而id是Integer类型的,因此要进行转换.
ItemsServiceImpl:
@Service public class ItemsServiceImpl implements ItemsService{
@Autowired private ItemsMapper itemsMapper;
@Override public List<Items> list() {…}
@Override public Items findItemsById(Integer id) { Items items = itemsMapper.selectByPrimaryKey(id); return items; } } |
需求:修改指定的商品信息.
itemsController:
@Controller public class itemsController {
@Autowired private ItemsService itemService;
@RequestMapping("/list") public ModelAndView itemsList() throws Exception{…}
/** *springMvc中默认支持的参数类型:也就是说在controller方法中能够加入这些也能够不加, 加不加看本身需不须要,都行. *HttpServletRequest *HttpServletResponse *HttpSession *Model */ @RequestMapping("itemEdit") public String itemEdit(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws Exception{…}
//springMvc能够直接接收基本数据类型,包括string.spirngMvc能够帮你自动进行类型转换. //controller方法接收的参数的变量名称必需要等于页面上input框的name属性值 @RequestMapping("updateitem") public String update(Integer id, String name, Float price, String detail) throws Exception{
Items items = new Items(); items.setId(id); items.setName(name); items.setPrice(price); items.setDetail(detail); items.setCreatetime(new Date());
itemService.update(items);
return"success"; } } |
Tips:参数列表中的参数都是从页面传过来的,虽然修改页面的日期被注释掉了,但仍要给他new个日期,由于该字段在数据库中被设置为非空.
补充(了解便可):
通常controller方法接收的参数的变量名称必需要等于页面上input框的name属性值,但若是加了@RequestParam("input框的name属性值")的话,参数名称就随便写了:
ItemsServiceImpl:
@Service public class ItemsServiceImpl implements ItemsService{
@Autowired private ItemsMapper itemsMapper;
@Override public List<Items> list() {…}
@Override public Items findItemsById(Integer id) {…}
@Override public void update(Items items) { itemsMapper.updateByPrimaryKeyWithBLOBs(items); } } |
Tips:用updateByPrimaryKeyWithBLOBs(items)是由于用反向工程生成的ItemsMapper.xml中相似的其余方法不能查询到Items中的detail属性(大文本格式),而该方法能够:
在浏览器url中输入的地址及后面带参数的,都是get请求,表单提交,修改和保存的都是post请求.在此,是post请求,会出现乱码问题,所以要解决post请求乱码的问题:
在web.xml中加入如下代码:
<!-- 配置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> |
解决get请求乱码的问题有如下两种方法:
<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编码
ItemsController:
@Controller public class itemsController {
@Autowired private ItemsService itemService;
//springMvc能够直接接收基本数据类型,包括string.spirngMvc能够帮你自动进行类型转换. //controller方法接收的参数的变量名称必需要等于页面上input框的name属性值 //spirngMvc能够直接接收pojo类型:要求页面上input框的name属性名称必须等于pojo的属性名称 @RequestMapping("updateitem") public String update(Items items) throws Exception{
items.setCreatetime(new Date());
itemService.update(items);
return"success"; } } |
Tips: spirngMvc能够直接接收pojo类型:要求页面上input框的name属性名称必须等于pojo的属性名称!!!
应用场景:好比须要进行高级查询时,既要经过商品信息进行查询,也还可能要用用户信息和其余信息进行查询,这时用pojo类接收是不够的,应该用vo(封装类)接收.
新建一个vo包:
QueryVo:
package cn.itheima.vo;
import cn.itheima.pojo.Items;
public class QueryVo {
//商品对象 private Items items;
//用户对象... //订单对象...
public Items getItems() { return items; } public void setItems(Items items) { this.items = items; } } |
ItemsController:
@Controller public class itemsController {
@Autowired private ItemsService itemService;
@RequestMapping("/list") public ModelAndView itemsList() throws Exception{…}
/** *springMvc中默认支持的参数类型:也就是说在controller方法中能够加入这些也能够不加, 加不加看本身需不须要,都行. *HttpServletRequest *HttpServletResponse *HttpSession *Model */ @RequestMapping("itemEdit") public String itemEdit(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws Exception{…}
//springMvc能够直接接收基本数据类型,包括string.spirngMvc能够帮你自动进行类型转换. //controller方法接收的参数的变量名称必需要等于页面上input框的name属性值 //spirngMvc能够直接接收pojo类型:要求页面上input框的name属性名称必须等于pojo的属性名称 @RequestMapping("updateitem") public String update(Items items) throws Exception{…}
//若是Controller中接收的是Vo,那么页面上input框的name属性值要等于vo的属性.属性.属性..... @RequestMapping("/search") public String search(QueryVo vo) throws Exception{
System.out.println(vo); return ""; } } |
ItemList页面中:
查询条件: <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> |
打断点测试,是有值的:
createTime为Date类型,且此字段在数据库中被设置为非空.若将Controller中update()里对createTime的处理注释掉, 放开修改页面中对createTime修改语句的注释,此时启动服务器,在修改页面对createTime进行修改,则会报错.缘由是createTime是Date类型,页面传过来的是String类型,而Controller中没有将String转换为Date,因此会报错:
这时候咱们须要自定义转换器:
新建个转换器包,在包下新建一个自定义的全局的String到Date的转换器类:
CustomGlobalStrToDateConverter:
import org.springframework.core.convert.converter.Converter; /** * String:源 * Date:目标 * @author Tan * */ public class CustomGlobalStrToDateConverter implements Converter<String, Date> {
@Override public Date convert(String source) {
try {
Date date = new SimpleDateFormat("yy-MM-DD hh:mm:ss").parse(source); return date;
} catch (ParseException e) { e.printStackTrace(); } return null; } } |
Tips:不熟悉SimpleDateFormat()相关方法的话,自行查阅JDK文档.
写完自定义转换器类后,要在SpringMvc.xml中进行配置:
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.itheima.controller"></context:component-scan>
<!-- 注解驱动: 替咱们显示的配置了最新版的注解的处理器映射器和处理器适配器 --> <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.itheima.controller.converter.CustomGlobalStrToDateConverter"/> </set> </property> </bean> </beans> |
从接收数据和向页面传递数据两个方面进行简单说明:
接收数据:
Struts2用模型/属性驱动接收数据,model/属性都是全局变量,全局变量中存放着数据,Action中的任何方法均可以用,所以线程不安全,所以Action才要作成多例的;
而SpringMvc用局部变量接收数据,线程安全,所以Controller是单例的.(不必开多例,浪费资源).
向页面传递数据:
Struts2经过值栈向页面传递数据;
而SpringMvc经过model向页面传递数据,model底层采用的是request域.
较为官方的解释:
1. springMvc:是一个表现层框架,
做用:就是从请求中接收传入的参数,
将处理后的结果数据返回给页面展现
2. ssm整合:
1)Dao层
pojo和映射文件以及接口使用逆向工程生成
SqlMapConfig.xml mybatis核心配置文件
ApplicationContext-dao.xml 整合后spring在dao层的配置
数据源
会话工厂
扫描Mapper
2)service层
事务 ApplicationContext-trans.xml
@Service注解扫描 ApplicationContext-service.xml
3)controller层
SpringMvc.xml
注解扫描:扫描@Controller注解
注解驱动:替咱们显示的配置了最新版的处理器映射器和处理器适配器
视图解析器:显示的配置是为了在controller中不用每一个方法都写页面的全路径
4)web.xml
springMvc前端控制器配置
spring监听
3.参数绑定(从请求中接收参数)重点
1)默认类型:
在controller方法中能够有也能够没有,看本身需求随意添加.
httpservletRqeust,httpServletResponse,httpSession,Model(ModelMap其实就是Mode的一个子类,通常用的很少)
2)基本类型:string,double,float,integer,long.boolean
3)pojo类型:页面上input框的name属性值必需要等于pojo的属性名称
4)vo类型:页面上input框的name属性值必需要等于vo中的属性.属性.属性....
5)自定义转换器converter:
做用:因为springMvc没法将string自动转换成date因此须要本身手动编写类型转换器
须要编写一个类实现Converter接口
在springMvc.xml中配置自定义转换器
在springMvc.xml中将自定义转换器配置到注解驱动上
最终目录结构: