入门
导包
配置 web.xml,所有的请求由springMVC管理
<?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>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--
<init-param>
修改默认springmvc加载的配置文件路径
<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>DispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
在 WEB-INF 下创建 DispatcherServlet-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- 配置url处理映射 -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!-- 配置控制器处理适配器 -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
<!-- 配置控制器-相当于配置了访问路径 -->
<bean name="/user.do" class="com.company.web.controller.UserController"/>
<!-- 配置资源视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀 -->
<property name="prefix" value="/WEB-INF/views/"></property>
<!--后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
创建 UserController
package com.company.web.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class UserController implements Controller {
@Override
public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
ModelAndView modelAndView = new ModelAndView("user/userlist");
modelAndView.addObject("name", "tom");
return modelAndView;
}
}
创建接收tom的jsp文件 userlist.jsp
<%--
Created by IntelliJ IDEA.
User: mac
Date: 2019-04-18
Time: 14:06
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${name}
</body>
</html>
目录结构
浏览器输入 http://localhost:8080/springmvc_war_exploded/user.do
url处理映射
方式一
即入门 DispatcherServlet-servlet.xml
方式二
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/user.do">userController</prop>
</props>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
<bean id="userController" class="com.company.web.controller.UserController"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
方式三 --未实现待整理
原因:ControllerClassNameHandlerMapping 未找到
<!-- 不用配置访问路径,默认的访问路径就是类名 userController.do -->
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
<bean id="userController" name="/user.do" class="com.company.web.controller.UserController"/>
<bean class="com.company.web.controller.UserController"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
控制器处理适配器
方式一
即入门 DispatcherServlet-servlet.xml
方式二
package com.company.web.controller;
import org.springframework.web.HttpRequestHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UserControllerHttp implements HttpRequestHandler {
@Override
public void handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
httpServletRequest.setAttribute("name", "tom");
httpServletRequest.getRequestDispatcher("/WEB-INF/views/user/userlist.jsp").forward(httpServletRequest, httpServletResponse);
}
}
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"></bean>
<bean name="/user.do" class="com.company.web.controller.UserControllerHttp"></bean>
注解
配置 DispatcherServlet-servlet.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- 配置扫描包 -->
<context:component-scan base-package="com.company.web.controller"></context:component-scan>
<!-- 配置处理映射 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
<!-- 配置适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>
<!-- 配置资源视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
package com.company.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController1 {
//@RequestMapping("list")
//@RequestMapping("/list")
@RequestMapping(value = "list", method = RequestMethod.GET)
public String list() {
return "user/userlist";
}
}
接收表单参数
方式一
@RequestMapping("add")
public String add(String username, String password) {
return "user/info";
}
<form action="${pageContext.request.contextPath}/user/add.do" method="post">
<input type="text" name="username"><br>
<input type="text" name="password"><br>
<input type="submit" value="提交"><br>
</form>
方式二
@RequestMapping("add")
public String add(User user) {
return "user/info";
}
<form action="${pageContext.request.contextPath}/user/add.do" method="post">
<input type="text" name="username"><br>
<input type="text" name="password"><br>
<input type="submit" value="提交"><br>
</form>
方式三
public class UserExt {
private User user;
private List<User> userList = new ArrayList<>();
private Map<String, Object> infos = new HashMap<>();
@RequestMapping("add")
public String add(UserExt userExt) {
return "user/info";
}
1.模型
<form action="${pageContext.request.contextPath}/user/add.do" method="post">
<input type="text" name="user.username"><br>
<input type="text" name="user.password"><br>
<input type="submit" value="提交"><br>
</form>
2.list
<form action="${pageContext.request.contextPath}/user/add.do" method="post">
<input type="text" name="userList[0].username"><br>
<input type="text" name="userList[0].password"><br>
<hr>
<input type="text" name="userList[1].username"><br>
<input type="text" name="userList[1].password"><br>
<input type="submit" value="提交"><br>
</form>
3.map
<form action="${pageContext.request.contextPath}/user/add.do" method="post">
<input type="text" name="infos['username']"><br>
<input type="text" name="infos['password']"><br>
<input type="submit" value="提交"><br>
</form>
使用Model存储数据
@RequestMapping("list2")
public String list2(Model model) {
List<User> list = new ArrayList<User>();
User user = new User("zhangsan", "123456");
list.add(user);
User user1 = new User("lisi", "123");
list.add(user1);
model.addAttribute("userlist", list);
return "user/userlist";
}
@PathVariable
@RequestMapping("edit/{id}")
public String edit(@PathVariable int id, Model model) {
return "user/userlist";
}
<a href="${pageContext.request.contextPath}/user/edit/${user.id}.do"></a>
转发和重定向
//转发
@RequestMapping("test")
public String test() {
//同一个控制器
//return "forward:list.do";
//不同一个控制器
return "forward:/user/list.do";
}
//重定向
@RequestMapping("test")
public String test() {
//同一个控制器
//return "redirect:list.do";
//不同一个控制器
return "redirect:/user/list.do";
}
@RequestParam
@RequestMapping("test2")
/**
* value:参数名称
* required:默认值
* defaultValue:参数是否必须有值
* */
public String test3(@RequestParam(value = "id", required = true, defaultValue = "30") int id) {
return "user/userlist";
}
@RequestBody 和 @ResponseBody
- @RequestBody 把json数据转成模型数据
- @ResponseBody 返回json对象
导包
配置文件 DispatcherServlet-servlet.xml
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<!-- 配置json转换器,springMVC使用jaskson来转换json -->
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</list>
</property>
</bean>
接收和响应json数据
adduser.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
<script>
function tojson() {
var url = '${pageContext.request.contextPath}/user/save.do';
var username = $('#username').val();
var password = $('#password').val();
var jsonObj = {username: username, password: password};
var parm = JSON.stringify(jsonObj);
$.ajax({
type: 'post',
url: url,
contentType: 'application/json;charset=utf-8',
data: parm,
success: function (respData) {
}
})
}
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/save.do" method="post">
<input type="text" name="username" id="username"><br>
<input type="text" name="password" id="password"><br>
<input type="button" value="json格式数据" onclick="tojson()"><br>
</form>
</body>
</html>
@RequestMapping("save")
public @ResponseBody User save(@RequestBody User user) {
System.out.println(user);
return user;
}
响应json数据
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/save.do" method="post">
<input type="text" name="username" id="username"><br>
<input type="text" name="password" id="password"><br>
<input type="submit" name="提交"><br>
</form>
</body>
</html>
@RequestMapping("save")
public @ResponseBody User save(User user) {
System.out.println(user);
return user;
}
关于多视图错误
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0' defined in ServletContext resource [/WEB-INF/DispatcherServlet-servlet.xml]: Cannot create inner bean 'org.springframework.web.servlet.view.xml.MarshallingView#7675bdb0' of type [org.springframework.web.servlet.view.xml.MarshallingView] while setting bean property 'defaultViews' with key [1]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.view.xml.MarshallingView#7675bdb0' defined in ServletContext resource [/WEB-INF/DispatcherServlet-servlet.xml]: Cannot create inner bean 'org.springframework.oxm.jaxb.Jaxb2Marshaller#618ea1bf' of type [org.springframework.oxm.jaxb.Jaxb2Marshaller] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.oxm.jaxb.Jaxb2Marshaller#618ea1bf': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.oxm.jaxb.Jaxb2Marshaller] from ClassLoader [ParallelWebappClassLoader...
需要导包
springmvc拦截器
配置拦截器 DispatcherServlet-servlet.xml
<mvc:interceptors>
<!-- 配置登录拦截器 -->
<mvc:interceptor>
<!-- /** 拦截所有的请求 -->
<mvc:mapping path="/**"/>
<!-- 不需要拦截的 -->
<!-- <mvc:exclude-mapping path="" -->
<bean class="com.conpany.web.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
LoginInterceptor
package com.company.web.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
//排除不需要拦截路径
System.out.println("客户端访问资源的路径:" + request.getRequestURI());
if (request.getRequestURI().endsWith("login.do")) {
return true;//放行
}
//如果已经登录,也要放行
if (request.getSession().getAttribute("user") != null) {
return true;
}
//进入到login页面
request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("未返回视图前 后处理");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("返回视图前 后处理");
}
}
默认跳转到登录页面
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<jsp:forward page="WEB-INF/views/login.jsp"></jsp:forward>
</body>
</html>