GettingStarted With SprimgMVC
一、原理图:
1. 用户访问 /index
2. 根据web.xml中的配置 所有的访问都会经过DispatcherServlet
3. 根据 根据配置文件springmvc-servlet.xml ,访问路径/index
会进入IndexController类
4. 在IndexController中指定跳转到页面index.jsp,并传递message数据
5. 在index.jsp中显示message信息

二、视图定位
解决了一个问题:
IndexController 写成 ModelAndView mav = new ModelAndView("index");还是能够跳转到index.jsp页面。
如何解决:
在springmvc-servlet.xml配置页面的位置及后缀
即,在springmvc-servlet.xml 添加了
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/" /> // value为你的页面放置的位置
<property name="suffix" value=".jsp" />
</bean>
三、注解方式
两个点
1.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">
// 包扫描
<context:component-scan base-package="controller" />
// 映射相关的配置
<!-- <bean id="simpleUrlHandlerMapping" -->
<!-- class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> -->
<!-- <property name="mappings"> -->
<!-- <props> -->
<!-- <prop key="/index">indexController</prop> -->
<!-- </props> -->
<!-- </property> -->
<!-- </bean> -->
<!-- <bean id="indexController" class="controller.IndexController"></bean> -->
</beans>
2.Indexcontroller 加入注解并且不用实现接口
@Controller
public class IndexController {
@RequestMapping("/index")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("index.jsp");
mav.addObject("message", "Hello Spring MVC");
return mav;
}
}
四、接受表单数据
1.addProduct.jsp
<form action="addProduct">
产品名称 :<input type="text" name="name" value=""><br />
产品价格: <input type="text" name="price" value=""><br />
<input type="submit" value="增加商品">
</form>
2.ProductController
为add方法准备一个Product 参数,用于接收注入;
addProduct.jsp提交的name和price会自动注入到参数 product里;
参数product会默认被当做值加入到ModelAndView 中,相当于:mav.addObject("product",product);
@Controller
public class ProductController {
@RequestMapping("/addProduct")
public ModelAndView add(Product product) throws Exception {
ModelAndView mav = new ModelAndView("showProduct");
return mav;
}
}
3.showProduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
产品名称: ${product.name}<br>
产品价格: ${product.price}
五、客户端跳转 and 服务端跳转
服务端跳转 -- 浏览器地址不变
客户端跳转 -- 浏览器地址会变
1)服务端跳转:在Servlet中进行服务端跳转的方式:
request.getRequestDispatcher("success.html").forward(request, response);
服务端跳转可以看到浏览器的地址依然是/login 路径,并不会变成success.html

2)客户端跳转
在Servlet中进行客户端跳转的方式:
response.sendRedirect("fail.html");
可以观察到,浏览器地址发生了变化

SpringMVC中的客户端跳转 and 服务端跳转:
1.服务端跳转
@RequestMapping("/index")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("index");
mav.addObject("message", "Hello Spring MVC");
return mav;
}
2.客户端跳转
@RequestMapping("/jump")
public ModelAndView jump() {
ModelAndView mav = new ModelAndView("redirect:/index");
return mav;
}
六、Session
什么是Session?
1.李佳汜到健身房去练胸肌,首先领了钥匙,然后进了更衣间,把衣服,裤子,钱包都放在盒子里面。
毛竞也到健身房去练翘臀。首先领了钥匙,然后 进了更衣间,把衣服,裤子,手机,《Java 21天从入门到精通》也放在了一个盒子里,但是这个盒子是和李佳汜的是不同的。
健身房,就相当于服务器,盒子,就是会话Session。
切换到我们常见的购物网站的场景
李佳汜登陆天猫之后,在购物车里看到的物品是蜡烛和皮鞭
毛竞登陆天猫之后,在购物车里看到的物品是手铐和《Java 21天从入门到精通》
2.从用户打开浏览器访问一个网站开始,无论在这个网站中访问了多少页面,点击了多少链接,都属于同一个会话。 直到该用户关闭浏览器为止,都属于同一个session。
Session 和Cookie的关系:
1.李佳汜和毛竞都有自己的盒子,那么他们怎么知道哪个盒子是自己的呢?
通过钥匙就能找到自己的盒子了。
盒子对应服务器上的Session。
钥匙对应浏览器上的Cookie。
2.原理图

SpringMVC中Session的使用:
IndexController
@RequestMapping("/check")
public ModelAndView check(HttpSession session) {
Integer i = (Integer) session.getAttribute("count");
if (i == null)
i = 0;
i++;
session.setAttribute("count", i);
ModelAndView mav = new ModelAndView("check");
return mav;
}
check.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
session中记录的访问次数:${count}
七、中文处理
两步
1.web.xml中加入CharacterEncodingFilter
<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>
- 表单中设置method = "post"
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*" isELIgnored="false"%>
<form action="addProduct" method="post">
产品名称 :<input type="text" name="name" value=""><br />
产品价格: <input type="text" name="price" value=""><br />
<input type="submit" value="增加商品">
</form>
八、上传文件
1> 流程:
访问 http://127.0.0.1:8080/springmvc/upload.jsp 出现上传界面(表单) - >
点击上传按钮 -> 路由跳转到form 中action的地址 - >
进入UploadController中对应函数进行处理 - >
跳转到showUploadFile.jsp界面 展示上传上去的图片
2>步骤:
1.配置web.xml 允许访问*.jpg(必须加在springmvc的servlet之前!!!)
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2.配置springmvc-servlet.xml 开放对上传功能的支持
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
3.upload.jsp 上传页面
- form 必须有method="post" 和 enctype="multipart/form-data"
- 上传组件:accept="image/*" 表示只能选择图片进行上传
- <input type="file" name="
" accept="image/*" /> 这个image 要与接收的实体类中的属性的名字一致
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*" isELIgnored="false"%>
<form action="uploadImage" method="post" enctype="multipart/form-data">
选择图片:<input type="file" name="image" accept="image/*" /> <br>
<input type="submit" value="上传">
</form>
4.准备接收图片的实体 UploadedImageFile
- 封装MultipartFile类型的字段 image ,用于接受页面的注入
- 这里的字段 image必须和上传页面upload.jsp中的image
<input type="file" name="" accept="image/*" />保持一致
package pojo;
import org.springframework.web.multipart.MultipartFile;
public class UploadedImageFile {
MultipartFile image;
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
}
5.UploadController
- 方法的第二个参数UploadedImageFile 中已经注入好了 image
- 通过 RandomStringUtils.randomAlphanumeric(10);获取一个随机文件名。 因为用户可能上传相同文件名的文件,为了不覆盖原来的文件,通过随机文件名的办法来规避
- 根据request.getServletContext().getRealPath 获取到web目录下的image目录,用于存放上传后的文件。
- 调用file.getImage().transferTo(newFile); 复制文件
- 把生成的随机文件名提交给视图,用于后续的显示
package controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
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;
@Controller
public class UploadController {
@RequestMapping("/uploadImage")
public ModelAndView upload(HttpServletRequest request, UploadedImageFile file)
throws IllegalStateException, IOException {
String name = RandomStringUtils.randomAlphanumeric(10);
String newFileName = name + ".jpg";
File newFile = new File(request.getServletContext().getRealPath("/image"), newFileName);
newFile.getParentFile().mkdirs();
file.getImage().transferTo(newFile);
ModelAndView mav = new ModelAndView("showUploadedFile");
mav.addObject("imageName", newFileName);
return mav;
}
}
6.showUploadedFile.jsp 显示图片的页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<img src="image/${imageName}"/>