Maven Spring MVC
Maven Spring MVC 基础
-
创建 Maven / Spring MVC 项目
-
如果遇到 org.springframework 无法安装的情况 , 观看安装Tomcat,才可以安装
-
配置 文件 / 代码
pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
</dependency>
<!-- Spring springframework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>5.3.32</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.13</version>
</dependency>
<!-- Spring Core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>6.1.13</version>
</dependency>
<!-- Spring Web MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.1.13</version>
</dependency>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>6.1.13</version>
</dependency>
<!-- Fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.51</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>5.0.0</version>
<scope>provided</scope>
</dependency>
<!-- JSTL 顺序 1 -->
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<version>2.0.0</version>
</dependency>
<!-- JSTL 顺序 2 -->
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jakarta.servlet.jsp.jstl</artifactId>
<version>2.0.0</version>
</dependency>
<!-- JSTL 顺序 3 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- apache fileUpload 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.5</version>
</dependency>
<!-- apache fileUpload 文件上传 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.17.0</version>
</dependency>
<!-- JSR-303 使用 导入 -->
<!-- JSR-303 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>8.0.1.Final</version>
</dependency>
<!-- JSR-303 -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<!-- JSR-303 -->
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.5.3.Final</version>
</dependency>
<!-- JSR-303 / JDK9以上 安装 -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.4.0-b180830.0359</version>
</dependency>
<!-- JAXB API -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- JAXB Implementation -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.1</version>
</dependency>
<!-- JSR-303 / JDK9以上 安装 -->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- JSR-303 使用 导入 结束 -->
</dependencies>
<build>
<finalName>springMVC</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
不需要理会以下内容了,目前不需要手动处理!!!
配置 JSTL 问题,需要额外下载文件,再手动引入项目里。
打开文件,放在apache-tomcat/lib 里面,然后打开项目 -> File -> Project Structure -> Libraries -> 点击 + 引入刚刚的 jstl 文件,就可以使用了。
如果遇到观看此视频 点击这里观看
resource/spring.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置自动扫描-->
<context:component-scan base-package="com.xs"/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.xs.converter.DateConverter">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd"/>
</bean>
<bean class="com.xs.converter.StudentConverter"/>
</list>
</property>
</bean>
<!-- 启用注解驱动的 Spring MVC -->
<mvc:annotation-driven conversion-service="conversionService">
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
</bean>
<!-- Fastjson -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 图片上传配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>
</beans>
webapp/WEB-INF/web.xml (假如是使用 MVC的)
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<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_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<!-- 显示中文 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 能够使用Form的时候,PUT,DELETE -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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.xml</param-value>
</init-param>
<!-- 图片上传 配置 -->
<load-on-startup>1</load-on-startup>
<multipart-config>
<max-file-size>10485760</max-file-size>
<max-request-size>10485760</max-request-size>
<file-size-threshold>0</file-size-threshold>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring MVC 静态资源访问 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<!-- Spring MVC 显示图片 格式 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<!-- Spring MVC 显示图片 格式 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<!-- Spring MVC 显示图片 格式 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpeg</url-pattern>
</servlet-mapping>
</web-app>
正式开始
@Controller
@RequestMapping("/index")
package com.xs.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/hello")
public class HelloHandler {
@RequestMapping("/index")
public String index(){
System.out.println("接收请求");
// 返回 视图
return "index";
}
}
Method
@RequestMapping(value = "/index", method = RequestMethod.POST)
Params
@RequestMapping(value = "/index", method = RequestMethod.POST, params = "id")
@RequestMapping(value = "/index", method = RequestMethod.POST, params = {"id", "name", "age"})
URL**?id=1&name=Hoo**, x
@RequestMapping(value = "/index", method = RequestMethod.POST, params = {"id=1", "name=Hoo"})
Rest 风格
RestFul 功能, 使代码更加方便快速
@RequestMapping("/index/{id}/{name}")
public String restfulWay(Integer id, String name){
System.out.println(id + " " + name);
// 返回 视图
return "index";
}
JSP 页面的转发 和 重定向
@RequestMapping("/restful/{id}/{name}")
public String restfulWay(Integer id, String name){
System.out.println(id + " " + name);
// 返回 视图
return "redirect:/index.jsp";
}
或
return "forward:/index.jsp";
Spring MVC 数据绑定
required = true
表示这个请求参数是必须的,也就是说,如果客户端的请求中没有包含这个参数,Spring MVC 会抛出异常(通常是 MissingServletRequestParameterException
),并返回一个错误响应。
@RequestMapping("/baseType")
@ResponseBody
public String baseType(int id){
return "id:"+id;
}
@RequestMapping("/baseType")
@ResponseBody
public String packageType(@RequestParam(value="id", required = true, defaultValue = "0") int id){
return "id:"+id;
}
数组
@RequestMapping("/arrayType")
@ResponseBody
public String arrayType(String[] names){
StringBuffer s = new StringBuffer();
for(String str:names){
s.append(str).append(" ");
}
return "names:"+s.toString();
}
POJO
package com.xs.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<form action="hello/test" method="post">
<table>
<tr>
<td>编号:</td>
<td>
<input type="text" name="id"/>
</td>
</tr>
<tr>
<td>姓名:</td>
<td>
<input type="text" name="name"/>
</td>
</tr>
<tr>
<td>
<input type="submit" value="提交"/>
</td>
</tr>
</table>
</form>
</head>
<body>
</body>
</html>
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(User user){
System.out.println(user);
// 返回 视图
return "index";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public String add(User user){
return user.toString()
}
List
@Controller
public class StudentController {
@RequestMapping("/getStudents")
public String getStudents(HttpServletRequest request) {
// 创建一个学生的列表
List<Student> students = new ArrayList<>();
students.add(new Student(1, "Alice"));
students.add(new Student(2, "Bob"));
students.add(new Student(3, "Charlie"));
// 将学生列表设置为请求属性,传递给 JSP
request.setAttribute("students", students);
// 返回视图名 (例如 students.jsp)
return "students";
}
}
@RequestMapping(value = "/listType", method = RequestMethod.POST)
@ResponseBody
public String listType(UserList userList){
StringBuffer stri = new StringBuffer();
for(User u:userList.getUsers()){
stri.append(u);
}
return "用户" + stri.toString();
}
package com.xs.entity;
import lombok.Data;
import java.util.List;
@Data
public class UserList {
private List<User> users;
}
package com.xs.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="hello/listType" method="post">
用户1 ID: <input type="text" name="users[0].id"/><br/>
用户1 Name: <input type="text" name="users[0].name"/><br/>
用户2 ID: <input type="text" name="users[1].id"/><br/>
用户2 Name: <input type="text" name="users[1].name"/><br/>
用户3 ID: <input type="text" name="users[2].id"/><br/>
用户3 Name: <input type="text" name="users[2].name"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
List.of
创建的列表是不可变的,这意味着一旦创建,就无法添加、删除或更改其元素。
List<String> immutableList = List.of("apple", "banana", "cherry");