1.springmvc简介
Spring MVC是一个基于MVC的web框架,
Spring MVC 分离了控制器、模型对象、过滤器以及处理程序对象的角色,这种分离让它们更容易进行定制。
优点:
采用了松散耦合可插拔组件结构,比其他 MVC 框架更具扩展性和灵活性
进行更简洁的Web层的开发;
springmvc组件:
控制器DispatcherServlet 接收请求和响应的
处理器映射器HandlerMapping
处理器适配器HandlerAdapter
视图解析器ViewResolver
处理器 handler(开发)
视图 view(开发)
客户端发来的请求经过控制器,交给映射器查找handler处理器,通过适配器按照指定规则执行handler处理器,
执行过程中,视图解析器会根据视图逻辑,返回视图view给控制器,之后响应给客户端。
2.入门程序
(1)maven工程 选择webapp
(2)导包
<properties>
<project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
<spring.version>5.0.6.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
(3)src/main/resorces下创建springmvc配置文件 springmvcConfig.xml
(4)web.xml 中配置 DispatcherServlet
<servlet>
<servlet-name>springmvc01</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvcConfig.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc01</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
(5)创建控制类
public class MyControl implements Controller{ //处理器 handler
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//创建对象
ModelAndView mv=new ModelAndView();
//设置视图
mv.setViewName("index.jsp");
return mv;
}
}
(6)配置访问映射 springmvcConfig.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="/hello" class="com.edu.MyControl"></bean>
<!-- 处理器映射器 -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
<!-- 处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
<!--视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>
</beans>
(7)启动tomcat运行
错误解决:
500错误:springmvc.xml没找到
404错误:web.xml <url-pattern>*.do</url-pattern> 和请求不一致
springmvc.xml <bean name="/hello.do" class="com.edu.MyControl"></bean> 和请求不一致
控制类中 mv.setViewName("index.jsp"); 默认webapp下查找 jsp页面地址不对
3.基于注解
(1)maven工程 webapp(同xml方式)
(2)导包(同xml方式)
(3)创建配置文件spring.xml
xmlns:context="http://www.springframework.org/schema/context"
开启注解扫描
<context:component-scan base-package="com.edu"/>
(4)web.xml配置控制器 (同xml方式)
(5)创建控制类
@Controller // 此处只能是Controller,不能是component service respotory
public class MyControl {
@RequestMapping("/hello")
public void doXXX(HttpServletRequest req,HttpServletResponse res) throws IOException{
res.sendRedirect("hello.jsp");
}
}
(6)部署并运行
4.映射请求requestMapping
类和方法
类:项目的根目录
方法:提供进一步的细分映射信息,相对于类定义处的 URL
【注意】类上没有映射请求时,相当于@RequestMapping("/") ,方法上的映射请求相对于应用根目录。
@Controller
@RequestMapping("/user") // "/" 应用根目录 http://localhost:8080/springmvc_02/user
public class MyControl {
@RequestMapping("/hello") // "/"代表的是/user http://localhost:8080//springmvc_02/user/hello
public void doXXX(HttpServletRequest req,HttpServletResponse res) throws IOException{
//res.sendRedirect("/hello.jsp"); // "/hello.jsp" 根目录查找 http://localhost:8080/hello.jsp
res.sendRedirect("hello.jsp"); hello.jsp位于webroot下的user文件夹中 // http://localhost:8080/springmvc_02/user/hello.jsp
或者res.sendRedirect("../hello.jsp"); hello.jsp位于webroot
}
}
@RequestMapping 的几个属性
value、 请求url
method、 请求方式
params 请求参数 (必须限定传参数)
headers 请求头
consumes:请求类型 text/html application/json
produces:返回类型 必须是请求accept包含的类型
@Controller
@RequestMapping("/user") // "/" 应用根目录
public class MyControl {
@RequestMapping(value="/hello",method={RequestMethod.GET},params={"name","psw"}) // "/"代表的是/user
public void doXXX(HttpServletRequest req,HttpServletResponse res) throws IOException{
res.sendRedirect("../hello.jsp"); // "/hello.jsp" 根目录查找
}
}
5.控制类的返回值
返回ModelAndView
返回字符串
返回void
(1) 返回ModelAndView
@RequestMapping("/index")
public ModelAndView do2(Model model){
ModelAndView mv=new ModelAndView();
mv.addObject("msg","欢迎你"); //request.setAttribute()
mv.setViewName("index.jsp");
return mv;
}
(2)返回字符串
@RequestMapping("/addUser")
public String do222(){
return "index.jsp";
}
@RequestMapping("/addUser2")
public String do3333(){
return "index"; //逻辑视图
}
@RequestMapping("/addUser3")
public String do444(){
return "forward:hello"; //请求转发 映射地址
}
@RequestMapping("/addUser4")
public String do5555(){
return "redirect:hello"; //重定向 映射地址
}
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- <property name="prefix" value="/WEB-INF/index.jsp"></property> -->
<property name="prefix" value="/"></property> //前缀
<property name="suffix" value=".jsp"></property> //后缀
</bean>
(3)返回void
public void doXXX(HttpServletRequest req,HttpServletResponse res) throws IOException{
res.sendRedirect("hello.jsp"); //重定向
req.getRequestDispatcher("hello.jsp").forward(req, res);
}
el表达式解析问题:
jsp1.2默认el解析是关闭的, 在页面page指令中 isELIgnored="false"
或者在web.xml 中
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
5、控制类方法的参数类型
HttpServletRequest
HttpServletResponse
Model org.springframework.ui接口
ModelMap org.springframework.ui类
Map<String ,Object>
除了这些对象之外,还可以是
(1)简单数据类型
@RequestMapping("/testSample")
public void testSample(String username,String password,int age,HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException{
System.out.println(username+","+password+","+age);
req.getRequestDispatcher("index.jsp").forward(req, res);
}
//测试:http://localhost:8080/springmvc_02/testSample?username=tom&password=123&age=18
//结果 tom,123,18
(2) pojo类型
<form action="${pageContext.request.contextPath}/testPojo">
用户名 <input type="text" name="username" value="${user.username }">
密码 <input type="text" name="password" value="${user.password }">
年龄<input type="text" name="age" value="${user.age }">
<input type="submit" value="保存">
</form>
@RequestMapping("/testPojo")
public String testPojo(UserInfo user,Model model){
System.out.println(user);
model.addAttribute("uu", user);
return "showUser.jsp";
}
(3)包装pojo
public class UserInfo {
private String username;
private String password;
private int age;
private UserDetail detail;
//get set
}
public class UserDetail {
private String hobby;
//省略很多字段
}
<form action="${pageContext.request.contextPath}/testPojo">
用户名 <input type="text" name="username" value="${user.username }">
密码 <input type="text" name="password" value="${user.password }">
年龄<input type="text" name="age" value="${user.age }">
爱好 <input type="text" name="detail.hobby" value="${user.detail.hobby }"> //name="detail.hobby" pojo实体类的属性名
<input type="submit" value="保存">
@RequestMapping("/testPojo")
public String testPojo(UserInfo user,Model model){
System.out.println(user);
model.addAttribute("uu", user);
return "showUser.jsp";
}
//form表单乱码
get请求 tomcat中 server.xml
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" useBodyEncodingURI=true URLEncoding="utf-8" />
new String(request.getParameter("uname").getBytes("iso-8859-1"),"utf-8")
post请求:
web.xml 过滤器
<filter>
<filter-name>ff</filter-name>
<filter-class>org.springframework.web.filter.CharsetEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>ff</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>