入门-第一个SpringMVC程序

jars

spring-aop.jar

spring-bean. jar

spring-context. jar

spring-core. jar

spring-web. jar

spring-webmvc. jar

spring-webmvc.jar

commons-logging

image-20210123222410984

配置web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?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">
<display-name>SpringMVCProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 配置映射 -->
<servlet>
<servlet-name>springDispatcherServlet</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>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

创建springmvc.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
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-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<!-- 扫描有注解的包 -->
<context:component-scan base-package="top.eshyee.Controller"></context:component-scan>
<!-- 配置视图解析器InternalResourceViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>

index.jsp/success.jsp

在WebContent中创建index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="welcome">firstSpringMVC</a>
</body>
</html>

再创建一个FOLDER起名“views”,其中创建success.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
第一个实例成功
</body>
</html>

编写SpringMVCController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package top.eshyee.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("SpringMVCController")
public class SpringMVCController {
// 通过method更改请求方式,params指定请求参数中必须有的参数 如:“name”且必须为zs,"age"!=23
@RequestMapping(value = "welcome")
public String welcome() {
return "success";
}
}

如果没配置错,运行成功。

其他配置

Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
//	通过method更改请求方式,params指定请求参数中必须有的参数 如:“name”且必须为zs,"age"!=23
@RequestMapping(value = "welcome", method = RequestMethod.POST, params = { "name=zs", "age!=23" })
public String welcome() {
return "success";
}

