1.MVC简单应用
1.1 先创建个web项目
1.2 导入包,在lib文件夹里
lib 文件夹要放在web-inf里面,不然会出错
1.3 编写web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<!--名字不能乱取,要对应的上springmvc-servlet的前部分,要改可以一起改-->
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<!--load-on-startup 元素标记容器是否应该在web应用程序启动的时候就加载这个servlet,(实例化并调用其init()方法)。
它的值必须是一个整数,表示servlet被加载的先后顺序。-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<!--同上-->
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
1.4 创建springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="simpleUrlHandlerMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<!--key就是路径地址,里面填写的是bean的id-->
<prop key="/index">indexController</prop>
</props>
</property>
</bean>
<bean id="indexController" class="controller.IndexController"></bean>
</beans>
1.5 创建控制类 IndexController
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class IndexController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//gei
ModelAndView mav = new ModelAndView("index.jsp");
//添加信息
mav.addObject("message", "Hello Spring MVC");
// return 可以到指定的页面
return mav;
}
}
1.6 准备index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<h1>${message}</h1>
1.7 运行
输入地址
http://127.0.0.1:8080/项目名/index
1.8 原理图
MVC视图定位
2.1 springmvc-servlet.xml,增加
<!--
viewResolver是视图解析器
prefix是指定一个前缀,suffix则是后缀
-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".jsp" />
</bean>
2.2 修改IndexController
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class IndexController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("index");
mav.addObject("message", "Hello Spring MVC2");
return mav;
}
}
2.3 移动index.jsp
把index.jsp移动到page文件夹
2.4 运行
3.MVC注解方式
3.1 修改IndexController
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//这个注解代表此类是控制类
@Controller
public class IndexController{
//在方法handleRequest 前面加上 @RequestMapping("/index") 表示路径/index会映射到该方法上
@RequestMapping("/index")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("index");
mav.addObject("message", "Hello Spring MVC2");
return mav;
}
}
3.2 修改springmvc-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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--去掉相关映射,因为已经用注解了-->
<!-- <bean id="simpleUrlHandlerMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<!–key就是路径地址,里面填写的是bean的id–>
<prop key="/index">indexController</prop>
</props>
</property>
</bean>
<bean id="indexController" class="controller.IndexController"></bean>-->
<!--需要在beans处声明命名空间-->
<!--下面代码的意思是扫描controller包下的控制类-->
<context:component-scan base-package="controller" />
<!--
viewResolver是视图解析器
prefix是指定一个前缀,suffix则是后缀
-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
3.3 运行
4.MVC接收表单数据
4.1 先创建实体类Product
public class Product {
private int id;
private String name;
private float price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
4.2 写addProduct.jsp
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//这个注解代表此类是控制类
@Controller
public class AddProductController{
//在方法handleRequest 前面加上 @RequestMapping("/index") 表示路径/index会映射到该方法上
@RequestMapping("/product")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("addProduct");
return mav;
}
}
4.3 写控制类AddProductController
//这个注解代表此类是控制类
@Controller
public class AddProductController{
//在方法handleRequest 前面加上 @RequestMapping("/index") 表示路径/index会映射到该方法上
@RequestMapping("/product")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("addProduct");
return mav;
}
}
4.4 写ProductController
注: addProduct.jsp 提交的name和price会自动注入到参数 product里
注: 参数product会默认被当做值加入到ModelAndView 中,相当于:
mav.addObject("product",product);
@Controller
public class ProductController {
@RequestMapping("/showProduct")
public ModelAndView add(Product product) throws Exception {
ModelAndView mav = new ModelAndView("showProduct");
return mav;
}
}
4.5 写showProduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
产品名称: ${product.name}<br>
产品价格: ${product.price}
4.6 打开链接
http://localhost:8080/项目名称/product
5.MVC客户端转跳
5.1 修改IndexController
@RequestMapping("/jump")
public ModelAndView jump() {
ModelAndView mav = new ModelAndView("redirect:/index");
return mav;
}
5.2 实验
访问http://localhost:8080/mvc22_war_exploded/jump会直接转跳到
http://localhost:8080/mvc22_war_exploded/index
6.MVC 如何使用SESSION
6.1 在IndexController中添加代码
@RequestMapping("/clear")
public ModelAndView clearcheck(HttpSession session) {
Integer i = (Integer) session.getAttribute("count");
session.setAttribute("count",0);
ModelAndView mav = new ModelAndView("redirect:/check");
return mav;
}
6.2 新增check.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
session中记录的访问次数:${count}
6.3 运行
7.MVC中文问题
7.1 在web.xml中添加代码
<!--filter其实就是过滤器-->
<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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
7.2 修改addProduct.jsp
为form 设置method="post"
<form action="showProduct" method="post">
产品名称 :<input type="text" name="name" value=""><br />
产品价格: <input type="text" name="price" value=""><br />
<input type="submit" value="增加商品">
</form>
7.3 运行,可以正常显示中文了
8.MVC上传文件
8.1 配置web.xml允许访问*.jpg
<!--这一段表示允许访问*.jpg-->
<!--因为配置springmvc的servlet的时候,使用的路径是"/",导致静态资源在默认情况下不能访问,所以要加上这一段,允许访问jpg-->
<!--并且必须加在springmvc的servlet之前-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
8.2 配置springmvc-servlet.xml
<!--
MultipartResolver 用于处理文件上传
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
8.3 写upload.jsp 上传页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*" isELIgnored="false"%>
<%--
上传页面,需要注意的是form 的两个属性必须提供
method="post" 和 enctype="multipart/form-data" 缺一不可
enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码
--%>
<form action="uploadImage" method="post" enctype="multipart/form-data">
<%--accept="image/*" 表示只能选择图片进行上传--%>
选择图片:<input type="file" name="image" accept="image/*" /> <br>
<input type="submit" value="上传">
</form>
8.4 准备UploadedImageFile
在UploadedImageFile中封装MultipartFile类型的字段 image ,用于接受页面的注入
这里的字段 image必须和上传页面upload.jsp中的image
<input type="file" name="image" accept="image/*" />
保持一致
import org.springframework.web.multipart.MultipartFile;
public class UploadedImageFile {
//这里的image名字必须和upload里的name名字相同
MultipartFile image;
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
}
8.5 UploadController 上传控制器
import org.apache.commons.lang.xwork.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import pojo.UploadedImageFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
@Controller
public class UploadController {
@RequestMapping("/uploadImage")
public ModelAndView upload(HttpServletRequest request, UploadedImageFile file)
throws IllegalStateException, IOException {
//通过RandomStringUtils.randomAlphanumeric(10);来获得一个随机名
String name = RandomStringUtils.randomAlphanumeric(10);
//加jpg
String newFileName = name + ".jpg";
//新建文件并设置文件地址
File newFile = new File(request.getServletContext().getRealPath("/image"), newFileName);
//getParentFile()是获取文件地址路径,mkdirs()是创建此抽象路径名指定的目录,包括所有必需但不存在的父目录
newFile.getParentFile().mkdirs();
//transferTo似乎是把上传上服务器的文件写下来
file.getImage().transferTo(newFile);
//接下来就是转跳了
ModelAndView mav = new ModelAndView("showUploadedFile");
mav.addObject("imageName", newFileName);
return mav;
}
@RequestMapping("/upload")
public ModelAndView upload(){
//转跳
ModelAndView mav = new ModelAndView("upload");
return mav;
}
}
8.6 showUploadedFile.jsp 显示图片的页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<img src="image/${imageName}"/>
8.7 运行测试
9.MVC拦截器
9.1 拦截器类:IndexInterceptor
public class IndexInterceptor extends HandlerInterceptorAdapter {
/**
* 在业务处理器处理请求之前被调用
* 如果返回false
* 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
* 如果返回true
* 执行下一个拦截器,直到所有的拦截器都执行完毕
* 再执行被拦截的Controller
* 然后进入拦截器链,
* 从最后一个拦截器往回执行所有的postHandle()
* 接着再从最后一个拦截器往回执行所有的afterCompletion()
*/
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle(), 在访问Controller之前被调用");
return true;
}
/**
* 在业务处理器处理请求执行完成后,生成视图之前执行的动作
* 可在modelAndView中加入数据,比如当前时间
*/
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("postHandle(), 在访问Controller之后,访问视图之前被调用,这里可以注入一个时间到modelAndView中,用于后续视图显示");
modelAndView.addObject("date","由拦截器生成的时间:" + new Date());
}
/**
* 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等
*
* 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
*/
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("afterCompletion(), 在访问视图之后被调用");
}
}
9.2 配置拦截器
<!--mvc:interceptors就是拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<!--指拦截地址-->
<mvc:mapping path="/index"/>
<!-- 定义在mvc:interceptor下面的表示是对特定的请求才进行拦截的 -->
<!-- 特定的拦截器 -->
<bean class="interceptor.IndexInterceptor"/>
</mvc:interceptor>
<!-- 当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandle和afterCompletion方法 -->
</mvc:interceptors>
9.3 修改 index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<h1>${message}</h1>
<p>${date}</p>
9.4 运行
参考网站:https://how2j.cn/k/springmvc/springmvc-springmvc/615.html