创建maven web工程,引入依赖
<!-- 版本锁定 -->
<properties>
<spring.version>5.0.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
在wweb.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">
<display-name>Archetype Created Web Application</display-name>
<!--配置前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置springMVC的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 让前端控制器是最先执行的servlet-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</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的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 开启注解扫描,Controller,异常处理,拦截器所在的包-->
<context:component-scan base-package="cn.hao"/>
<!-- 视图解析器对象 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--告诉前端控制器,哪些资源不拦截-->
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/images/**" location="/images/"/>
<!--配置异常处理器-->
<bean class="cn.hao.exception.SysExceptionResolver" id="sysExceptionResolver"></bean>
<!--配置多级拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<!--要拦截的具体的方法-->
<mvc:mapping path="/user/*"/>
<bean id="myInterceptor" class="cn.hao.Interceptor.MyInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<!--要拦截的具体的方法-->
<mvc:mapping path="/user/*"/>
<bean id="myInterceptor2" class="cn.hao.Interceptor.MyInterceptor2"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!-- 开启SpringMVC框架注解的支持 -->
<mvc:annotation-driven />
</beans>
编写index.jsp和HelloController
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>入门程序</h3>
<a href="/user/testString">testString</a>
<br>
<a href="/user/testVoid">testVoid</a>
<br>
<a href="/user/testModelAndView">testModelAndView</a>
<br>
<a href="/user/testException">testException</a>
<br>
<h3>拦截器</h3>
<a href="/user/testInterceptor">testInterceptor</a>
</body>
</html>
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testString")
public String testString(Model model) {
System.out.println("testString方法执行了");
//模拟从数据库查出来用户
User user = new User();
user.setUsername("小明");
user.setPassword("1234");
user.setAge(19);
//存到model对象
model.addAttribute("user", user);
return "success";
}
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("testVoid方法执行了");
// request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
// response.sendRedirect(request.getContextPath()+"/index2.jsp");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("<h1 >你好<h1>");
return;
}
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView() {
System.out.println("testModelAndView方法执行了");
ModelAndView mv = new ModelAndView();
User user = new User();
user.setUsername("小丑");
user.setPassword("1234");
user.setAge(19);
mv.addObject("user", user);
mv.setViewName("success");
return mv;
}
@RequestMapping("/testAjax")
public @ResponseBody User testAjax(@RequestBody User user) {
System.out.println("testAjax方法执行了");
System.out.println(user);
//响应,模拟查询数据库
user.setUsername("Rose");
user.setAge(33);
return user;
}
@RequestMapping("/fileUpload1")
public String fileUpload1(HttpServletRequest request) throws Exception {
System.out.println("fileUpload1方法执行了");
String path = request.getSession().getServletContext().getRealPath("/uploads/");
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> fileItems = upload.parseRequest(request);
for (FileItem item : fileItems) {
if (item.isFormField()) {
//普通
} else {
//文件
String name = item.getName();
String s = UUID.randomUUID().toString().replace("-", "");
name = s + name;
item.write(new File(path, name));
item.delete();
}
}
return "success";
}
@RequestMapping("/fileUpload2")
public String fileUpload2(HttpServletRequest request, MultipartFile upload) throws Exception {
System.out.println("fileUpload2方法执行了");
String path = request.getSession().getServletContext().getRealPath("/uploads/");
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
String name = upload.getOriginalFilename();
String s = UUID.randomUUID().toString().replace("-", "");
name = s + name;
upload.transferTo(new File(path, name));
return "success";
}
@RequestMapping("/fileUpload3")
public String fileUpload3(MultipartFile upload) throws Exception {
System.out.println("fileUpload3方法执行了");
//定义上传服务器的路径
String path = "http://localhost:8081/uploads/";
String name = upload.getOriginalFilename();
String s = UUID.randomUUID().toString().replace("-", "");
name = s + name;
//跨服务器上传
//创建客户端对象
Client client = Client.create();
//和服务器连接
WebResource resource = client.resource(path + name);
//上传
resource.put(upload.getBytes());
return "success";
}
@RequestMapping("/testException")
public String testException() throws SysException {
System.out.println("testException方法执行了");
try {
int a = 10 / 0;
} catch (Exception e) {
e.printStackTrace();
throw new SysException("查询所有用户出现错误");
}
return "success";
}
@RequestMapping("/testInterceptor")
public String testInterceptor() {
System.out.println("testInterceptor方法执行了");
return "success";
}
}
在WEB-INF目录下创建pages文件夹,编写success.jsp的成功页面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>执行成功</h3>
${user.username}
${user.password}
${user.age}
<% System.out.println("success.jsp执行了"); %>
</body>
</html>
启动Tomcat服务器,进行测试
项目结构