//限制请求头
@RequestMapping(value = "welcome2", headers = {
"accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"accept-encoding=gzip, deflate, br" })
public String welcome2() {
return "success";
}

JSP

1
2
3
4
5
6
7
8
<body>
<a href="SpringMVCController/welcome2">firstSpringMVC</a>
<form action="SpringMVCController/welcome" method="post">
<input name="name">
<input name="age">
<input type="submit" value="post">
</form>
</body>

ANT风格

Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//	ant风格
//中间 任意字符*,任意目录**
@RequestMapping(value = "welcome3/**/test")
public String welcome3() {
return "success";
}
// 中间单个字符
@RequestMapping(value = "welcome4/a?c/test")
public String welcome4() {
return "success";
}
@RequestMapping(value = "welcome5/{name}")
public String welcome5(@PathVariable("name") String name) {
System.out.println(name);
return "success";
}

jsp

1
2
3
<a href="SpringMVCController/welcome3/adas/test">ant风格1</a>
<a href="SpringMVCController/welcome4/abc/test">ant风格2</a>
<a href="SpringMVCController/welcome5/张三">ant风格-@PathVariable</a>

REST 实现delete和put

controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//REST 风格--通过隐藏域区分delete和put
@RequestMapping(value = "testPost/{name}")
public String testPost(@PathVariable("name") String name) {
System.out.println("增"+name);
return "success";
}
@RequestMapping(value = "testDelete/{name}" )
public String testDelete(@PathVariable("name") String name) {
System.out.println("删"+name);
return "success";
}
@RequestMapping(value = "testPut/{name}")
public String testPut(@PathVariable("name") Integer name) {
System.out.println("改"+name);
return "success";
}
@RequestMapping(value = "testGet/{name}")
public String testGet(@PathVariable("name") String name) {
System.out.println("查"+name);
return "success";
}
@RequestMapping(value="testRest/{id}",method=RequestMethod.DELETE)
public String testDelete(@PathVariable("id") Integer id) {
System.out.println("delete:删 " +id);
return "success" ;
}

jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<form action="SpringMVCController/testPost/1234" method="post">
<input type="submit" value="增">
</form><br/>
<form action="SpringMVCController/testDelete/1234" method="post">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="删">
</form><br/>
<form action="SpringMVCController/testPut/1234" method="post">
<input type="hidden" name="_method" value="PUT">
<input type="submit" value="改">
</form><br/>
<form action="SpringMVCController/testGet/1234" method="get">
<input type="submit" value="查">
</form><br/>
<form action="SpringMVCController/testRest/1234" method="post">
<input type="hidden" name="_method" value="DELETE"/>
<input type="submit" value="删">
</form>

过滤器 xml

1
2
3
4
5
6
7
8
9
<!-- 增加一个过滤器,目的是给普通浏览器增加delete|put的支持 -->
<filter>
<filter-name>HiddenHttpMethodFilte</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilte</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

杂项

Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@RequestMapping(value = "testParam")
// required = false,defaultValue = "2" 可以不传uage ,默认值为2,客户端没有传入uage参数才能生效defaultValue配置
public String testParam(@RequestParam("uname") String uname,@RequestParam(value="uage",required = false,defaultValue = "2") Integer uage) {
System.out.println(uname);
System.out.println(uage);
return "success";
}
@RequestMapping(value = "testRequestHeader")
public String testRequestHeader(@RequestHeader("Accept-Language") String al) {
System.out.println(al);
return "success";
}
@RequestMapping(value = "testCookieValue")
public String testCookieValue(@CookieValue("JSESSIONID") String jSessionId) {
System.out.println(jSessionId);
return "success";
}

// 使用原生态的ServletAPI--直接使用
@RequestMapping(value = "testSerlet")
public String testSerlet(HttpServletRequest request, HttpServletResponse response) {
System.out.println(request);
System.out.println(response);
return "success";
}

JSP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</form>
<br />
<form action="SpringMVCController/testParam" method="post">
<input type="text" name="uname">
<!-- <input type="text" name="uage"> -->
<input type="submit" value="提交">

</form>
<br />
<a href="SpringMVCController/testRequestHeader">testRequestHeader</a>

<br />
<a href="SpringMVCController/testCookieValue">testCookieValue</a>
<br />
<a href="SpringMVCController/testSerlet">testSerlet</a>
<br />

对象的接收(级联)

创建一个级联对象

Student

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package top.eshyee.entity;

public class Student {
private String name;
private int age;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", address=" + address + "]";
}
}

Address

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package top.eshyee.entity;

public class Address {
private String homeAddress;
private String schoolAddress;
public String getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
public String getSchoolAddress() {
return schoolAddress;
}
public void setSchoolAddress(String schoolAddress) {
this.schoolAddress = schoolAddress;
}
@Override
public String toString() {
return "Address [homeAddress=" + homeAddress + ", schoolAddress=" + schoolAddress + "]";
}
}

controller

1
2
3
4
5
@RequestMapping(value = "testObject")
public String testObject(Student student) {//属性必须跟表单内的值一样
System.out.println(student);
return "success";
}

jsp

1
2
3
4
5
6
7
<form action="SpringMVCController/testObject" method="post">
name:<input type="text" name="name"><br/>
age:<input type="text" name="age"><br/>
schooladdress:<input type="text" name="address.schoolAddress"><br/>
homeaddress:<input type="text" name="address.homeAddress"><br/>
<input type="submit" value="提交">
</form>

ModelAndView

Controller

1
2
3
4
5
6
7
8
9
@RequestMapping(value = "testModelAndView")
public ModelAndView testModelAndView() {
ModelAndView mv=new ModelAndView("success");
Student student=new Student();
student.setName("aa");
student.setAge(1);
mv.addObject("student",student);//相当于request.setAttribute
return mv;
}

Success JSP

用于展示拿到的值

1
${requestScope.student.age}--${requestScope.student.name}--

测试页面的JSP

1
2
<a href="SpringMVCController/testModelAndView">testModelAndView</a>
<br />

其他方法

Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@RequestMapping(value = "testModelMap")
public String testModelMap(ModelMap mm) {

Student student = new Student();
student.setName("aa");
student.setAge(1);
mm.put("student", student);// request域
return "success";
}

@RequestMapping(value = "testMap")
public String testMap(Map<String, Object> map) {

Student student = new Student();
student.setName("aa");
student.setAge(1);
map.put("student", student);// request域
return "success";
}

@RequestMapping(value = "testModel")
public String testModel(Model model) {

Student student = new Student();
student.setName("aa");
student.setAge(1);
model.addAttribute("student", student);// request域
return "success";
}

JSP

1
2
3
4
5
6
<a href="SpringMVCController/testModelMap">testModelMap</a>
<br />
<a href="SpringMVCController/testMap">testMap</a>
<br />
<a href="SpringMVCController/testModel">testModel</a>
<br />

如果要把request的中的对象放入session中,在类前加注解@SessionAttributes

Controller

1
2
3
4
5
6
@SessionAttributes("student")
@Controller
@RequestMapping("SpringMVCController")
public class SpringMVCController {
...
}

Success JSP

1
2
3
4
5
6
7
<body>
实例成功
request:<br/>
${requestScope.student.age}--${requestScope.student.name}--
<br/>session:<br/>
${sessionScope.student.age}--${sessionScope.student.name}--
</body>

视图、视图解析器

视图的顶级接口:View
视图解析器:ViewResolver常见的视图和解析器:
InternalResourceView、InternalResourceViewResolverpublic class JstlView extends InternalResourceView:
springMVC解析jsp时会默认使用InternalResourceView,如果发现Jsp中包含了jstl语言,则自动转为JstlView

JstlView 可以解析jst1\实现国际化操作

mvc:view-controller

在xml使用该标签可不用写Controller

xml

1
<mvc:view-controller path="Controller/testMvcViewController" view-name="success"/>

index jsp

1
<a href="Controller/testMvcViewController" >testMvcViewController</a>

但是只写mvc:view-controller 会自动屏蔽Controller

若需共存,需加标签

1
<mvc:annotation-driven></mvc:annotation-driven>

指定跳转方式

forward: 请求转发 redirect: 重定向

此种方式不会被视图解析器加上前缀和后缀

Controller中

1
return "forward:/views/success.jsp";//或者redirect

处理静态资源

在SpringMVC中,直接访问静态资源,会 报404

原因:所有请求在web.xml中被拦截,交给SpringMVC的DispatchServlet处理,然而该处理方式是直接找requestmapping了,但静态资源没有配requestmapping,所以404.

解决方式:不需要mvc的,交给tomcat的servlet处理

1
2
3
<!-- 该注解会使SpringMVC在收到没有对应requestmapping的请求时,将请求交给服务器的servlet处理 -->
<mvc:default-servlet-handler/>
<mvc:annotation-driven></mvc:annotation-driven>

类型转换

Spring自带一些常见的类型转换

可以自定义

i 编写自定义转换器的类(实现convert接口)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package top.eshyee.converter;

import org.springframework.core.convert.converter.Converter;

import top.eshyee.entity.Student;

public class MyConverter implements Converter<String,Student>{

@Override
public Student convert(String source) {//字符串--返回学生--传入格式1-zs-23
return new Student(Integer.parseInt(source.split("-")[0]),source.split("-")[1],Integer.parseInt(source.split("-")[2]));

}
}

ii 将编写的转换器加入到MVC中

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- 1 将转换器纳入SpringIOC容器 -->
<bean id="MyConverter" class="top.eshyee.converter.MyConverter"></bean>
<!-- 2 将MyConverter纳入到SpringMVC提供的bean中 -->
<bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="MyConverter"/>
</set>
</property>
</bean>
<!-- 将conversionServiceFactoryBean注册到annotationdriven中 -->
<!-- 此配置是mvc的基础配置 -->
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"></mvc:annotation-driven>

iii 测试

jsp

1
2
3
4
<form action="SpringMVCController/testConverter" method="post">
studentInfo:<input type="text" name="studentInfo"><br/>
<input type="submit" value="提交">
</form>

Controller

1
2
3
4
5
@RequestMapping(value = "testConverter") 
public String testConverter(@RequestParam("studentInfo") Student student) {
System.out.println(student);
return "success";
}

数据格式化

SpringMVC提供注解实现格式化

配置标签

1
2
3
<!-- 配置数据格式化 注解所依赖的bean -->
<bean id="formattingConversionServiceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"></bean>
<mvc:annotation-driven conversion-service="formattingConversionServiceFactoryBean"></mvc:annotation-driven>

添加注解

Student类中

1
2
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthday;