解析 :Spring mvc 是Spring框架的一部分,基于mvc 的表现层框架 , 用于web项目开发
简单来说就是 m(model) 模型- v(view) 视图 - c(controller) 控制器 , 三次架构设计模式 。 主要用于前端页面的展示和后端业务数据处理逻辑分离
模式优点:分层设计 , 实现我们业务系统各个组件之间的解耦 , 有利于业务系统的可拓展性 , 维护性 , 有利于并行开发,提升开发效率
创建一个web 项目
加入pom.xml的依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.dsdd.weyougroupId>
<artifactId>springmvc-firstartifactId>
<version>0.0.1-SNAPSHOTversion>
<packaging>warpackaging>
<name>springmvc-first Maven Webappname>
<url>http://maven.apache.orgurl>
<properties>
<spring.version>4.3.8.RELEASEspring.version>
<jstl.version>1.2jstl.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>${jstl.version}version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<version>2.1version>
<configuration>
<port>8080port>
<path>/springmvc-firstpath>
<uriEncoding>UTF-8uriEncoding>
<server>tomcat7server>
configuration>
plugin>
plugins>
build>
project>
加入SpringMvc.xml
<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.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
beans>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>springmvc-firstdisplay-name>
<servlet>
<servlet-name>springmvc-firstservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvc-firstservlet-name>
<url-pattern>*.dourl-pattern>
servlet-mapping>
<welcome-file-list>
<welcome-file>index.htmlwelcome-file>
<welcome-file>index.htmwelcome-file>
<welcome-file>index.jspwelcome-file>
<welcome-file>default.htmlwelcome-file>
<welcome-file>default.htmwelcome-file>
<welcome-file>default.jspwelcome-file>
welcome-file-list>
web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
springmvc入门程序
你好,世界。${hello}
// @Controller注解:用于标记普通的java类,作为控制器
@Controller
public class HelloController {
// ModelAndView:模型和视图,用于设置响应的模型数据,用于设置响应的视图
// @RequestMapping注解:配置请求的url
@RequestMapping("/hello.do")
public ModelAndView hello(){
// 1.创建ModelAndView对象
ModelAndView mav = new ModelAndView();
// 2.设置响应的模型数据
// addObject方法:设置响应的模型数据
// attributeName参数:模型的名称(hello)
// attributeValue参数:模型的数据
mav.addObject("hello", "springmvc!!!");
// 3.设置响应的视图
// setViewName方法:设置视图名称
// viewName参数:视图名称(jsp页面的物理路径)
mav.setViewName("/WEB-INF/jsp/hello.jsp");
return mav;
}
}
<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.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
beans>
解析 : 根据请求的url , 查找处理器
org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
在springmvc.xml中加入配置处理器映射器
<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.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">bean>
beans>
解析:执行处理器方法
org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
<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.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">bean>
beans>
<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.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
<mvc:annotation-driven>mvc:annotation-driven>
beans>
解析 :把逻辑视图(在controller设置的视图名称)解析成物理视图(在浏览器看到的页面)。
org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver
<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.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
<mvc:annotation-driven>mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/">property>
<property name="suffix" value=".jsp">property>
bean>
beans>
解析 :
1 用户页面请求 , 前端控制器接受用户请求***(DispatcherServlet 为springMvc的核心类)***
2 请求处理器映射器 , 查找处理器(处理器映射器:HandlerMapping查找处理器)
3 根据请求的url , 查找处理器(处理器Controller)
4 返回处理器到前端控制器
5 请求处理器适配器 , 执行处理器(处理器适配器:HandlerAdapter执行处理器)
6 执行处理器 ,返回模型和视图
7 请求解析视图 , 视图解析器(ViewResolve解析视图)
8 解析视图:jsp
9 返回视图 , 响应用户
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.dsdd.weyougroupId>
<artifactId>ssmartifactId>
<version>0.0.1-SNAPSHOTversion>
<packaging>warpackaging>
<name>ssm Maven Webappname>
<url>http://maven.apache.orgurl>
<properties>
<spring.version>4.3.8.RELEASEspring.version>
<aspectj.version>1.6.12aspectj.version>
<jstl.version>1.2jstl.version>
<mybatis.version>3.4.5mybatis.version>
<mybatis.spring.version>1.3.1mybatis.spring.version>
<mysql.version>5.1.30mysql.version>
<dbcp.version>1.2.2dbcp.version>
<slf4j.version>1.7.7slf4j.version>
<log4j.version>1.2.17log4j.version>
<commons.lang.version>2.6commons.lang.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>${aspectj.version}version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>${jstl.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>${mybatis.spring.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>${dbcp.version}version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>commons-langgroupId>
<artifactId>commons-langartifactId>
<version>${commons.lang.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
<scope>providedscope>
dependency>
dependencies>
<build>
<finalName>ssmfinalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<version>2.1version>
<configuration>
<port>8080port>
<path>/ssmpath>
<uriEncoding>UTF-8uriEncoding>
<server>tomcat7server>
configuration>
plugin>
plugins>
build>
project>
<configuration>
<typeAliases>
<package name="com.dsdd.weyou.po"/>
typeAliases>
configuration>
<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.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
<mvc:annotation-driven>mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/">property>
<property name="suffix" value=".jsp">property>
bean>
beans>
<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="${db.driverClassName}"/>
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
<property name="maxActive" value="${db.maxActive}"/>
<property name="minIdle" value="${db.minIdle}"/>
<property name="maxIdle" value="${db.maxIdle}"/>
<property name="initialSize" value="${db.initialSize}"/>
<property name="maxWait" value="${db.maxWait}"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.dsdd.weyou.mapper">property>
bean>
beans>
<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:component-scan base-package="com.dsdd.weyou.service"/>
beans>
<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="add*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="query*" propagation="SUPPORTS" read-only="true"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.dsdd.weyou.service..*.*(..))"/>
aop:config>
beans>
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/springmvc?characterEncoding=utf-8
db.username=root
db.password=admin
db.maxActive=10
db.minIdle=2
db.maxIdle=5
db.initialSize=5
db.maxWait=6000
# Global logging configuration
log4j.rootLogger=INFO, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ssmdisplay-name>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring/applicationContext-*.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>ssmservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring/springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>ssmservlet-name>
<url-pattern>*.dourl-pattern>
servlet-mapping>
<welcome-file-list>
<welcome-file>index.htmlwelcome-file>
<welcome-file>index.htmwelcome-file>
<welcome-file>index.jspwelcome-file>
<welcome-file>default.htmlwelcome-file>
<welcome-file>default.htmwelcome-file>
<welcome-file>default.jspwelcome-file>
welcome-file-list>
web-app>
通过HttpServletRequest对象,获取请求的参数 , 使用getParameter方法
通过response对象设置数据响应
通过session对象,获取到会话中的数据
Model是模型,用于设置响应的模型数据 ,ModelMap是Model接口的实现,使用ModelMap和使用Model是一样,如果使用Model,springmvc实例化成ModelMap ,使用Model响应模型数据,就可以不使用ModelAndView,使用字符串String响应视图。
// 使用Model设置响应模型数据,使用字符串响应视图
@RequestMapping("/queryItemById.do")
public String queryItemById(Model model,HttpServletRequest request){
// 1.获取参数
String id = request.getParameter("id");
// 2.根据商品Id查询商品
Item item = this.itemService.queryItemById(Integer.parseInt(id));
// 3.响应商品数据
// addAttribute方法:设置响应的模型数据
model.addAttribute("item", item);
return "item/itemEdit";
}
使用简单类型接收请求的参数,推荐使用简单类型的包装类型(Integer),不建议使用简单类型的基础类型(int)。原因是基础类型不能为null值,如果不传递会报异常。
常用注解:@RequestParam注解 ,设置请求的参数名称,与方法形参的名称匹配 。 属性value:设置请求的参数名称 。 属性required:设置请求的参数名称是否必须要传递。true:必须要传递;false:可以传递,可以不传递。默认是true。属性defaultValue:设置参数的默认值。如果传递参数,使用实际的参数值;如果没有传递,使用默认值
将传递的参数名和接收参数的类的字段名保持一致既可以接收参数 (Data数据类型 , 字符串类型乱码)
post 字符串乱码 :
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
get 字符串乱码 :
<build>
<finalName>ssmfinalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<version>2.1version>
<configuration>
<port>8080port>
<path>/ssmpath>
<uriEncoding>UTF-8uriEncoding>
<server>tomcat7server>
configuration>
plugin>
plugins>
build>
部署阶段 字符串乱码: tomcat 安装目录下conf中的server.xml
<connector URIEncoding="UTF-8" port="8080" protocol=""/>
解决日期字符串类型问题:
// Converter
//S,Source,源,转换之前的数据,这里是字符串类型的商品生产日期
//T,Targert,目标,转换之后的数据,这里是Date类型的日期
public class DateConverter implements Converter<String, Date> {
/* (non-Javadoc)
* @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object)
*/
@Override
// 实现转换逻辑
public Date convert(String source) {
// TODO Auto-generated method stub
// 1.日期格式对象
// 2016-02-03 13:22:53
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
// 转换成功,直接返回
return format.parse(source);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 转换失败,返回null
return null;
}
}
<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.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
<mvc:annotation-driven conversion-service="conversionService">mvc:annotation-driven>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.dsdd.weyou.converter.DateConverter">bean>
set>
property>
bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/">property>
<property name="suffix" value=".jsp">property>
bean>
beans>
定义一个pojo,将list作为pojo的属性
@RequestParam注解 ,设置请求的参数名称,与方法形参的名称匹配 。
@RequestMapping注解 , 设置请求的url , 限制http请求方法,在类上加上注解可以做分类管理,窄化请求
@RequestBady 注解 , 在处理器方法的形参上使用 , 把请求json格式的数据,转换成java对象
@ResponseBody注解 ,在方法的返回值上,或者方法上面使用,把响应的java对象,转换json格式的数据
ModelAndView
void 返回void,使用request对象和response对象响应。
request 转发是原来的请求,可以获取到旧的request对象中的参数数据 ,转发浏览器的url不会发生改变,转发只能在项目内部转发,getRequestDispatcher方法:获得转发器对象 ,path参数:转发的目标url
request.getRequestDispatcher("queryItem.do").forward(request, response);
response 重定向是产生新的请求 , 旧的request的参数数据获取不到 , 浏览器的url会变成目标的url ,可以重定向内部也可重定向外部 , sendRedirest方法,重定向
response.sendRedirect("https://www.cnblogs.com");
response 响应数据
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("json数据");
String 返回
解析 : 请求处理流程 : 客户端(浏览器)-> 前端控制器(dispatcherServlet)->表现层(controller)->业务层(service)->持久层(dao)
解决方案 : 从dao开始,每一层发生异常,都向上一层抛出,一直抛到前端控制器,前端控制器需要调用异常处理器包装异常,返回一个友好的提示页面给用户。
![img](file:///C:\Users\Administrator\AppData\Local\Temp\ksohtml\wps6C4C.tmp.png)
自定义异常处理系统 : 处理步骤
public class SsmException extends Exception {
// 异常消息
private String message;
/**
*
*/
public SsmException() {
super();
}
/**
* @param message
*/
public SsmException(String message) {
super();
this.message = message;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
}
public class SsmExceptionResolver implements HandlerExceptionResolver {
/* (non-Javadoc)
* @see org.springframework.web.servlet.HandlerExceptionResolver#resolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
*/
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
// TODO Auto-generated method stub
// 包装异常
// 定义系统异常
SsmException sse = null;
// 判断是否是系统异常
if(ex instanceof SsmException){
sse = (SsmException) ex;
}else{
// 创建一个未知异常
sse = new SsmException("未知异常!");
}
// 创建ModelAndView对象
ModelAndView mav = new ModelAndView();
mav.addObject("message", sse.getMessage());
mav.setViewName("error/error");
return mav;
}
}
<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.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
<mvc:annotation-driven conversion-service="conversionService">mvc:annotation-driven>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.dsdd.weyou.converter.DateConverter">bean>
set>
property>
bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/">property>
<property name="suffix" value=".jsp">property>
bean>
<bean class="com.dsdd.weyou.exception.SsmExceptionResolver">bean>
beans>
// 使用简单类型Integer,接收请求的商品参数id
// 形参id的名称,要与请求参数的名称一致
@RequestMapping("/queryItemById.do")
public String queryItemById(Model model,Integer id) throws SsmException{
// 1.根据商品Id查询商品
Item item = this.itemService.queryItemById(id);
// 增加异常测试======================start
if(item == null){
throw new SsmException("商品不存在!");
}
// 测试运行时异常
//int i = 1/0;
// 增加异常测试======================end
// 2.响应商品数据
// addAttribute方法:设置响应的模型数据
model.addAttribute("item", item);
return "item/itemEdit";
}
区别 :
拦截器相当于servlet中过滤器,可以对处理器方法执行预处理(在处理器方法执行前执行);对处理器方法执行后处理(在处理器方法执行后执行)。自定义拦截器需要实现接口(HandlerInterceptor)接口
public class FirstInterceptor implements HandlerInterceptor {
/* (non-Javadoc)
* @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
*/
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
// TODO Auto-generated method stub
System.out.println("FirstInterceptor--preHandle方法执行中......");
return true;
}
/* (non-Javadoc)
* @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
*/
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
System.out.println("FirstInterceptor--postHandle方法执行中......");
modelAndView.addObject("message", "我是postHandle方法......");
}
/* (non-Javadoc)
* @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
*/
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
System.out.println("FirstInterceptor--afterCompletion方法执行中......");
}
}
<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.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
<mvc:annotation-driven conversion-service="conversionService">mvc:annotation-driven>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.dsdd.weyou.converter.DateConverter">bean>
set>
property>
bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/">property>
<property name="suffix" value=".jsp">property>
bean>
<bean class="com.dsdd.weyou.exception.SsmExceptionResolver">bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760">property>
<property name="maxInMemorySize" value="4096">property>
<property name="defaultEncoding" value="UTF-8">property>
bean>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/interceptor.do"/>
<bean class="com.dsdd.weyou.interceptor.FirstInterceptor">bean>
mvc:interceptor>
mvc:interceptors>
beans>
// 拦截器讲解专用
@RequestMapping("/interceptor.do")
public String testInterceptor(Model model){
System.out.println("ItemController--testInterceptor方法执行中......");
model.addAttribute("message1", "我是处理器testInterceptor方法......");
return "inter/interceptor";
}
使用场景
preHandle方法:在处理器方法执行前执行,在jsp响应前执行。执行预处理,返回布尔类型值,返回true继续执行;返回false,终止执行。在企业项目中,通常在这个方法执行用户登录校验,权限菜单校验业务功能。
postHandle方法:在处理器方法执行后,在jsp响应前执行。执行后处理。在企业项目中,通常在这个方法执行公共的模型数据设置,比如页面的头部信息,尾部信息。
afterCompletion方法:在处理器方法执行后,在jsp页面响应后执行。执行后处理。在企业项目中,通常在这个方法执行操作日志的记录。