Spring MVC(三)
接收表单数据:效果预览
注: addProduct.jsp 提交的name和price会自动注入到参数 product里
注: 参数product会默认被当做值加入到ModelAndView 中
- addProduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*" isELIgnored="false"%>
<form action="addProduct">
产品名称 :<input type="text" name="name" value=""><br />
产品价格: <input type="text" name="price" value=""><br />
<input type="submit" value="增加商品">
</form>
- 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>
<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>
</web-app>
- 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="irViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
- ProductController.java
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import pojo.Product;
@Controller
public class ProductController {
@RequestMapping("/addProduct")
public ModelAndView add(Product product) throws Exception {
ModelAndView mav = new ModelAndView("showProduct");
return mav;
}
}
- showProduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
产品名称: ${product.name}<br>
产品价格: ${product.price}
客户端跳转(重定向)
注意区分两种方式的不同
- IndexController.java
package controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class IndexController {
@RequestMapping("/index")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("index");
mav.addObject("message", "Hello Spring MVC");
return mav;
}
@RequestMapping("/jump")
public ModelAndView jump() {
ModelAndView mav = new ModelAndView("redirect:/index"); //表示客户端跳转
return mav;
}
}
- web.xml(和上面一样就不写了)
- springmvc-servlet.xml
- index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<h1>${message}</h1>
访问http://localhost:8080/springmvc2/jump结果客户端跳转到了http://localhost:8080/springmvc2/index
Session
Session在用户登录,一些特殊场合在页面间传递数据的时候会经常用到
访问localhost:8080/springmvc3/clear该路径后,清空session中的count. 并且客户端跳转到/check
- web.xml
- springmvc-servlet.xml
- IndexController
package controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class 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;
}
@RequestMapping("/clear") //访问该路径后,清空session中的count. 并且客户端跳转到/check
public ModelAndView clear(HttpSession session) {
session.setAttribute("count", 0);
ModelAndView mav = new ModelAndView("redirect:/check");
return mav;
}
}
- check.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
session中记录的访问次数:${count}
中文处理问题
在Spring MVC中处理中文问题和Filter处理中文问题是一样的手段
修改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>
<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>
<!--配置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>
</web-app>
上传文件
效果图
1.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">
<!--表示允许访问*.jpg。
为什么要加这一段呢? 因为配置springmvc的servlet的时候,使用的路径是"/",导致静态资源在
默认情况下不能访问,所以要加上这一段,允许访问jpg。 并且必须加在springmvc的servlet之前-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<!--表示允许访问*.gif-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</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>
<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>
</web-app>
- 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="irViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".jsp" />
</bean>
<!--开放对上传功能的支持-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
</beans>
- UploadedImageFile.java
package pojo;
import org.springframework.web.multipart.MultipartFile;
public class UploadedImageFile {
MultipartFile image; //MultipartFile类型的字段 image ,用于接受页面的注入
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
}
- upload.jsp
<%@ 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>
上传页面,需要注意的是form 的两个属性必须提供
method=“post” 和 enctype=“multipart/form-data” 缺一不可,
上传组件 增加一个属性 accept=“image/*” 表示只能选择图片进行上传,
留意 这个image,后面会用到这个image
- UploadController.java
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);
// 先获取到当前项目路径,加上"/image",加上文件名,组合成文件的绝对路径(在服务器上)
newFile.getParentFile().mkdirs(); // 为了避免空指针异常,先创建文件所在文件夹
file.getImage().transferTo(newFile); // 创建完文件夹,就可以把文件存储到服务器上了,这一步,文件已经成功保存
ModelAndView mav = new ModelAndView("showUploadedFile"); 先配置视图的位置
mav.addObject("imageName", newFileName);// 把参数设置好,后面jsp要用到,jsp中使用了"/image/${imageName}"这样的形式
return mav;
}
}
- showUploadedFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<img src="image/${imageName}"/>
喜欢的朋友可以关注我的个人公众号,后台回复java资料可免费领取资源。