SpringMVC的概念
Model View Controller
主流MVC框架
- struts1
- webwork
- struts2
- SpringMVC
- jsf
SpringMVC特点
- 功能组件划分细致
- 灵活、强大
- 设计思想优秀
MVC框架都做什么
- 以Controller为中心完成对系统流程的控制管理
- 从请求中收集数据
- 对传入参数进行验证
- 根据请求调用相应业务逻辑完成数据处理
- 将处理结果返回給视图
- 国际化支持
- 针对不同视图技术提供不同解析支持方案
- 针对JSP视图技术提供标签库
- 通过拦截器链实现面向方面编程完成系统级控制
- 对文件上传、下载等常用功能的封装
SpringMVC框架的核心构件
- DispatcherServlet
核心控制器,在web.xml中配置
- Controller
控制器,自己创建的类excends Controller,在springMVC-servlet.xml中配置
- Handler Mapping
管理映射,把请求映射到具体的控制器
- ViewResolver&View
- InternalResourceViewResolver
统一资源视图解析器,在springMVC-servlet.xml中配置,两个属性:prefix前缀、suffix后缀
- Interceptors
拦截器,自己写的类,实现HandlerInterceptor类
- LocalResolver
- Validate
springMVC的环境搭建
例:记录作家信息,两个跳转
一、导包
- spring的包,beans、context、core、expression、web、webmvc
- 日志包
- 标准标签库
二、创建jsp页面
个人习惯先写显示层,View(jsp)——action——dao——service——controller——(ok.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>
<h1>springMVC首页</h1>
<a href="person.action">人物信息</a>
</body>
</html>
<%@ 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>
<h1>记录人物</h1>
<form action="ok.action" method="post">
<label for="name">人物姓名:</label>
<input type="text" name="name" id="name" value="东野圭吾"/><br/>
<label for="desc">人物描述:</label>
<input type="text" name="desc" id="desc" value="《解忧杂货店》的作者"/><br/>
<label for="age">人物姓名:</label>
<input type="text" name="age" id="age" value="59"/><br/>
<input type="submit" value="记录"/>
</form>
</body>
</html>
<%@ 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>
<h1>信息界面</h1>
<h3>人物姓名:${p.name}</h3>
<h3>人物描述:${p.desc}</h3>
<h3>人物年龄:${p.age}</h3>
</body>
</html>
三、web.xml中配置DispatcherServlet
<!-- 核心控制器 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 修改springMVC-servlet.xml的默认位置 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/springMVC-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup><!-- 服务一启动就加载 -->
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
如果使用如上配置,Spring Web MVC框架将加载"/WEB-INF/config/springMVC-servlet.xml"来进行初始化上下文,而不是"/WEB-INF/[servlet名字]-servlet.xml"
四、在src目录下新建springMVC-servlet.xml配置文件
- 头文件增加三项:beans,context,mvc
<?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: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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<bean name="/person.action" class="com.springMVC.controller.PersonController"></bean>
<bean name="/ok.action" class="com.springMVC.controller.SaveController"></bean>
</beans>
五、创建Controller类
package com.springMVC.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class PersonController implements Controller {
//创建日志打印对象
static Log logger=LogFactory.getLog(PersonController.class);
@Override
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
logger.info("执行到PersonController内");
return new ModelAndView("/WEB-INF/jsp/person.jsp");
}
}
package com.springMVC.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.springMVC.entity.Person;
public class SaveController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
req.setCharacterEncoding("utf-8");
Person p=new Person();
p.setName(req.getParameter("name"));
p.setDesc(req.getParameter("desc"));
p.setAge(Integer.parseInt(req.getParameter("age")));
return new ModelAndView("/WEB-INF/jsp/ok.jsp", "p", p);
}
}
springMVC拦截器
处理乱码问题、权限管理
乱码,在web.xml配置拦截器
<!-- 字符拦截器 -->
<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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
springMVC的注解
- @Controller
不用再实现Controller接口 - @RequestMapping(value="/product.action")
不用写跳转,写一个方法返回String类型的jsp文件名, - @Autowired
不用再配置映射路径
package com.springMVC.controller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.springMVC.entity.Product;
import com.springMVC.service.IProductService;
@Controller
public class OkController {
@Autowired
private IProductService service;
static Log logger=LogFactory.getLog(OkController.class);
@RequestMapping
public String add(Product p,Model model) throws Exception{
service.save(p);
model.addAttribute("p", p);
return "ok";
}
}
开启包扫描
<context... 包名>开启springMVC注解驱动
<mvc...driven>导入aop包
加入service层
- @Service
不用再配置bean来创建对象 - @Scope("prototype")范围:原型
模拟数据库
Map<Long,Product>
模拟主键自增
AtomicLong
写一个方法,添加id自增功能,传入Map集合返回Product对象
package com.springMVC.service.impl;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import com.springMVC.entity.Product;
import com.springMVC.service.IProductService;
public class ProductServiceImpl implements IProductService{
//模拟数据库
Map<Long,Product> map=new HashMap<Long,Product>();
//模拟主键自增
AtomicLong add=new AtomicLong();
@Override
public Product save(Product p) throws Exception {
Long id=add.incrementAndGet();
p.setId(id);
map.put(id, p);
return p;
}
}