springmvc的响应
Springmvc的响应和作用域使用:
方式一:用字符串响应
请求转发:
单元方法的返回值类型为String类型
使用 return "forward:/文件路径"
重定向:
单元方法的返回值类型为String类型
使用 return "redirect:/文件路径"
注意:
返回值中的第一个/表示项目根目录。
方式二:使用Springmvc的原生对象响应:
使用View
请求转发:
单元方法的返回值类型为View类型
View v=new InternalResourceView("/show.jsp");//相当于请求转发。
重定向:
单元方法的返回值类型为View类型
View v=new RedirectView("/05-springmvc/show.jsp");//重定向,但是/代表服务器根目录
使用ModelAndView:
请求转发:
单元方法的返回值类型为ModelAndView类型
ModelAndView mv=new ModelAndView("forward:/show.jsp");
重定向:
单元方法的返回值类型为ModelAndView类型
ModelAndView mv=new ModelAndView("redirect:/show.jsp");
方式三:直接响应
--------------------------------------------------------------------
SpringMVC的作用域使用:
方式一:使用原生的request对象和session对象
使用方式不变。
方式二:在单元方法上声明Map形参,使用Map进行作用域数据传递。
注意:此种方式相当于使用request,请求转发。
方式三:在单元方法声明Model形参,使用Model实例化对象进行数据传递。
注意:此种方式相当于使用request,请求转发。
-----------------------------------------------------------------------
Spring MVC响应的例子
源码:
@Controller
public class TestCon {
/**
* 方式一:使用字符串:
* 请求转发
* 单元方法的返回值类型为字符串类型
* 返回值中使用"forward:转发资源的相对路径"。
* 注意:forward可以省略不写
* 作用域:
* request作用域:和以前一样,正常使用即可。request对象需要在单元方法上作用形参声明。
* session作用域:和以前一样,正常使用即可。session对象需要在单元方法上作用形参声明。
*
* 重定向
* 单元方法的返回值类型为字符串类型
* 返回值中使用"redirect:转发资源的相对路径"。
*
* 相对路径:
* 相对的是请求地址路径,会将请求地址的最后一个字母直接替换为返回值中的路径,并请求新路径的资源。
* 注意:
* 在请求准发和重定向的路径中第一个开头的/表示项目根目录。
* @return
*/
@RequestMapping("demo1/aa")
public String demo(HttpServletRequest req,HttpSession hs){
System.out.println("使用字符串直接响应----请求转发");
req.setAttribute("str", "our teacher`s english is good");
hs.setAttribute("ss", "Springmvc is easy for me");
return "forward:/show.jsp";
}
@RequestMapping("demo2/bb")
public String demo2(){
System.out.println("使用字符串直接响应----重定向");
return "redirect:/show.jsp";
}
/**
* 方式二:
* 使用springmvc的原生对象:
* View
* ModelAndView
*/
@RequestMapping("view")
public View demo3(){
//View v=new InternalResourceView("/show.jsp");//相当于请求转发。
View v=new RedirectView("/05-springmvc/show.jsp");//重定向,但是/代表服务器根目录
return v;
}
@RequestMapping("mv")
public ModelAndView demo4(){
ModelAndView mv=new ModelAndView("forward:/show.jsp");
mv.addObject("str", "this is modelAndview");
return mv;
}
/**
* 方式三:直接响应
* @throws IOException
*
*/
@RequestMapping("resp")
public void demo5(HttpServletRequest req,HttpServletResponse resp) throws IOException{
resp.getWriter().write("today the weather is good,it is able to better study");
}
/**
* Spring mvc 的作用域:
* Map方式:
* 在单元方法上声明map集合对象
*
* Model方式:
* 在单元方法上声明Model类型的参数
* 注意:
* 此两种方式都相当于使用request
*
*/
@RequestMapping("map")
public String demoMap(Map<String ,Object> map) throws IOException{
map.put("str", "this is map");
return "/show.jsp";
}
@RequestMapping("model")
public String demoModel(Model m) throws IOException{
m.addAttribute("str", "this is model");
return "/show.jsp";
}
}
springmvc的视图解析器
SpringMVC的视图解析器:
问题:
因为WEB-INF文件夹对浏览器是不可见的。所以开发的时候,往往会将
Jsp文件和静态资源文件存放在WEB-INF文件夹先,对资源进行保护。
必须使用请求转发才能访问。这样造成单元方法的返回值书写变得麻烦。
解决:
使用自定义视图解析器
使用:
在Springmvc的配置文件中配置自定义视图解析器
<!-- 配置自定义视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
注意:
如果使用了自定义视图解析器,在请求转发使用forward关键触发默认视图解析器,来转发
单元方法。
springmvc的上传和下载
SpringMVC的上传:
导入jar包
创建jsp文件,并设置为上传模式
配置Springmvc
将上传的文件存到指定位置
springmvc的配置:
<!-- 配置上传资源解析对象 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property><!--设置解析编码格式 -->
<property name="maxInMemorySize" value="150000"></property><!--内存大小 -->
<property name="maxUploadSize" value="1024123123"></property><!--文件大小 -->
</bean>
<!--配置异常解析器 --><!-- 异常映射解析类:当出现什么类型异常时,跳转到指定位置. -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">sizeLimit</prop>
</props>
</property>
</bean>
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>
<form action="upload" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="uname" value=""/> <br />
年龄:<input type="text" name="age" value=""/><br />
头像:<input type="file" name="photo" /><br />
<input type="submit" value="提交" /><br />
</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>
<img src="images/1.jpg" width="200px" /><a href="down?filename=1.jpg">下载</a>
</body>
</html>
控制器:
@Controller
public class TestUpload {
//上传
@RequestMapping("upload")
public String upload(String uname,int age,MultipartFile photo) throws IllegalStateException, IOException{
//将图片存储到指定位置
//校验文件类型
//获取文件后缀名
String suffixName=photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf("."));
//判断
if(!(".jpg".equals(suffixName) || ".png".equals(suffixName))){
return "error";
}
//设置文件大小
//文件重命名
String newName=UUID.randomUUID()+""+suffixName;
//创建存储路径
File f=new File("D:/images");
if(!f.exists()){
f.mkdirs();
}
File f2=new File(f,newName);
photo.transferTo(f2);
//将相关数据存储到数据库中(上传人,真实名,新名,存储路径)
return "success";
}
//下载
@RequestMapping("down")
public void down(String filename,HttpServletRequest req,HttpServletResponse resp) throws IOException{
//设置响应头
resp.setContentType("application/octet-stream");//表示任意类型
resp.setHeader("Content-Disposition", "attachment;filename=abcdef.jpg");
//获取要下载的图片的路径
String path=req.getServletContext().getRealPath("/images");
File f=new File(path,filename);
//获取输出流资源
OutputStream os=resp.getOutputStream();
//输出图片资源
os.write(FileUtils.readFileToByteArray(f));
os.flush();
os.close();
}
}
SpringMVC 和jsp的上传下载的区别:
jsp需要编程人员手动创建Upload对象解析数据,而Spring MVC 可以直接自动帮助编程人员完成解析并且返回封装好的文件对象。
springmvc的编码过滤器
字符编码过滤器只能解决POST请求.
解决请求和响应编码格式
只需要把filter在web.xml中配置出来,就让这个Filter生效
<!--配置编码过滤器 -->
<filter>
<filter-name>encoding</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>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
web.xml和springmvc最新
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<!--配置spring -->
<!--配置applicationContext,xml的路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置监听器 -->
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
<!--配置SpringMVC 的servlet -->
<servlet>
<servlet-name>servlet123</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置Spring MVC 的配置文件路径 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>servlet123</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置编码过滤器 -->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
springmvc.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.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.bjsxt.controller"></context:component-scan>
<!-- 配置解析器 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 配置静态资源放行 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
<!-- 配置自定义视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置上传资源解析对象 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property><!--设置解析编码格式 -->
<property name="maxInMemorySize" value="150000"></property><!--内存大小 -->
<property name="maxUploadSize" value="1024123123"></property><!--文件大小 -->
</bean>
<!--配置异常解析器 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">sizeLimit</prop>
</props>
</property>
</bean>
</beans>
细节问题
控制器方法HandlerMethod的配置办法:
响应字符串方式:
原生的响应方式应该是使用ModerAndView 去调用jsp .例如:
@RequestMapping("mv")
public ModelAndView demo4(){
ModelAndView mv=new ModelAndView("forward:/show.jsp");
mv.addObject("str", "this is modelAndview");
return mv;
}
但是Spring简化了这个流程,把创建ModerAndView的过程交给了DispatcherServlet来处理。
如果需要存数据,底层用的是Map<String,Obejct>.
dispatcherServlet 接收到字符串后,用字符串代替地址栏的别名。
forward:/show.jsp /show.jsp绝对路径
例子:
@RequestMapping("demo1/aa")
public String demo(HttpServletRequest req,HttpSession hs){
System.out.println("使用字符串直接响应----请求转发");
req.setAttribute("str", "our teacher`s english is good");
hs.setAttribute("ss", "Springmvc is easy for me");
return "forward:/show.jsp";
}
视图解析器:
WEB-INF文件夹:对于浏览器是不可见的。但是请求转发可以访问。重定向也不可访问。
如果使用自定义解析器,返回的字符串可以直接写别名,不用写.jsp
自定义解析器的好处:
编写代码时,设置跳转视图时方便.(控制器方法返回值)
例子:
<!-- 自定义视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/page/"></property>
<!-- 后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
控制器:@RequestMapping("demo1")
public String demo1(){
System.out.println("执行demo1");
return "demo1";
}
访问控制器demo1后会跳转到/WEB-INF/page/demo1.jsp
如果想转发到其他单元方法,可以在返回值前添加forward:或redirect:让系统不执行自定义视图解析器.执行系统默认视图解析器,例子:
@RequestMapping("demo2")
public String demo2(){
System.out.println("执行demo2");
return "redirect:demo1";
}
文件上传:
上传图片到数据库问题:
1、把文件存放到服务器硬盘上,然后把文件路径和文件信息存放到数据库中。
2、把文件直接以二进制的形式存放到数据库中,这种效率比较低,一般推荐使用第一种。
现在流行的都是云存储方式,直接在阿里云或者腾讯云的服务器上的硬盘上存储。
MIME类型:MIME (Multipurpose Internet Mail Extensions) 是描述消息内容类型的因特网标准。
MIME 消息能包含文本、图像、音频、视频以及其他应用程序专用的数据。
参考网址:http://www.w3school.com.cn/media/media_mimeref.asp
类型/子类型 扩展名
image/jpeg jpg
//动态获取项目根目录
File path=new File(this.getServletContext().getRealPath("/images"));
适用于上线阶段。
os.flush()的问题:
java在使用流时,都会有一个缓冲区,按一种它认为比较高效的方法来发数据:把要发的数据先放到缓冲区,缓冲区放满以后再一次性发过去,而不是分开一次一次地发.而flush()表示强制将缓冲区中的数据发送出去,不必等到缓冲区满.所以如果在用流的时候,没有用flush()这个方法,很多情况下会出现流的另一边读不到数据的问题,特别是在数据特别小的情况下.
jsp上传下载复习
jsp:
导入:commons-fileupload-1.3.2.jar
commons-io-2.5.jar
<body>
<h3>欢迎注册506班级系统</h3>
<hr />
<form action="upload" method="post" enctype="multipart/form-data">
用户名: <input type="text" name="uname" value=""/><br />
年龄: <input type="text" name="age" value=""/><br />
头像: <input type="file" name="photo" value="" /><br />
<input type="submit" value="提交"/>
</form>
</body>
servlet:
public class UploadServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//设置请求编码格式
req.setCharacterEncoding("utf-8");
//设置响应编码格式
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//获取上传请求数据
//创建解析工厂类对象
FileItemFactory factory=new DiskFileItemFactory();
//创建上传流数据解析对象
ServletFileUpload upload=new ServletFileUpload(factory);
//设置解析编码格式
upload.setHeaderEncoding("utf-8");
//设置解析数据的限定大小
upload.setSizeMax(1024*1024*6);
//设置单个文件的限定大小
upload.setFileSizeMax(1024*1024*3);
//解析数据
List<FileItem> fileItems=null;
try {
fileItems = upload.parseRequest(req);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//声明变量记录上传的相关信息
String uname="";
String age="";
String contentType="";
String realname="";
String newName="";
//遍历解析数据的List集合
for(FileItem item:fileItems){
// System.out.println("获取资源的类型(普通表单项为null):"+item.getContentType());
// System.out.println("获取表单项的name属性值:"+item.getFieldName());
// System.out.println("获取上传的文件名(普通表单项为null)"+item.getName());
// System.out.println("获取资源的大小"+item.getSize());
// System.out.println("获取资源的字符串数据:"+item.getString("utf-8"));
// System.out.println("普通表单项值为true,上传表单项为false:"+item.isFormField());
// System.out.println("----------------------------------");
//判断存储了上传资源的FileItem对象
if(!item.isFormField()){
//获取文件类型
contentType=item.getContentType();
//上传文件重命名,避免覆盖
//获取真实文件名
realname=item.getName();
System.out.println(realname);
//获取文件的后缀名
String suffixName=realname.substring(realname.lastIndexOf("."));
//创建新的文件名
newName=System.currentTimeMillis()+""+UUID.randomUUID()+""+suffixName;
//校验文件上传类型
if(!(".jpg".equals(suffixName) || ".png".equals(suffixName))){
resp.getWriter().write("文件类型不不正确,只接受类型.jpg和.png的图片");
return;
}
//校验文件大小
Long size=item.getSize();
if(size>1024*1024*5){
resp.getWriter().write("文件大小超出限制,大小限制为5KB");
return;
}
//创建存储目录
//动态获取项目根目录
File path=new File(this.getServletContext().getRealPath("/images"));//适用于上线阶段
//File path=new File("D:/images");//适用于开发阶段
//判断并创建指定目录
if(!path.exists()){
path.mkdirs();
}
//创建存储路径
File realpath=new File(path,newName);
//将上传资源存储到硬盘中
try {
item.write(realpath);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
//获取普通表单项数据
if("uname".equals(item.getFieldName())){
uname=item.getString("utf-8");
}else if("age".equals(item.getFieldName())){
age=item.getString("utf-8");
}
}
}
//调用业务层对象将数据存储到数据库中
UploadService us=new UploadServiceImpl();
//将数据存储
int i=us.insertUploadInfoService(uname, age, contentType, realname, newName);
//判断
if(i>0){
req.getSession().setAttribute("newName", newName);
//重定向到主页面
resp.sendRedirect("main.jsp");
}
}
}
--------------------------------------------------------------------------------
下载:
jsp:
<body>
<h3>文件上传成功,6666,上传的文件为:</h3>
<hr />
<img src="images/${newName}" width="300px"/><a href="down?uid=3">下载</a>
</body>
servlet:
public class DownLoadServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//设置请求编码格式
req.setCharacterEncoding("utf-8");
//设置响应编码格式
resp.setCharacterEncoding("utf-8");
//获取请求信息
String uid=req.getParameter("uid");
//处理请求信息
//根据UID获取该用户的上传信息
DownLoadService ds=new DownLoadServiceImpl();
Upload p=ds.getUploadInfoService(uid);
//设置响应文件类型
resp.setContentType(p.getContenttype());
//设置响应头告诉浏览器资源需要下载到客户端的硬盘中
System.out.println(p.getRealname());
resp.setHeader("Content-disposition","attachment;filename="+p.getNewname());
//获取要下载的资源的路径
String path=this.getServletContext().getRealPath("/images");
//创建File对象获取绝对路径
File f=new File(path,p.getNewname());
//获取资源读取流对象
InputStream is=new FileInputStream(f);
//获取输出流对象
OutputStream os= resp.getOutputStream();
//将图片下载给浏览器
IOUtils.copy(is, os);
//关闭流资源
is.close();
os.close();
}
}
上传下载小例子
1、导入相关Jar包,注意得有2个上传下载相关的包
2、一张图片
src:
springmvc.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.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.bjsxt.controller"></context:component-scan>
<!--配置注解驱动器 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!--配置静态资源放行 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
<!--配置自定义视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置上传资源解析对象 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property><!--设置解析编码格式 -->
<property name="maxInMemorySize" value="150000"></property><!--设置所占内存大小 -->
<property name="maxUploadSize" value="1024123123"></property><!--设置文件上传大小 -->
</bean>
<!--配置异常解析器 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">sizelimit</prop>
</props>
</property>
</bean>
</beans>
com.bjsxt.controller:
TestUploadDown.java:
package com.bjsxt.controller;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.aspectj.util.FileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import sun.reflect.misc.FieldUtil;
@Controller
public class TestUploadDown {
@RequestMapping("upload")
public String upload(String uname,String uage,MultipartFile photo) throws IllegalStateException, IOException{
//将文件存储到指定的位置
//校验文件类型
//获取文件后缀名
String suffixName=photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf("."));
//判断
if(!(".png".equals(suffixName)||".jpg".equals(suffixName))){
return "error";
}
//设置文件大小
//文件重命名
String newName=UUID.randomUUID()+""+suffixName;
//创建存储路径
File f=new File("c:/images");
if(!f.exists()){
f.mkdirs();
}
File f2=new File(f,newName);
//保存文件
photo.transferTo(f2);
//将相关文件信息存储到数据库中
//请求转发到新页面
return "success";
}
//下载
@RequestMapping("down")
public void down(String fileName,HttpServletRequest req,HttpServletResponse resp) throws IOException{
//设置浏览器不解析,直接下载
resp.setHeader("Content-Disposition", "attachment;filename=abcdef.jpg");
//设置响应头
resp.setContentType("application/octet-stream");
//获取要下载的图片路径
String path=req.getServletContext().getRealPath("/images");
File f=new File(path,fileName);
//获取输出流资源
OutputStream os=resp.getOutputStream();
//输出图片资源
os.write(FileUtils.readFileToByteArray(f));
os.flush();
os.close();
}
}
WebContent:
images:1.jpg
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<!--配置spring -->
<!--配置springmvc -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--配置编码过滤器 -->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
upload.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>
<form action="upload" method="post" enctype="multipart/form-data">
用户名<input type="text" name="uname" value=""/><br />
年龄 <input type="text" name="uage" value=""/><br />
头像 <input type="file" name="photo"/><br />
<input type="submit" value="提交" /><br />
</form>
</body>
</html>
down.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>
<img src="image/1.jpg" width="200px"/> <a href="down?fileName=1.jpg">点击下载</a>
</body>
</html>
WEB-INF:
page:
success.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>
upload success!
</body>
</html>
error.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>
upload error!
</body>
</html>
sizelimit.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>
upload too big!
</body>
</html>
源码:
链接:https://pan.baidu.com/s/12ARPig96QtnaosVVrgxNWQ 密码:mwdl
小案例
需求分析:
数据库设计:
t_user:
CREATE TABLE `t_user` (
`uid` int(10) NOT NULL AUTO_INCREMENT,
`uname` varchar(100) NOT NULL,
`upwd` varchar(100) NOT NULL,
PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
email:
CREATE TABLE `email` (
`eid` int(10) NOT NULL AUTO_INCREMENT,
`rid` int(10) NOT NULL,
`sid` int(10) NOT NULL,
`title` varchar(100) NOT NULL,
`content` varchar(1000) NOT NULL,
`filename` varchar(100) NOT NULL,
`date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`eid`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
1、导入相关jar包
aopalliance.jar
asm-3.3.1.jar
aspectjweaver.jar
cglib-2.2.2.jar
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
commons-logging-1.1.1.jar
commons-logging-1.1.3.jar
jackson-annotations-2.4.0.jar
jackson-core-2.4.1.jar
jackson-databind-2.4.1.jar
javassist-3.17.1-GA.jar
jstl-1.2.jar
log4j-1.2.17.jar
log4j-api-2.0-rc1.jar
log4j-core-2.0-rc1.jar
mybatis-3.2.7.jar
mybatis-spring-1.2.3.jar
mysql-connector-java-5.1.30.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar
spring-aop-4.1.6.RELEASE.jar
spring-aspects-4.1.6.RELEASE.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
spring-jdbc-4.1.6.RELEASE.jar
spring-tx-4.1.6.RELEASE.jar
spring-web-4.1.6.RELEASE.jar
spring-webmvc-4.1.6.RELEASE.jar
standard-1.1.2.jar
文件目录:
src:
applicationContext.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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
"
default-autowire="byName"
>
<!--配置注解扫描 -->
<context:component-scan base-package="com.bjsxt.serviceImpl,com.bjsxt.pojo"></context:component-scan>
<!--配置代理模式为cglib -->
<aop:aspectj-autoproxy proxy-target-class="true" ></aop:aspectj-autoproxy>
<!--配置数据源文件扫描 -->
<context:property-placeholder location="classpath:db.properties"/>
<!--配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--配置工厂 -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"></bean>
<!--配置mapper包扫描 -->
<bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.bjsxt.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="factory"></property>
</bean>
<!--配置事务 -->
<!--配置事务Bean -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"></bean>
<!--配置事务管理办法 -->
<tx:advice id="advice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="ins*"/>
<tx:method name="del*"/>
<tx:method name="up*"/>
<tx:method name="sel*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--配置相关事件 -->
<aop:config>
<aop:pointcut expression="execution(* com.bjsxt.serviceImpl.*.*(..))" id="my"/>
<aop:advisor advice-ref="advice" pointcut-ref="my"/>
</aop:config>
<!--配置切面 -->
<!--配置切点bean -->
<!--配置通知bean -->
<!--织入形成切面 -->
<!--配置其他bean -->
</beans>
springmvc.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.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.bjsxt.controller"></context:component-scan>
<!--配置mvc注解驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!--配置静态资源方式 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
<!--配置自定义视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/email/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置上传资源解析对象 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxInMemorySize" value="150000"></property>
<property name="maxUploadSize" value="1024123123"></property>
</bean>
<!--配置异常解析器 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">sizeLimit</prop>
</props>
</property>
</bean>
</beans>
db.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root
log4j.properties:
log4j.rootCategory=info,LOGFILE
log4j.logger.com.bjsxt.mapper=debug, CONSOLE
log4j.logger.com.bjsxt.advice=debug, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=- %c-%d-%m%n
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=C:/BiZhi/axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=- %c-%d-%m%n
com.bjsxt.controller:
EmailController.java:
package com.bjsxt.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import com.bjsxt.pojo.Email;
import com.bjsxt.pojo.User;
import com.bjsxt.service.EmailService;
@Controller
public class EmailController {
//声明业务层对象
@Resource
private EmailService emailServiceImpl;
//登录检测
@RequestMapping("login")
public String login(String uname,String upwd,HttpServletRequest req){
//调用业务层对象
User user = emailServiceImpl.checkUserInfo(uname, upwd);
if(user!=null){
req.getSession().setAttribute("user", user);
return "redirect:main";
}else{
req.setAttribute("str", "账号或密码错误,请重新输入");
return "forward:/login.jsp";
}
}
//主页面显示
@RequestMapping("main")
public String main(HttpServletRequest req){
//获取当前用户ID
int uid=((User)req.getSession().getAttribute("user")).getUid();
//调取业务层处理数据
List<Email> lm=emailServiceImpl.selEmailInfo(uid);
//返回响应页面
req.setAttribute("lm", lm);
return "main";
}
//公共转发方法
@RequestMapping("{path}")
public String restful(@PathVariable String path){
return path;
}
//发送邮件
@RequestMapping("s")
public String send(int rid,String title,String content,MultipartFile photo,HttpServletRequest req) throws IllegalStateException, IOException{
//保存图片
//判断文件类型
//获取文件后缀名
String suffixName=photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf("."));
//判断文件类型
if(!(".jpg".equals(suffixName)||".png".equals(suffixName))){
return "error";
}
//文件重命名
String newName=UUID.randomUUID()+suffixName;
//创建保存路径
File f=new File(req.getServletContext().getRealPath("/images"),newName);
photo.transferTo(f);
//保存图片信息到数据库
//获取当前用户ID
int uid=((User)req.getSession().getAttribute("user")).getUid();
//处理数据
int i= emailServiceImpl.insertEmail(rid, uid, title, content, newName);
if(i>0){
//将文件名存到作用域中
req.setAttribute("newName", newName);
//返回结果
return "success";
}
return "error";
}
}
com.bjsxt.mapper:
EmailMapper.java
package com.bjsxt.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.bjsxt.pojo.Email;
import com.bjsxt.pojo.User;
public interface EmailMapper {
//验证用户名密码
User checkUserInfo(String uname,String upwd);
//根据ID获取email信息
List<Email> selEmailInfo(int rid);
//插入发送信件信息
int insertEmail(int rid,int sid,String title,String content,String filename);
}
EmailMapper.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjsxt.mapper.EmailMapper">
<!--根据账号密码查询用户信息 -->
<select id="checkUserInfo" resultType="com.bjsxt.pojo.User">
select * from t_user where uname=#{0} and upwd=#{1}
</select>
<!--根据账户ID查询邮件信息 -->
<resultMap type="com.bjsxt.pojo.Email" id="rm">
<id column="eid" property="eid"/>
<result column="rid" property="rid"/>
<result column="sid" property="sid"/>
<result column="title" property="title"/>
<result column="content" property="content"/>
<result column="filename" property="filename"/>
<result column="date" property="date"/>
<association property="user" javaType="com.bjsxt.pojo.User">
<id column="uid" property="uid"/>
<result column="uname" property="uname"/>
<result column="upwd" property="upwd"/>
</association>
</resultMap>
<select id="selEmailInfo" resultMap="rm">
select * from email e
join t_user t
on e.sid=t.uid
where rid=#{0}
</select>
<!--插入信件信息 -->
<insert id="insertEmail">
insert into email values(default,#{0},#{1},#{2},#{3},#{4},now())
</insert>
</mapper>
com.bjsxt.pojo:
User.java:
package com.bjsxt.pojo;
public class User {
private int uid;
private String uname;
private String upwd;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(int uid, String uname, String upwd) {
super();
this.uid = uid;
this.uname = uname;
this.upwd = upwd;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpwd() {
return upwd;
}
public void setUpwd(String upwd) {
this.upwd = upwd;
}
@Override
public String toString() {
return "User [uid=" + uid + ", uname=" + uname + ", upwd=" + upwd + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + uid;
result = prime * result + ((uname == null) ? 0 : uname.hashCode());
result = prime * result + ((upwd == null) ? 0 : upwd.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (uid != other.uid)
return false;
if (uname == null) {
if (other.uname != null)
return false;
} else if (!uname.equals(other.uname))
return false;
if (upwd == null) {
if (other.upwd != null)
return false;
} else if (!upwd.equals(other.upwd))
return false;
return true;
}
}
Email.java:
package com.bjsxt.pojo;
public class Email {
private int eid;
private int rid;
private int sid;
private String title;
private String content;
private String filename;
private String date;
private User user;
public Email() {
super();
// TODO Auto-generated constructor stub
}
public Email(int eid, int rid, int sid, String title, String content, String filename, String date, User user) {
super();
this.eid = eid;
this.rid = rid;
this.sid = sid;
this.title = title;
this.content = content;
this.filename = filename;
this.date = date;
this.user = user;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public int getRid() {
return rid;
}
public void setRid(int rid) {
this.rid = rid;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Email [eid=" + eid + ", rid=" + rid + ", sid=" + sid + ", title=" + title + ", content=" + content
+ ", filename=" + filename + ", date=" + date + ", user=" + user + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((content == null) ? 0 : content.hashCode());
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + eid;
result = prime * result + ((filename == null) ? 0 : filename.hashCode());
result = prime * result + rid;
result = prime * result + sid;
result = prime * result + ((title == null) ? 0 : title.hashCode());
result = prime * result + ((user == null) ? 0 : user.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Email other = (Email) obj;
if (content == null) {
if (other.content != null)
return false;
} else if (!content.equals(other.content))
return false;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (eid != other.eid)
return false;
if (filename == null) {
if (other.filename != null)
return false;
} else if (!filename.equals(other.filename))
return false;
if (rid != other.rid)
return false;
if (sid != other.sid)
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
return true;
}
}
com.bjsxt.service:
EmailService.java:
package com.bjsxt.service;
import java.util.List;
import com.bjsxt.pojo.Email;
import com.bjsxt.pojo.User;
public interface EmailService {
//验证用户名和密码
User checkUserInfo(String uname,String upwd);
//根据ID获取邮件信息
List<Email> selEmailInfo(int rid);
//插入发送信件信息
int insertEmail(int rid,int sid,String title,String content,String filename);
}
com.bjsxt.serviceImpl:
EmailServiceImpl.java:
package com.bjsxt.serviceImpl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.bjsxt.mapper.EmailMapper;
import com.bjsxt.pojo.Email;
import com.bjsxt.pojo.User;
import com.bjsxt.service.EmailService;
@Service
public class EmailServiceImpl implements EmailService{
//声明mapper接口对象
@Resource
private EmailMapper emailMapper;
//验证用户名和密码
@Override
public User checkUserInfo(String uname, String upwd) {
return emailMapper.checkUserInfo(uname, upwd);
}
//根据ID获取邮件信息
@Override
public List<Email> selEmailInfo(int rid) {
return emailMapper.selEmailInfo(rid);
}
@Override
public int insertEmail(int rid, int sid, String title, String content, String filename) {
return emailMapper.insertEmail(rid, sid, title, content, filename);
}
}
WebContent:
login.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>登录页面</title>
</head>
<body>
<form action="login" method="get">
用户名 <input type="text" name="uname" value=""/><br />
密码 <input type="password" name="upwd" value="" /><br />
<input type="submit" value="登录"/></form>
<span> ${str}</span>
</body>
</html>
images文件夹
WEB-INF:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<!--配置Spring -->
<!--配置applicationContext,xml的路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置监听器 -->
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
<!--配置SpringMVC 的servlet -->
<servlet>
<servlet-name>servlet123</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置Spring MVC 的配置文件路径 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>servlet123</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--配置编码过滤器 -->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
email:
error.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>
error upload!
</body>
</html>
main.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>
<a href="send">发送邮件</a>
<table cellpadding="0" cellspacing="0" border=" solid 1px">
<tr height="30px">
<td width="200px">标题</td>
<td width="200px">时间</td>
<td width="200px">发送人</td>
</tr>
<c:forEach items="${lm}" var="e">
<tr>
<td>${e.title}</td>
<td>${e.date}</td>
<td>${e.user.uname}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
send.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>
<form action="s" method="post" enctype="multipart/form-data">
收件人: <input type="text" name="rid"/><br />
主题: <input type="text" name="title" /><br />
正文: <textarea name="content" id="" cols="30" rows="10"></textarea><br />
附件: <input type="file" name="photo" /><br />
<input type="submit" value="提交" /><br />
</form>
</body>
</html>
sizeLimit.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>
上传文件超出限制。
</body>
</html>
success.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>
success upload!
<a href="main">点击跳转</a> 主页面
上传文件为 <img src="images/${newName}" alt="" />
</body>
</html>
源码:
链接:https://pan.baidu.com/s/1eq5PoUs_NzCXdUUzYMGdUA 密码:w2yb
小案例总结
技能点1:
Mysql数据库 :timestamp 时间戳
显示日期加时间
java pojo 类 用String date存。
now() 表示当前系统时间, 是日期加时间。
技能点2:
公共跳转方法:
利用restful: {page}接收的是请求名d'd Localhost:8080/项目名/请求名
@RequestMapping("{page}")
public String goPage(@PathVariable String page){
return page;
}
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
作业知识点整理:
1、使用restful声明公共单元方法,主要是用来进行页面的请求转发的。
@RequestMapping("{path}")
public String getJsp(@PathVariable String path){
System.out.println("1111");
return path;
}
2、静态资源存储到WEB-INF文件夹,则需要在springmvc.xml中的
静态资源放行映射路径中加上WEB-INF
<mvc:resources location="/WEB-INF/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/WEB-INF/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/WEB-INF/images/" mapping="/images/**"></mvc:resources>
模拟邮箱:
需求分析:
功能分析:
登录功能
主页面显示邮件信息功能
发送邮件功能
数据库设计:
用户表t_user
用户ID
用户名
密码
邮件表 email
邮件ID
收件人
发件人
主题
正文
时间
附件
将用户ID作为 发件人和收件人的ID
技术分析:
SpringMVC+spring+mybatis+jsp+js+html+css+jquery+ajax
功能分析:
搭建SSM运行环境
登录功能:
点击登录发送请求到服务器的servlet
----------------------------------------->servlet
根据请求地址寻找单元方法
调用单元方法
接受返回值
请求转发或者重定向
----------------------------------->controller
创建单元方法
声明形参
处理请求
调用业务层对象校验用户登录信息
成功
将用户信息存储到session中
重定向到main.jsp
失败
请求转发到登录页面
-------------------------------->service
创建业务方法
声明形参
调用mapper对象查询用户信息
返回结果
------------------------------->mapper
创建mapper.xm文件
创建接口
小结
springmvc的响应
springmvc的视图解析器
springmvc的上传和下载
springmvc的编码过滤器
web.xml和springmvc最新
细节问题
jsp上传下载复习
上传下载小例子
小案例
小案例总结