spring-mvc的学习笔记
spring—mvc框架
导入依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.SpringMvc</groupId>
<artifactId>SpringMvc</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringMvc Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!-- spring操作数据库还需要使用spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>10.0.27</version>
</dependency>
<!--jsp的依赖-->
<dependency>
<groupId>jakarta.servlet.jsp</groupId>
<artifactId>jakarta.servlet.jsp-api</artifactId>
<version>3.0.0</version>
<scope>provided</scope>
</dependency>
<!--jar包的依赖-->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>5.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMvc</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
web.xml的配置
<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"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<!-- 配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.springmvc.web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/userServlet</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>
<!--配置spring的前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
版本适配的原因 , 因为tomcat10以上需要换jar包,导致向下不兼容,所以访问不到服务器
下载tomcat 8
https://tomcat.apache.org/download-80.cgi#8.5.86
解决tomcat8中无法导入jar包的方法
全局配置
监听器
package com.springmvc.listener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextLoaderListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext = sce.getServletContext();
//读取web.xml的全局参数
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
// ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
servletContext.setAttribute("app",app);
System.out.println("spring容器创建完毕");
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
监听器的工具类
package com.springmvc.listener;
import org.springframework.context.ApplicationContext;
import javax.servlet.ServletContext;
public class WebApplicationContextUtils {
public static ApplicationContext getWebApplicationContext(ServletContext servletContext){
return (ApplicationContext) servletContext.getAttribute("app");
}
}
实现类
package com.springmvc.web;
import com.springmvc.service.UserService;
import org.springframework.context.ApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UserServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
UserService userService = app.getBean(UserService.class);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
spring-mvc.xml
<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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--controller组件扫描-->
<context:component-scan base-package="com.springmvc.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--mvc的注解驱动-->
<mvc:annotation-driven conversion-service="conversionService"/>
<!--开放访问权限-->
<!-- <mvc:resources mapping="/js/**" location="/js/"/>-->
<!-- <mvc:resources mapping="/img/**" location="/img/"/>-->
<mvc:default-servlet-handler/>
<!--声明转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.springmvc.converter.DateConverter"/>
</list>
</property>
</bean>
<!--配置文件上传解析器-->
<!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">-->
<!-- <!–上传文件总大小–>-->
<!-- <property name="maxUploadSize" value="5242800"/>-->
<!-- <!–上传单个文件的大小 –>-->
<!-- <property name="maxUploadSizePerFile" value="5242800"/>-->
<!-- <!–上传文件的编码类型–>-->
<!-- <property name="defaultEncoding" value="UYF-8"/>-->
<!-- </bean>-->
<!--配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSizePerFile" value="500000"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="500000"/>
</bean>
</beans>
内部资源处理
配置内部资源视图解析器
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--/jsp/success.jsp-->
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置处理器的映射器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>
用spring设置数据源
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=false&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="13140284966wr"/>
</bean>
控制层
有多种spring mvc操作 的方法
package com.springmvc.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springmvc.domain.User;
import com.springmvc.domain.VO;
import lombok.Data;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@Controller
@RequestMapping(value = "/rsama")
public class UserController {
//本机地址 http://localhost:8080/rsama/quick2
@RequestMapping(value = "/quick2")
public ModelAndView save2(){
/*
Model 模型 作用为封装数据
View 作用为展示数据
*/
ModelAndView modelAndView = new ModelAndView();
//设置模型数据
modelAndView.addObject("username","springmvc");
//设置视图名称
modelAndView.setViewName("/success.jsp");
return modelAndView;
}
@RequestMapping(value = "/quick3")
public ModelAndView save3(ModelAndView modelAndView){
//设置模型数据
modelAndView.addObject("username","sharuan");
//设置视图名称
modelAndView.setViewName("/success.jsp");
return modelAndView;
}
@RequestMapping(value = "/quick4")
public String save4(Model model){
model.addAttribute("username" ,"lalalal");
return "/success.jsp";
}
@RequestMapping(value = "/quick5")
public String save5(HttpServletRequest request){
return "/success.jsp";
}
@RequestMapping(value = "/quick6")
public void save6(HttpServletResponse response) throws IOException {
response.getWriter().print("hello springmvc");
}
@RequestMapping(value = "/quick7")
@ResponseBody //直接进行数据返回
public String save7() throws IOException {
return "hello spring mvc";
}
@RequestMapping(value = "/quick8")
@ResponseBody
public String save8() throws IOException {
return "{\"username\":\"zhansan\",\"age\":18}";
}
@RequestMapping(value = "/quick9")
@ResponseBody
public String save9() throws IOException {
User user = new User();
user.setUsername("lisi");
user.setAge(30);
//json的转换工具将对象转换json格式的字符串返回
ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(user);
return s;
}
//期望springmvc自动把user对象转换成json字符串
@RequestMapping(value = "/quick10")
@ResponseBody
public User save10() throws IOException {
User user = new User();
user.setUsername("lisi");
user.setAge(30);
return user;
}
@RequestMapping(value = "/quick11")
@ResponseBody
public void save11(String username , int age) throws IOException {
System.out.println(username);
System.out.println(age);
}
@RequestMapping(value = "/quick12")
@ResponseBody
public void save12(User user) throws IOException {
System.out.println(user);
}
@RequestMapping(value = "/quick13")
@ResponseBody
public void save13(String[] strs) throws IOException {
System.out.println(Arrays.asList(strs));
}
@RequestMapping(value = "/quick14")
@ResponseBody
public void save14(VO vo) throws IOException {
System.out.println(vo);
}
@RequestMapping(value = "/quick15")
@ResponseBody
public void save15(@RequestBody List<User> userList) throws IOException {
System.out.println(userList);
}
@RequestMapping(value = "/quick16")
@ResponseBody
public void save16( @RequestParam(value = "name",required = false , defaultValue = "sadas") String username ) throws IOException {
System.out.println(username);
}
@RequestMapping(value = "/quick17/{username}")
@ResponseBody
public void save17( @PathVariable("username") String username ) throws IOException {
System.out.println(username);
}
@RequestMapping(value = "/quick18")
@ResponseBody
public void save18(Date date) throws IOException {
System.out.println(date);
}
@RequestMapping(value = "/quick19")
@ResponseBody
public void save19(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
System.out.println(response);
System.out.println(request);
System.out.println(session);
}
@RequestMapping(value = "/quick20")
@ResponseBody
public void save20(@RequestHeader(value = "User-Agent") String user_agent) throws IOException {
System.out.println(user_agent);
}
@RequestMapping(value = "/quick21")
@ResponseBody
public void save21(@CookieValue(value = "JSESSIONID") String jsessionId) throws IOException {
System.out.println(jsessionId);
}
@RequestMapping(value="/quick22")
@ResponseBody
public void save22(String username, MultipartFile uploadFile) throws IOException {
//获得文件名称
String originalFilename = uploadFile.getOriginalFilename();
//System.out.println(username);
//System.out.println(uploadFile);
System.out.println(username);
uploadFile.transferTo(new File("C:\\upload\\"+originalFilename));
}
//本机地址 http://localhost:8080/rsama/quick
@RequestMapping(value = "/quick",method = RequestMethod.GET , params = {"username"})
public String save(){
System.out.println("Controller save running");
return "redireat:/jsp/success.jsp";
}
}
类型转换器
Date对象
package com.springmvc.converter;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String s) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(s);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}