一、搭建SpringMvc环境(简单四步搭建完成)
-
创建一个动态web项目
-
引入SpringMvc的相关包
-
配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <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:spring-mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <!--*.do拦截所有--> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
-
在src下创建解析视图配置文件夹(名字与定义解析视图对应spring-mvc.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:p="http://www.springframework.org/schema/p"
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/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描使用注解的包,包括子集 -->
<context:component-scan base-package="com.yuanhuan"/>
<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 视图解析器(解析到WEB-INF/jsp 下面的后缀为 .jsp的文件) -->
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
- 测试
//加上@Controller表示会扫描这个类
@Controller
public class HelloWorld {
//表示当访问helloWorld.do时候,会调用次方法
@RequestMapping("/helloWorld")
public String helloWorld(Model model) {
model.addAttribute("message", "SpringMvc你好");
return "helloWorld";
}
}
实例访问流程:
- 当在网址上访问http://localhost:8080/SpringMvcStudy/helloWorld.do时,会被
org.springframework.web.servlet.DispatcherServlet(web.xml)接收请求。 - DispatcherServlet接收请求并分发Controller到上面测试HelloWorld类的helloWorld方法,
- helloWorld方法返回helloWorld字符串至视图解析器(spring-mvc.xml)
- 视图解析器解析将返回的helloWorld 与.jsp拼接,并解析到WEB-INF/jsp 下 寻找helloWorld.jsp并执行。
SpringMVC控制器相关知识
一、请求映射(就是上面的@controller,一个类里可写多个形成层次结构)
二、请求参数(如何接收从服务器返回的值,例子在下面)
三、返回模型和视图(上面例子是模型和视图分开返回,下面ModeAndView就是一个整体,将视图和模型封装,例子在下面)
一二三的例子如下:
@Controller
//因为项目中会有很多Controller,所以这里定义是为了结构分层
@RequestMapping("/student")
public class StudentController {
public static List<Student> studentList = new ArrayList<>();
static {
studentList.add(new Student(1, "张三", 13));
studentList.add(new Student(2, "李四", 14));
studentList.add(new Student(3, "王五", 15));
}
@RequestMapping("/preSave")//请求映射分层结构,访问该方法,就为student/preSave.do
//接收服务器的参数:@RequestParam(value="id",required = false)意思是可以从服务器接收名为id的数据,并赋值给后面紧跟的值
public ModelAndView addStudent(@RequestParam(value="id",required = false)String id2) {
ModelAndView modelAndView = new ModelAndView();
//底层是放在request中(注意引包一定是org.springframework.web.servlet.ModelAndView,不然取不到数据)
if(id2==null){
modelAndView.setViewName("student/add");
}else {
modelAndView.addObject("student", studentList.get(Integer.valueOf(id2) - 1));
modelAndView.setViewName("student/update");
}
//返回视图和模型
return modelAndView;
}
}
四、SpringMvc对象属性自动封装
就是从服务器传来数据时,根据name值自动封装为类的对象,必须要name的值与类属性名相同才行
@RequestMapping("/save")
//自动将从服务器表单里面的name,age 封装到student中
public String saveStudent(Student student) {
studentList.add(student);
//重定向(客户端跳转)
return "redirect:/student/list.do";
}
五、SpringMvc Post乱码问题
表单post提交到后台时会乱码,springmvc提供过滤器处理乱码问题
在web.xml中加入:
<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>*.do</url-pattern>
</filter-mapping>
六、Controller 内部转发和重定向
//重定向(客户端跳转)
return "redirect:/student/list.do";
//内部转发(服务器跳转,可携带参数和request范围值
//return "forword:/student/list.do";
七、SpringMvc 对 ServletAPI 的支持
就是服务器方法那边一样可以使用request,response,session等对象,方便数据的传输,上面ModelAndView虽然可以从服务器到前台,但从前台到服务器上面只讲了通过参数接收和自动匹配对象属性。但如果要具体从前台取得一些数组什么的还是不方便,所以可以用servlet对象来传送。
@RequestMapping("/login")
//参数也可以时session,随意搭配都可以
public String login(HttpServletRequest request, HttpServletResponse response) {
String name=request.getParameter("name");
String password=request.getParameter("password");
request.getSession().setAttribute("currentUser",name);
return "redirect:/main.jsp";
}
八、SpringMvc 对 Json 的支持
在服务器返回对象时,直接自动转换为json对象(开发一般不用,虽然方便,但不方便管理)
步骤:
- 在视图解析文件spring-mvc.xml中加入三条语句,
xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
添加完成后为:
- 在视图解析文件spring-mvc.xml中加入
<!--支持对象与json的转换-->
<mvc:annotation-driven/>
-
加入jackson包
-
在需要转json格式的类的定义时加上@RequestMapping("/getAjaxUser")
具体例子:
@RequestMapping("/getAjaxUser")
public @ResponseBody User getUser() {
return new User("袁欢", "123");
}
SpringMvc 文件上传
支持单文件多文件上传(多文件就是同时上传多个文件)
-
引入包:
-
在spring-mvc.xml视图解析文件中加入
<!--上传文件配置--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--第一个时设置上传编码,第二个时设置上传的最大容量--> <property name="defaultEncoding" value="UTF-8"/> <property name="maxUploadSize" value="10000000"/> </bean>
-
使用例子:
网页:
<form method="post" action="${pageContext.request.contextPath }/file/upload2.do" enctype="multipart/form-data">
<table>
<tr>
<td colspan="2">文件上传</td>
</tr>
<tr>
<td>选择文件</td>
<td><input type="file" id="file" name="file"></td>
</tr>
<tr>
<td>选择文件</td>
<td><input type="file" id="file1" name="file"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交"></td>
</tr>
</table>
</form>
服务器:
@Controller
@RequestMapping("/file")
public class FileService {
//单文件
@RequestMapping("/upload1")
public String uploadFile(@RequestParam(value = "file")MultipartFile file, HttpServletRequest request) throws IOException {
//获得项目路径
String filePath=request.getServletContext().getRealPath("/");
printPath(request);
file.transferTo(new File(filePath + "upload3/" + file.getOriginalFilename()));
return "redirect:/main.jsp";
}
//多文件
@RequestMapping("/upload2")
public String uploadFile(@RequestParam(value = "file")MultipartFile []files, HttpServletRequest request) throws IOException {
String filePath=request.getServletContext().getRealPath("/");
for(MultipartFile file:files)
file.transferTo(new File(filePath + "upload3/" + file.getOriginalFilename()));
return "redirect:/main.jsp";
}
}