SpringMVC笔记(下)
AJAX
- AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
- AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
- Ajax 不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的Web应用程序的技术
- 当您在谷歌的搜索框输入关键字时,JavaScript 会把这些字符发送到服务器,然后服务器会返回一个搜索建议的列表。
- 通过在后台服务器进行少量的数据交换,就可以实现异步局部更新。
异步刷新可理解为网页的局部刷新,同步指需要按部就班地完成一整套流程,更新整个页面
利用AJAX可以做:
- 注册时,输入用户名自动检测用户是否已经存在。自动检测第二遍输入的密码和第一遍是否相同。
- 登陆时,点击登陆后返回小框框提示密码是否正确。
- 删除数据行时,将行ID发送到后台,后台在数据库中删除,数据库删除成功后,在页面DOM中将数据行也删除。(自动局部刷新
伪造AJAX
-
创建一个新的Module,然后导入web支持,添加lib文件,各种配置等等(如果resources文件没有被自动标记,就手动标记
-
编写一个 ajax-frame.html 使用 iframe 测试
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>ajax-frame</title>
</head>
<body>
<!--script不要自闭和-->
<script type="text/javascript">
function LoadPage(){
//得到下面输入框内的内容
var targetUrl = document.getElementById('url').value;
console.log(targetUrl);
//传给显示框来显示url地址对应的网页
document.getElementById("iframePosition").src = targetUrl;
}
</script>
<div>
<p>请输入要加载的地址:<span id="currentTime"></span></p>
<p>
<!-- 百度好像不能访问-->
<input id="url" type="text" />
<input type="button" value="提交" onclick="LoadPage()">
</p>
</div>
<div>
<h3>加载页面位置:</h3>
<iframe id="iframePosition" style="width: 100%;height: 500px;"></iframe>
</div>
</body>
</html>
- 不用启动tomcat直接在浏览器上面运行这个html
jQuery.ajax
- **Ajax的核心是XMLHttpRequest对象(XHR)。**在这里,纯JS原生实现Ajax我们不去讲解,可以自主了解。
- XHR为向服务器发送请求和解析服务器响应提供了接口。能够以异步方式从服务器获取新数据。(可以打开控制台查看)
- 通过 jQuery AJAX 方法,您能够使用 HTTP Get 和 HTTP Post 从远程服务器上请求文本、HTML、XML 或 JSON – 同时您能够把这些外部数据直接载入网页的被选元素中。
jQuery.ajax(...)
部分参数:
url:请求地址
type:请求方式,GET、POST(1.9.0之后用method)
headers:请求头
data:要发送的数据
contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
async:是否异步
timeout:设置请求超时时间(毫秒)
beforeSend:发送请求前执行的函数(全局)
complete:完成之后执行的回调函数(全局)
success:成功之后执行的回调函数(全局)
error:失败之后执行的回调函数(全局)
accepts:通过请求头发送给服务器,告诉服务器当前客户端课接受的数据类型
dataType:将服务器端返回的数据转换成指定类型
"xml": 将服务器端返回的内容转换成xml格式
"text": 将服务器端返回的内容转换成普通文本格式
"html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
"script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
"json": 将服务器端返回的内容转换成相应的JavaScript对象
"jsonp": JSONP 格式使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数
测试:(各种配置都ok的基础上)
- 编写AjaxController.java 设置请求
//@Controller +@ResponseBody
//这个地方一定要记得改!!!
//不要走视图解析器!!!卡了好久好久!!!
@RestController
public class AjaxController {
@RequestMapping("/r1")
public void test1(String name, HttpServletResponse response) throws IOException {
if ("admin".equals(name)) {
//弹出窗口提示正确
response.getWriter().print("true");
} else {
response.getWriter().print("false");
}
response.getWriter().close();
}
@RequestMapping("/r2")
public void test2(HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().print("你好");
response.getWriter().close();
}
//不知道为什么就是请求不到这个地址!!!
//因为走了视图解析器!!
@RequestMapping("/r3")
public String test3(String name, String pwd) {
String msg = "";
if ("szg".equals(name)) {
if ("123456".equals(pwd)) msg = "ok";
else msg = "密码错误";
} else {
msg = "用户名错误";
}
return msg;
}
}
- 导入jquery ,可以使用在线的CDN , 也可以下载导入
在线的CDN
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
先在官网下载,然后复制到项目web/static/js/中 千万不要复制到WEB-INF下面(
<script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
- 编写index.jsp
失去焦点事件:就是输入框被选中,写完东西之后鼠标移开
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<%-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>--%>
<script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
<script>
function a1(){
// $.post 等价于 ajax.post post方式提交
$.ajax({
url:"${pageContext.request.contextPath}/r1",
data:{'name':$("#txtName").val()},
success:function (data) {
alert(data);
}
});
}
//函数的另一种方式 不用写函数名称
$(function () {
//设置点击事件
$("#butt").click(function () {
//默认get方式提交
$.ajax({
url:"${pageContext.request.contextPath}/r2",
success:function (data){
//两种显示的方法
//在p标签里显示返回的值(前提是body里要有p标签
$("p").html(data);
//在弹出窗口显示返回的值
alert(data);
}
})
})
})
$(function (){
$("#submit").click(function () {
$.ajax({
url:"${pageContext.request.contextPath}/r3",
data:{"name":$("#textName").val(),"pwd":$("#textPwd").val()},
success:function(data){
if(data.toString()=="ok"){
alert("正确!")
}
else alert(data.toString());
}
})
})
})
</script>
</head>
<body>
<%--onblur:失去焦点触发事件运行a1函数--%>
用户名:<input type="text" id="txtName" onblur="a1()"/>
<button id="butt">点我获取数据</button>
<p></p>
正确账号:szg 正确密码:123456
<div>
用户名:<input type="text" id="textName" />
密码:<input type="password" id="textPwd"/>
<button id="submit" >提交</button>
</div>
</body>
</html>
- 在Maven中选中当前的module然后Clean!!然后刷新!!然后配置Tomcat运行
拦截器
(30条消息) Spring 过滤器 拦截器 AOP区别_笃行淡言-CSDN博客_aop和拦截器
概述
SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter【javaweb视频中有讲】,用于对处理器进行预处理和后处理。
过滤器
- servlet规范中的一部分,任何java web工程都可以使用
- 在url-pattern中配置了/*之后,可以对所有要访问的资源进行拦截
拦截器
- 拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
- 拦截器只会拦截访问的控制器方法, 如果访问的是jsp/html/css/image/js是不会进行拦截的
想要自定义拦截器,必须实现 HandlerInterceptor 接口。
测试
- 创建一个新的module,添加web支持然后(web.xml springmvc-servlet.xml 创建lib文件夹并导入 配置Tomcat)
- 在com.song.config编写一个拦截器MyInterceptor
public class MyInterceptor implements HandlerInterceptor {
//在请求处理的方法之前执行(控制器接受前
//返回true就执行下一个拦截器
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("------------处理前------------");
return true;
}
//在请求处理方法执行之后执行
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("------------处理后------------");
}
//在dispatcherServlet处理后执行,做清理工作.
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("------------清理------------");
}
}
- 在springmvc的配置文件中配置拦截器(直接加在后面就行)
<mvc:interceptors>
<mvc:interceptor>
<!--/** 包括路径及其子路径-->
<!--/admin/* 拦截的是/admin/add等等这种 , /admin/add/user不会被拦截-->
<!--/admin/** 拦截的是/admin/下的所有-->
<mvc:mapping path="/**"/>
<!--bean配置的就是拦截器,注册自己写的自定义拦截器-->
<bean class="com.song.config.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
- 在controller包里编写一个Controller文件InterceptorController
@RestController
public class InterceptorController {
@RequestMapping("/interceptor")
public String testFunction() {
System.out.println("执行控制器中的方法");
return "hello";
}
}
- index.jsp 写一个跳转链接
<a href="${pageContext.request.contextPath}/interceptor">拦截器测试</a>
- Tomcat运行
验证用户是否登录 (认证用户)
这集开始弹幕说讲的很乱,然后我就直接看的笔记然后自己写的。。。
思路:
1、有一个登陆页面login.jsp,同时需要写一个controller访问页面。
2、登陆页面有一提交表单的动作。提交的信息需要在controller中处理:判断用户名密码是否正确。如果正确,向session中写入用户信息。返回登陆成功。
3、拦截用户请求,判断用户是否登陆。如果用户已经登陆。放行, 如果用户未登陆,则跳转到登陆页面
(30条消息) getRequestDispatcher()用法介绍_baiping1991的专栏-CSDN博客_getrequestdispatcher
- 首先编写login.jsp(WEB-INF/jsp文件夹下)
<body>
<form action="${pageContext.request.contextPath}/login">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="pwd"><br>
<input type="submit" value="提交">
</form>
<a href="${pageContext.request.contextPath}/index.jsp">返回主界面</a>
</body>
- 编写控制器UserController
@Controller
public class UserController {
//登陆提交
@RequestMapping("/login")
public String login(HttpSession session, String username, String pwd) throws Exception {
// 向session记录用户身份信息
session.setAttribute("user", username);
//判断处理 与数据库进行比对
//跳转到成功界面
return "success";
}
//退出登陆
@RequestMapping("logout")
public String logout(HttpSession session) throws Exception {
// session 手动过期
session.invalidate();
return "login";
}
//跳转到登陆页面
@RequestMapping("/jumplogin")
public String jumpLogin() throws Exception {
return "login";
}
//跳转到成功页面
@RequestMapping("/jumpsuccess")
public String jumpSuccess() throws Exception {
return "success";
}
}
- 在com.szg.config包里编写LoginInterceptor
public class LoginInterceptor implements HandlerInterceptor {
//在请求处理的方法之前执行(控制器接受前
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
// 如果是登陆页面则放行
System.out.println("uri: " + request.getRequestURI());
if (request.getRequestURI().contains("login")) {
return true;
}
// 如果用户已登陆也放行
if(request.getSession().getAttribute("user") != null) {
return true;
}
//response.sendRedirect()是重新定向,前后页面不是一个request。 不能去WEB-INF里的jsp页面。
//request.getRequestDispather();返回的是一个RequestDispatcher对象。
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
// response.sendRedirect("/index.jsp");
// response.sendRedirect("${pageContext.request.contextPath}/jumplogin");
return false;
}
}
- 关于首页index.jsp
<body>
<a href="${pageContext.request.contextPath}/interceptor">拦截器测试</a>
<hr>
<%-- 跳到请求再走视图解析器跳登陆页面 --%>
<a href="${pageContext.request.contextPath}/jumplogin">进入登录界面</a>
<a href="${pageContext.request.contextPath}/jumpsuccess">进入个人中心</a>
</body>
- 编写success.jsp(WEB-INF/jsp文件夹下)
<body>
<h1>登录成功页面</h1>
<hr>
<h2>
${user}成功登录!!
</h2>
<h3>
个人信息。。。。。。
</h3>
<a href="${pageContext.request.contextPath}/index.jsp">返回主界面</a>
<a href="${pageContext.request.contextPath}/logout">注销</a>
</body>
- 记得更改springmvc配置文件里的拦截器的注册bean!!
<bean class="com.song.config.LoginInterceptor"/>
- 配置好Tomcat运行即可,发现不登录或者注销后就进不去个人中心了
文件上传下载
文件上传是项目开发中最常见的功能之一 ,springMVC 可以很好的支持文件上传,但是SpringMVC上下文中默认没有装配MultipartResolver,因此默认情况下其不能处理文件上传工作。如果想使用Spring的文件上传功能,则需要在上下文中配置MultipartResolver。
前端表单要求:为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data。只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器;
有一说一,感觉特别水,底层应该就是IO流吧…建议自己多百度
对表单中的 enctype 属性做个详细的说明: (在下面的index.xml文件中然后
- application/x-www=form-urlencoded:默认方式,只处理表单域中的 value 属性值,采用这种编码方式的表单会将表单域中的值处理成 URL 编码方式。
- multipart/form-data:这种编码方式会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数中,不会对字符编码。
- text/plain:除了把空格转换为 “+” 号外,其他字符都不做编码处理,这种方式适用直接通过表单发送邮件。
测试:
- 首先导入需要的依赖,servlet-api尽量用最新的
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
- 创建一个新的子工程SpringMVC-06-file 然后添加web支持,创建lib文件导入jar包,配置web.xml和SpringMVC配置
- 在springmvc-servlet.xml中添加如下代码
这个bena的id必须为:multipartResolver 否则404
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小上限,单位为字节(10485760=10M) -->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
- 编写前端页面 index.jsp
一旦设置了enctype为multipart/form-data,浏览器即会采用二进制流的方式来处理表单数据,而对于文件上传的处理则涉及在服务器端解析原始的HTTP响应。
<body>
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file"/><br>
<input type="submit" value="upload">
</form>
<hr>
<a href="/download">点击下载</a>
</body>
- 编写控制器FileController
@RestController
public class FileController {
//@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象。CommonsMultipartFile,需要在前面加@RequestParam !!
//MultipartFile 是接口, CommonsMultipartFile 是其实现类
//批量上传CommonsMultipartFile则为数组即可
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
//获取文件名 : file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
//如果文件名为空,直接回到首页!
if ("".equals(uploadFileName)){
return "redirect:/index.jsp";
}
System.out.println("上传文件名 : "+uploadFileName);
//上传路径保存设置 一般只需要改这里!!用户上传的文件保存到哪里
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址:"+realPath);
InputStream is = file.getInputStream(); //文件输入流
OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流
//将文件转化为字符流然后读出后写入 IO操作
int len=0;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return "over!";
}
/*
* 采用file.Transto 来保存上传的文件
*/
@RequestMapping("/upload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//上传文件地址
System.out.println("上传文件保存地址:"+realPath);
//通过 CommonsMultipartFile 的方法 直接写文件(注意这个时候)
//transferTo 保存文件到某路径的专用函数
file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
return "over!";
}
// 下载文件
@RequestMapping(value="/download")
public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{
// 一般情况下只需要改 地址 和 文件名称
// 要下载的图片地址
String path = request.getServletContext().getRealPath("/upload");
String fileName = "1.jpg";
//1、设置response 响应头
response.reset(); //设置页面不缓存,清空buffer
response.setCharacterEncoding("UTF-8"); //字符编码
response.setContentType("multipart/form-data"); //二进制传输数据
//设置响应头
response.setHeader("Content-Disposition",
"attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path,fileName);
//2、 读取文件--输入流
InputStream input=new FileInputStream(file);
//3、 写出文件--输出流
OutputStream out = response.getOutputStream();
byte[] buff =new byte[1024];
int index=0;
//4、执行 写出操作
while((index= input.read(buff))!= -1){
out.write(buff, 0, index);
out.flush();
}
out.close();
input.close();
return null;
}
}
- 配置Tomcat运行结果:首先是检测上传,上传成功在uplo文件夹下。然后检测下载,成功下载。