
🌐Hello World !
Ajax即Asynchronous Javascript And XML(异步JavaScript和XML);Ajax技术网页应用能够快速地将增量更新呈现在用户界面上,不需要重载(刷新)整个页面,使程序能够更快地回应用户的操作
- web.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"> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>encoding</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>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
- applicationContext.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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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"> <!--自动扫描指定的包,下面所有的注解交给IOC容器管理--> <context:component-scan base-package="com.wei.controller"/> <!--静态资源过滤--> <mvc:default-servlet-handler/> <!--配置annotation-driven使:处理器映射器 和 处理器适配器 自动完成实例的注入--> <mvc:annotation-driven/> <!--视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!--前缀--> <property name="prefix" value="/WEB-INF/jsp/"/> <!--后缀--> <property name="suffix" value=".jsp"/> </bean> </beans>
- AjaxController类
package com.wei.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @RestController public class AjaxController { @RequestMapping("/t1") public String test(){ return "hello"; } @RequestMapping("/a1") public void a1(String name, HttpServletResponse response) throws IOException { System.out.println("a1:param=>"+name); if ("weishuo".equals(name)){ response.getWriter().print("True"); }else { response.getWriter().print("False"); } } }
- test.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>iframe测试体验页面无刷新</title> </head> <body> <div> <p>请输入地址:</p> <p> <input type="text" id="url" value="https://www.csdn.net/"> <input type="button" value="提交" onclick="go()"> </p> </div> <div> <iframe id="iframe" style="width: 100%;height: 500px"></iframe> </div> <script> function go(){ var url = document.getElementById("url").value; document.getElementById("iframe").src=url; } </script> </body> </html>
- index.jsp
<%-- Created by IntelliJ IDEA. User: ws199 Date: 2022/12/15 Time: 17:02 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> <script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.2.js"></script> <script> function a() { $.post({ url: "${pageContext.request.contextPath}/a1", data: {"name": $("#username").val()}, success: function (data,status) { console.log("data=" + data); console.log("status=" + status); } }) } </script> </head> <body> <%--失去焦点的时候,发起一个请求到后台--%> 用户名:<input type="text" id="username" οnblur="a()"> </body> </html>启动tomcat测试!打开浏览器的控制台,当我们鼠标离开输入框的时候,可以看到发出了一个ajax的请求
- user类
package com.wei.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private String name; private int age; private String sex; }
- AjaxController类
@RequestMapping("/a2") public List<User> a2(){ List<User> userList = new ArrayList<>(); //添加数据 userList.add(new User("wei_shuo",18,"男")); userList.add(new User("wei",17,"女")); userList.add(new User("shuo",8,"男")); return userList; }
- 前端jsp页面
<%-- Created by IntelliJ IDEA. User: ws199 Date: 2022/12/17 Time: 15:28 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.2.js"></script> <script> $(function () { $("#btn").click(function () { $.post("${pageContext.request.contextPath}/a2", function (data) { console.log(data) var html = ""; for (let i = 0; i < data.length; i++) { html += "<tr>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].age + "</td>" + "<td>" + data[i].sex + "</td>" + "</tr>" } $("#content").html(html); }) }) }); </script> </head> <body> <input type="button" value="加载数据" id="btn"> <table> <tr> <td>姓名</td> <td>年龄</td> <td>性别</td> </tr> <tbody id="content"> <%--数据:后台--%> </tbody> </table> </body> </html>
- AjaxController类
@RequestMapping("/a3") public String a3(String name, String pwd) { String msg = ""; if (name != null) { if ("Admin".equals(name)) { msg = "OK"; } else { msg = "用户名输入错误"; } } if (pwd != null) { if ("123456".equals(pwd)) { msg = "OK"; } else { msg = "密码输入错误"; } } return msg; }
- login.jsp页面
<%-- Created by IntelliJ IDEA. User: ws199 Date: 2022/12/20 Time: 9:01 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.2.js"></script> </head> <body> <p> 用户名:<input type="text" id="name" οnblur="a1()"> <span id="userInfo"></span> </p> <p> 密码:<input type="text" id="pwd" οnblur="a2()"> <span id="pwdInfo"></span> </p> <script> function a1() { $.post({ url: "${pageContext.request.contextPath}/a3", data: {"name": $("#name").val()}, success: function (data) { if (data.toString() === 'OK') { $("#userInfo").css("color", "green"); } else { $("#userInfo").css("color", "red"); } $("#userInfo").html(data); } }) } function a2() { $.post({ url: "${pageContext.request.contextPath}/a3", data: {"pwd": $("#pwd").val()}, success: function (data) { if (data.toString() === 'OK') { $("#pwdInfo").css("color", "green"); } else { $("#pwdInfo").css("color", "red"); } $("#pwdInfo").html(data); } }) } </script> </body> </html>
- AjaxController类
@RequestMapping("/a4") public String a4(String name, String pwd) { String msg = ""; if (name != null && pwd != null) { if ("Admin".equals(name) && "123456".equals(pwd)) { msg = "OK"; } else { msg = "用户名或者密码输入错误"; } } return msg; }
- login.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.2.js"></script> </head> <body> <p> 用户名:<input type="text" id="name" οnblur="Login()"> <span id="UserPwdInfo"></span> </p> <p> 密码:<input type="text" id="pwd" οnblur="Login()"> </p> <script> function Login() { $.post({ url: "${pageContext.request.contextPath}/a4", data: {"name": $("#name").val(),"pwd":$("#pwd").val()}, success: function (data) { if (data.toString() === 'OK') { $("#UserPwdInfo").css("color", "green"); } else { $("#UserPwdInfo").css("color", "red"); } $("#UserPwdInfo").html(data); } }) } </script> </body> </html>
SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。开发者可以自己定义一些拦截器来实现特定的功能
- servlet规范中的一部分,任何java web工程都可以使用
- 在url-pattern中配置了/*之后,可以对所有要访问的资源进行拦截
- 拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
- 拦截器只会拦截访问的控制器方法, 如果访问的是jsp/html/css/image/js是不会进行拦截的
- 拦截器MyInterceptor类
package com.wei.config; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyInterceptor implements HandlerInterceptor { //在请求处理的方法之前执行 // return true 执行下一个拦截器 // return false 不执行下一个拦截器 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("======处理前======"); return true; } //在请求处理方法执行之后执行 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("======处理后======"); } //dispatcherServlet处理后执行,做清理工作 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("======清理======"); } }
- applicationContext.xml拦截器配置
<!--拦截器配置--> <mvc:interceptors> <mvc:interceptor> <!--/** 包括路径及其子路径--> <mvc:mapping path="/**"/> <!--bean配置的就是拦截器--> <bean class="com.wei.config.MyInterceptor"/> </mvc:interceptor> </mvc:interceptors>
- TestController测试
@RestController public class TestController { @GetMapping("t1") public String test(){ System.out.println("TestController==Test"); return "OK"; }
- 结果
======处理前====== TestController==Test ======处理后====== ======清理======
- index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <h1><a href="${pageContext.request.contextPath}/user/goLogin">登录页面</a></h1> <h1><a href="${pageContext.request.contextPath}/user/main">首页</a></h1> </body> </html>
- main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>首页</h1> <span>${username}</span> <p> <a href="${pageContext.request.contextPath}/user/goOut">注销</a> </p> </body> </html>
- login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>登录页面</h1> <form action="${pageContext.request.contextPath}/user/login" method="post"> 用户名:<input type="text" name="username"/> 密码:<input type="text" name="password"/> <input type="submit" value="提交"> </form> </body> </html>
- loginController
package com.wei.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpSession; @Controller @RequestMapping("user") public class loginController { @RequestMapping("main") public String main(){ return "main"; } @RequestMapping("goLogin") public String login(){ return "login"; } @RequestMapping("/login") public String login(HttpSession session, String username, String password, Model model){ session.setAttribute("userLoginInfo",username); model.addAttribute("username",username); return "main"; } @RequestMapping("/goOut") public String goOut(HttpSession session){ //销毁session数据 //session.invalidate(); //移除session数据 session.removeAttribute("userLoginInfo"); return "main"; } }
- 拦截器LoginInterceptor.java
package com.wei.config; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); //判断什么情况,放行 //登录页面,放行 if (request.getRequestURI().contains("goLogin")){ return true; } //第一次登录,没有session,放行 if (request.getRequestURI().contains("login")){ return true; } if (session.getAttribute("userLoginInfo")!=null){ return true; } //判断什么情况,拦截 request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response); return false; } }
- 拦截器配置applicationContext.xml
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/user/**"/> <bean class="com.wei.config.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors>
- pom.xml导入包
<dependencies> <!--文件上传--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <!--servlet-api导入高版本的--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> </dependencies>
- applicationContext.xml
<!--文件上传配置--> <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
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post"> <input type="file" name="file"/> <input type="submit" value="upload"> </form> </body> </html>
- FileController.java
package com.wei.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.*; @RestController public class FileController { //@RequestParam("file") 将name=file控件得到的文件封装成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)); //文件输出流 //读取写出 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 "redirect:/index.jsp"; } /* * 采用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的方法直接写文件(注意这个时候) file.transferTo(new File(realPath +"/"+ file.getOriginalFilename())); return "redirect:/index.jsp"; } }
- FileController.java
@RequestMapping(value="/download") public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{ //要下载的图片地址 String path = request.getServletContext().getRealPath("/upload"); String fileName = "基础语法.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; }
- index.jsp
<a href="/download">点击下载</a>
🌼 结语:创作不易,如果觉得博主的文章赏心悦目,还请——
点赞👍收藏⭐️评论📝

我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A
我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只