<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.java.SpringMVCgroupId>
<artifactId>SpringMVCartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>SpringMVC Maven Webappname>
<url>http://www.example.comurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.7maven.compiler.source>
<maven.compiler.target>1.7maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.6version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5.2version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.7.3version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.7.3version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.7.3version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
<scope>providedscope>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.4version>
dependency>
dependencies>
<build>
<finalName>SpringMVCfinalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<version>2.2version>
<configuration>
<path>/path>
<port>8080port>
<uriEncoding>UTF-8uriEncoding>
configuration>
plugin>
plugins>
build>
project>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<async-supported>trueasync-supported>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<servlet>
<servlet-name>DispatcherServletservlet-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>DispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:component-scan base-package="com.java.service"/>
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${username}"/>
<property name="password" value="${password}"/>
bean>
<bean id="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:annotation-driven transaction-manager="tx"/>
<bean id="fb" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.java.mapper"/>
<property name="sqlSessionTemplateBeanName" value="fb"/>
bean>
beans>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.java.controller"/>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
mvc:message-converters>
mvc:annotation-driven>
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
<typeAliases>
<typeAlias type="java.util.List" alias="list"/>
<package name="com.java.entity"/>
typeAliases>
configuration>
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/asset
username=root
password=Root
Spring是IOC和AOP的容器框架,SpringMVC是基于Spring功能之上添加的Web框架,想用SpringMVC必须先依赖Spring。 简单讲的话可以将SpringMVC类比于servlet。
Spring可以说是一个管理bean的容器,也可以说是包括很多开源项目的总称,SpringMVC是其中一个开源项目,所以简单走个流程的话,http请求一到,由容器(如:tomact)解析http搞成一个request,通过映射关系(路径,方法,参数)被SpringMVC一个分发器去找到可以处理这个请求的bean,那tomcat里面就有spring管理bean的一个池子(bean容器)里面找到,处理完了就把响应返回回去。
SpringMVC是一个MVC模式的WEB开发框架。
Spring是一个通用解决方案,最大的用处就是通过LOC/AOP解耦,降低软件复杂性, 所以Spring可以结合SpringMVC等很多其他解决方案一起使用,不仅仅只适用于WEB开发。
在整个 SpringMVC 框架中,DispatcherServlet 处于核心位置,它负责协调和组织不同组件完成请求处理并返回响应工作。我们看一下请求处理的大致流程:
@RequestMapping注解:请求路径映射,可以修饰类或者方法。如果标注在某个controller的类级别上,则表明访问此类路径下的方法都要加上其配置的路径;最常用的是标注在方法上,表明哪个具体的方法来接受处理某次请求。如果类上没有该注解,只是在方法上有该注解,那么在浏览器请求的时候url=localhost:8080/方法请求映射名称。
@RequestParam()是请求参数注解,应用在方法的参数中。
@RequestParam主要用于在SpringMVC后台控制层获取参数,类似一种是request.getParameter(“name”),它有三个常用参数:defaultValue = “0”,required = false,value = “isApp”;
defaultValue :表示设置默认值
required:通过boolean设置是否是必须要传入的参数,true表示必须传入,如果不传则为null,如果为null,则报异常。
value: 值表示接收的传入的参数名称
restful风格的参数注解,只能修饰从路径中获取的参数,用于将请求URL中的模板变量映射到功能处理方法的参数上,即取出uri模板中的变量作为参数。
等效于@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)注解,可将Date时间格式的国际格式转为中文格式,主要应用于实体类的Date类型属性上,或者方法中Date类型的参数上。
package com.java.entity;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
/**
* @author Liushun
* @date Created in 2018/9/21 20:29
* @description 用户实体类
*/
public class User {
// 用户姓名
private String name;
// 用户年龄
private Integer age;
// 用户出生日期
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birth;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", birth=" + birth +
'}';
}
}
package com.java.controller;
import com.java.entity.User;
import org.springframework.format.annotation.DateTimeFormat;
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;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Date;
import java.util.Map;
import java.util.Set;
/**
* @author Liushun
* @date Created in 2018/9/21 21:36
* @description springMVC获取参数的几种方式
*/
@Controller
@RequestMapping("/con1")
public class TestParamController {
/*@RequestParam:
1、如果请求参数名和后台接收参数名不一致,使用此注解可正常传参,不然会传参失败
2、相当于request.getParameter()
3、如果不使用@RequestParam,方法的形参和url中的参数名要保持一致
*/
@RequestMapping("/paramTest")
public void paramTest(@RequestParam(value = "name") String name1, Integer age, @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date birth){
System.out.println("name:" + name1);
System.out.println("age:" + age);
System.out.println("birth:" + birth);
}
// 一次性获取所有的请求参数
@RequestMapping("/paramsTest")
public void paramsTest(@RequestParam Map map){
Set<Map.Entry> set = map.entrySet();
for(Map.Entry entry : set){
System.out.println(entry.getKey() + "——" + entry.getValue());
}
}
// 专门处理post请求
@RequestMapping(value = "/entityTest",method = RequestMethod.POST)
public void entityTest(User user){
System.out.println("POST请求接参:" + user);
}
// 专门处理get请求
@RequestMapping(value = "/entityTest",method = RequestMethod.GET)
public void entityTest2(User user){
System.out.println("GET请求接参:" + user);
}
/**@GetMapping用于将HTTP get请求映射到特定处理程序的方法注解
具体来说,@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。
@PostMapping用于将HTTP post请求映射到特定处理程序的方法注解
具体来说,@PostMapping是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写。*/
// rest风格的参数获取——url中只有参数值,参数名在注解中,路径变量的注解:@PathVariable
@RequestMapping("/restfulTest/{name}/{age}/{birth}")
public void restfulTest(@PathVariable String name,
@PathVariable Integer age,
@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date birth){
System.out.println("name:" + name);
System.out.println("age:" + age);
System.out.println("birth:" + birth);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
springMVC获取参数的几种方式
测试restful风格的请求参数获取
将传入的参数类型转化为json或者xml格式,应用于方法之上,适用于ajax后台
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区
使用时机:返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用,其实就是为了把传出或者传入的参数类型转变成json,xml类型
package com.java.controller;
import com.java.entity.User;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
/**
* @author Liushun
* @date Created in 2018/9/21 21:03
* @description 响应正文和页面跳转
*/
@Controller
@RequestMapping("/con2")
public class TestResponseController {
//1、响应字符串,相当于response.getWriter().write("我爱你,中国")
// @RequestMapping注解中produces = "text/html;charset=UTF-8",解决响应中文乱码
@RequestMapping(value = "/responseString",produces = "text/html;charset=UTF-8")
@ResponseBody
public String responseString(){
return "我爱你,中国";
}
// 2、响应实体类字符串
@RequestMapping(value = "/responseEntityStr",produces = "text/html;charset=UTF-8")
@ResponseBody
public String responseEntityStr(){
User user = new User();
user.setName("鬼见愁");
return user.toString();
}
// 3、以json格式响应实体类
@RequestMapping("/responseEntity")
@ResponseBody
public Object responseEntity(){
User user = new User();
user.setName("鬼见愁");
return user;
}
// 4、响应字节流图片
@RequestMapping("/responseByte")
public void responseByte(HttpServletResponse response){
try {
FileInputStream fis = new FileInputStream("E:\\Img_Demo\\liushishi.jpg");
ServletOutputStream os = response.getOutputStream();
IOUtils.copy(fis, os);
} catch (IOException e) {
e.printStackTrace();
}
}
//上面是响应正文 下面是页面的跳转
// 5、页面的跳转——转发
@RequestMapping("/toShow")
public String toShow(){
// 自动拼接前后缀并转发到对应的jsp
return "show";
}
// 6、页面的跳转——重定向
@RequestMapping("/toShow2")
public String toShow2(){
// 重定向的路径:1.非web-inf下的jsp 2.其它的RequestMapping路径
return "redirect:toShow";
}
// 7、方法的请求映射,利用model传值
@RequestMapping("/saveData1")
public String saveData1(Model model){
// 把数据k-v保存在model类中,其实保存在request作用域中
model.addAttribute("name","鬼见愁");
// 渲染视图,跳页面
return "show";
}
// 8、方法的请求映射,利用ModelMap传值
@RequestMapping("/saveData2")
public String saveData2(ModelMap modelMap){
modelMap.addAttribute("name","鬼见愁");
return "show";
}
// 9、ModelAndView表示模型与视图,既可以进行传值,又可以进行渲染视图
@RequestMapping("/saveData3")
public ModelAndView saveData3(ModelAndView modelAndView){
modelAndView.addObject("name","鬼见愁");
modelAndView.setViewName("show");
return modelAndView;
}
}
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.7.3version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.7.3version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.7.3version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.4version>
dependency>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
mvc:message-converters>
mvc:annotation-driven>
所有的存储数据model,modelMap,modelAndView,均默认保存在request作用域中
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
Title
展示页面
applicationScope:${applicationScope.name}
sessionScope:${sessionScope.name}
requestScope:${requestScope.name}
pageScope:${pageScope.name}