一.什么是Springmvc
SpringMVC属于SpringFrameWork的后续产品。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC架构,从而在使用Spring进行WEB开发时,可以选择使用Spring的SpringMVC框架或集成其他MVC开发框架,如Struts1,Struts2等.
二.springmvc的框架结构
三.springmvc的简单应用
创建maven项目,在pom.xml中配置架包
<!-- 配置springmvc的架包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
在web.xml中配置springmvc的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 解决乱码问题 -->
<filter>
<filter-name>myFilterone</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<!-- encoding只是设计request -->
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!-- request和response都设计 -->
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>myFilterone</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 在使用springmvc的标签或者国际化 都需要spring的支持 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 请求method支持put和delete必须添加过滤器 -->
<filter>
<filter-name>myFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- springmvc配置 -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- freemarker配置 -->
<servlet>
<servlet-name>freemarker</servlet-name>
<servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
<!-- 模板的查找路径 从上下文根路径查找 模板 ftl-->
<init-param>
<param-name>TemplatePath</param-name>
<param-value>/</param-value>
</init-param>
<!-- 是否不需要缓存 -->
<init-param>
<param-name>NoCache</param-name>
<param-value>true</param-value>
</init-param>
<!-- 最终显示是html -->
<init-param>
<param-name>ContentType</param-name>
<param-value>text/html;charset=UTF-8</param-value>
</init-param>
<!-- FreeMarker settings: -->
<init-param>
<param-name>template_update_delay</param-name>
<param-value>0</param-value> <!-- 0 is for development only! Use higher value otherwise. -->
</init-param>
<init-param>
<param-name>default_encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!-- 数字的格式 -->
<init-param>
<param-name>number_format</param-name>
<param-value>0.##</param-value>
</init-param>
<!-- servlet 容器启动时实例化 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>freemarker</servlet-name>
<url-pattern>*.ftl</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
在WEB-INF下必须有个mvc-servlet.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
">
<!-- 扫描bean -->
<context:component-scan base-package="springmvc"></context:component-scan>
<!-- springmvc 配置拦截 / 所有资源都被拦截 图片无法展示 将除控制层以外的资源交回给servlet处理 -->
<mvc:default-servlet-handler/>
<!-- 将springmvc注解的action交给springmvc处理 -->
<mvc:annotation-driven validator="localValidatorFactoryBean">
<mvc:message-converters>
<!-- 配置json消息转换器 -->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html</value>
<value>application/x-www-form-urlencoded</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="localValidatorFactoryBean" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource"></property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 该拦截器用于拦截URL上参数 -->
<mvc:interceptors>
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<!-- 没传就读浏览器的 -->
<property name="paramName" value="a"></property>
</bean>
<mvc:interceptor>
<mvc:mapping path="/tm"/>
<bean class="springmvc.less05.controller.MyInterController"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!-- 参数需要被临时存储在某个地方 当用户再次访问使用之前设置的参数 -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
</bean>
<!-- 启用文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 限制上传文件大小 5M -->
<property name="maxUploadSize" value="5242880"></property>
</bean>
<context:property-placeholder location="classpath:/jdbc.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="${url}" ></property>
<property name="username" value="${userName1}" ></property>
<property name="password" value="${password}" ></property>
<property name="driverClassName" value="${driverClassName}" ></property>
</bean>
<!-- 事务管理器 不再使用jdbc的commit和rollback 必须由事务管理器提供 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 定义通知 通知的代码 spring已经实现 -->
<tx:advice id="myAdvise" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="update*"/>
<tx:method name="save*"/>
<tx:method name="delete*"/>
<tx:method name="select*" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut expression="execution(* springmvc.*.*.*.*(..)) " id="myPoint"/>
<aop:advisor advice-ref="myAdvise" pointcut-ref="myPoint"/>
</aop:config>
</beans>
简单的应用
package springmvc.less01.hellow;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* springmvc中一个路径和方法的映射叫做一个action(动作)
*/
@Controller
public class HelloController {
@RequestMapping("/text")
public String add(HttpServletResponse response,HttpServletRequest request) throws IOException{
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println("你好 springmvc="+request.getParameter("id"));
return null;
}
@RequestMapping("/param")
public String updete(User user,HttpServletResponse response) throws IOException{
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println(user.getId()+"--"+user.getName());
return null;
}
@RequestMapping("/mvc")
public String mvc(HttpServletRequest request) throws IOException{
request.setAttribute("name", "zs");
return "/index.jsp";
}
}
四.Restful风格设计概念
REST,即RepresentationalState Transfer的缩写。"表现层状态转化"。研究计算机科学两大前沿----软件和网络----的交叉点
"表现层"其实指的是"资源"(Resources)的"表现层"。所谓"资源",就是网络上的一个实体,或者说是网络上的一个具体信息。它可以是一段文本、一张图片、一首歌曲、一种服务,总之就是一个具体的实在。你可以用一个URI(统一资源定位符)指向它,每种资源对应一个特定的URI。要获取这个资源,访问它的URI就可以,因此URI就成了每一个资源的地址或独一无二的识别符。
restful URI的设计不该包含动词。因为"资源"表示一种实体,所以应该是名词,URI不应该有动词,动词应该放在HTTP协议中。
举例来说,某个URI是/arcticle/show/1,其中show是动词,这个URI就设计错了,正确的写法应该是/arcticle/1,然后用GET方法表示show。
优质Web架构五条关键原则列举如下:
对资源的操作就是一个动作(GET(查) | POST(新增) | PUT(修改) | DELETE (删除) )
rest是一种设计风格 设计资源的标识符
http://localhost:8080/s/deleteUser?id=1(标准http协议 资源定义方式)
http://localhost:8080/s/user/1(rest风格)
rest风格的controller
package springmvc.less01.hellow;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* 浏览器的提交方式必须和@RequestMapping指定的资源动作必须一致
* 否则抛出405
* @author Administrator
*
*/
@Controller
public class RestController {
/**
* /user/2==/user/{userid=2}
* @return
*/
@RequestMapping(value="/user/{id}",method=RequestMethod.GET)
public String index(@PathVariable(value="id") String userid){
return "/less01/user.jsp";
}
@RequestMapping(value="/user/{id}",method=RequestMethod.PUT)
public String updateUser(@PathVariable(value="id") String userid,String name,HttpServletResponse response) throws IOException{
response.getWriter().println(userid+name+"update");
return null;
}
@RequestMapping(value="/user",method=RequestMethod.POST)
public String aauser(String name,HttpServletResponse response) throws IOException{
response.getWriter().println(name+"add");
return null;
}
@RequestMapping(value="/user/{id}",method=RequestMethod.DELETE)
public String deleteUser(@PathVariable(value="id") String userid,HttpServletResponse response) throws IOException{
response.getWriter().println(userid+"delete");
return null;
}
}
jsp页面
<body algin="centet">
<form action="${pageContext.request.contextPath}/user/1" method="post">
<input type="hidden" name="_method" value="put">
<input type="text" name="name">
<input type="submit" value="上传"/>
</form>