1.地址后面拼接参数及显示到jsp页面
package com.twy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.twy.pojo.User;
@Controller
public class HelloController {
// http://127.0.0.1:8080/springmvc_demo1/reg.action?name=hello&id=3
@RequestMapping("/reg")
public ModelAndView reg(String name, Integer id) {
System.out.println(name);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("result");
modelAndView.addObject("name", name);
modelAndView.addObject("id", id);
return modelAndView;
}
}
2.post提交javabean 及jsp显示提交的javabean数据
3.响应json字符串数据
加入json jar包
配置spring配置文件
编写控制器
package com.twy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.twy.pojo.User;
@Controller
public class HelloController {
// http://127.0.0.1:8080/springmvc_demo1/testJson.action
@RequestMapping("/testJson")
@ResponseBody
public User testJson() {
User user = new User();
user.setUid(2);
user.setUname("涂文远");
user.setAge(35);
return user;
}
}
结果:
4.从URL上获取参数 RESTFul风格
package com.twy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.twy.pojo.User;
@Controller
public class HelloController {
//传统方式:http://127.0.0.1:8080/springmvc_demo2/findUser.action?userId=42
//rest方式:http://127.0.0.1:8080/springmvc_demo2/findUser/42.action
@RequestMapping("/findUser/{id}")
@ResponseBody
public User queryUserById(@PathVariable("id") Integer userId) {
// 业务 根据id去查找用户
User user = new User();
user.setUid(userId);
user.setUname("涂文远");
user.setAge(35);
return user;
}
}
5. 请求json ,响应json
WebContent/add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
</head>
<body>
<input type="button" value="submitAdd" onclick="addUser()" />
<script>
var addUser = function() {
var user = {
uid : 1,
uname : "test",
age : 28
};
$.ajax({
type : "POST",
data : JSON.stringify(user),
url : "add.action",
contentType : "application/json",
dataType:"json",
success:function(data){
alert(data.uid+","+data.uname+","+data.age);
}
});
}
</script>
</body>
</html>
HelloContorller.java
package com.twy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.twy.pojo.User;
@Controller
public class HelloController {
@RequestMapping("/add")
@ResponseBody
public User add(@RequestBody User user) {
System.out.println(user.getUname() + ":" + user.getUid() + ":" + user.getAge());
return user;
}
}
6.上传文件
所需jar包
src/config/spring-mvc.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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--Spring注解扫描 -->
<context:component-scan
base-package="com.twy.controller"></context:component-scan>
<!-- 默认使用:RequestMappingHandlerMapping, RequestMappingHandlerAdapter:组件 -->
<mvc:annotation-driven></mvc:annotation-driven>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 /WEB-INF/jsp/hello.jsp -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 文件上传,id必须设置为multipartResolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置文件上传大小 -->
<property name="maxUploadSize" value="5000000" />
</bean>
</beans>
src/com/twy/controller/FileController.java
package com.twy.controller;
import java.io.File;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping("/file")
public class FileController {
@RequestMapping("/upload")
public String upload(MultipartFile myFile) throws IllegalStateException, IOException {
System.out.println("ssssssssssssssssss");
// 将上传的文件保存到服务器目录中
File target = new File("d:\\uploadFile\\" + myFile.getOriginalFilename());
myFile.transferTo(target);
return "success";
}
}
WebContent/fileupload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="file/upload.action" enctype="multipart/form-data" method="post">
文件: <input type="file" name="myFile"/><br>
<input type="submit" value="上传"/>
</form>
</body>
</html>
WebContent/WEB-INF/jsp/success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>上传成功</title>
</head>
<body>
上传成功!!!!!
</body>
</html>
7.拦截器
src/com/twy/interceptor/MyInterceptor.java
package com.twy.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyInterceptor implements HandlerInterceptor {
/**
* Controller调用已经结束了,而且视图也返回了 日志记录,异常的处理
*/
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
System.out.println("afterCompletion");
}
/**
* 在Controller调用之后执行 可以对返回的数据进行进一步的处理
*/
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
System.out.println("postHandle");
}
/**
* 在Controller调用之前执行,如果这个方法返回true,表明可以调用Controller,否则的话会直接返回
* 用来一些全局的控制,用户登录验证,权限拦截等
*/
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object arg2) throws Exception {
// TODO Auto-generated method stub
System.out.println("preHandle");
return true;
}
}
springmvc配置拦截器
<?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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--Spring注解扫描 -->
<context:component-scan
base-package="com.twy"></context:component-scan>
<!-- 默认使用:RequestMappingHandlerMapping, RequestMappingHandlerAdapter:组件 -->
<mvc:annotation-driven></mvc:annotation-driven>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 /WEB-INF/jsp/hello.jsp -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 文件上传,id必须设置为multipartResolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置文件上传大小 -->
<property name="maxUploadSize" value="5000000" />
</bean>
<!--配置拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 所有请求都进入拦截器 -->
<mvc:mapping path="/**" />
<!-- 配置具体的拦截器 -->
<bean class="com.twy.interceptor.MyInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>
执行结果
8.异常处理器
自定义异常类
MyException.java
package com.twy.exception;
public class MyException extends Exception {
public MyException() {
}
public MyException(String msg) {
super(msg);
}
}
自定义异常处理器
package com.twy.exception;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
public class MyExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
Exception arg3) {
String msg;
if (arg3 instanceof MyException) {
msg = arg3.getMessage();
} else {
Writer out = new StringWriter();
PrintWriter s = new PrintWriter(out);
arg3.printStackTrace(s);
msg = out.toString();
}
// 可以发送邮件等一些方式做通知
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg", msg);
modelAndView.setViewName("error");
return modelAndView;
}
}
异常处理配置 (在springmvc.xml中添加)
<!-- 配置全局异常处理器 -->
<bean id="customHandleException" class="com.twy.exception.MyExceptionResolver"></bean>
错误页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
系统出错了:${msg }
</body>
</html>
模拟异常测试
package com.twy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.twy.exception.MyException;
@Controller
public class HelloController {
// http://127.0.0.1:8080/springmvc_demo1/hello.action
@RequestMapping("/hello")
public String hello() throws MyException {
int i = 10;
if (i == 10) {
throw new MyException("除数不能为0");
}
int j = i / 0;
return "hello";
}
}
效果