国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

SpringMVC學(xué)習(xí)筆記(二)

2019-11-08 02:45:02
字體:
供稿:網(wǎng)友

SPRingMVC學(xué)習(xí)筆記(二)

綜合示例,文件上傳,自定義攔截器,json交互

個(gè)人筆記,如有錯(cuò)誤,懇請(qǐng)批評(píng)指正。

綜合示例(springmvc文件上傳)

multipartResolver使用

spring-mvc.xml文件添加如下內(nèi)容:

<!--文件上傳使用, 配置multipartResolver,id名為約定好的 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 配置文件(每次上傳的所有文件總大小)大小,單位為b, 1024000表示1000kb --> <property name="maxUploadSize" value="1024000" /> </bean>

中文亂碼處理

web.xml文件添加如下內(nèi)容:

<filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-v alue>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

如果上邊的方式設(shè)置后,仍然有亂碼,請(qǐng)嘗試修改tomcat安裝目錄下的apache-tomcat安裝目錄/conf/server.xml文件,修改Connector元素內(nèi)容,添加URIEncoding=”UTF-8” ,修改后內(nèi)容 如下:

<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8"/>

properties文件信息注入

PropertiesFactoryBean:用來注入properties類型的配置文件信息

<!--PropertiesFactoryBean對(duì)properties文件可用 ,可以用來注入properties配置文件的信息 --> <bean id="uploadProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="location" value="classpath:xxxxx.properties"></property> </bean>

文件上傳示例

導(dǎo)入包

繼續(xù)使用上一章節(jié)代碼,并導(dǎo)入文件上傳需要的jar包:commons-fileupload-1.2.2.jar, commons-io-2.0.1.jar

修改student實(shí)體類,添加文件類型屬性
public class Student implements Serializable { private static final long serialVersionUID = -5304386891883937131L; private Integer stuId; private String stuName; private String stuPwd; private Integer stuAge; private MultipartFile[] files; ......}
編寫上傳頁(yè)面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><html> <head> <title>My jsp 'index.jsp' starting page</title> </head> <body> <form action="student/save.action" method="post" enctype="multipart/form-data"> 姓名:<input type="text" name="stuName"><br/> 密碼<input type="passWord" name="stuPwd"><br> 請(qǐng)選擇文件:<br/><input type="file" name="files"><br/> <input type="file" name="files"><br/> <input type="submit" value="文件上傳測(cè)試"> </form> </body></html>
編寫控制器

StudentAction.java

@Controller@RequestMapping("/student")public class StudentAction { public StudentAction(){ System.out.println("---StudentAction構(gòu)造方法被調(diào)用---"); } @RequestMapping("/save") public String save(Student student) { System.out.println("save方法已注入student對(duì)象:"+student); MultipartFile[] files=student.getFiles(); for(MultipartFile file:files){ if(file.isEmpty()){ System.out.println("文件為空"); }else{ System.out.println("文件不為空!"); System.out.println("格式:" + file.getContentType()); System.out.println("原名:" + file.getOriginalFilename()); System.out.println("大小:" + file.getSize()); System.out.println("表單控件的名稱" + file.getName()); try { FileUtils.copyInputStreamToFile(file.getInputStream(), new File("e:/testupload/"+file.getOriginalFilename())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } System.out.println("---調(diào)用業(yè)務(wù)邏輯進(jìn)行業(yè)務(wù)處理---"); //直接使用字符串,返回視圖,進(jìn)行結(jié)果展現(xiàn)等 return "forward:/jsp/main.jsp"; }}
修改配置文件

添加文件處理器CommonsMultipartResolver配置

<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd "> <mvc:annotation-driven></mvc:annotation-driven> <context:component-scan base-package="*"/> <!--文件上傳使用, 配置multipartResolver,id名稱為約定好的 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 配置文件(每次上傳的所有文件總大小)大小,單位為b, 1024000表示1000kb --> <property name="maxUploadSize" value="1024000" /> </bean></beans>
編寫處理完后跳轉(zhuǎn)的頁(yè)面

main.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><html> <head> <title>main.jsp</title> </head> <body> /jsp/main.jsp頁(yè)面 student: ${requestScope.student} </body></html>
文件存放于tomcat目錄下處理方式

? 在項(xiàng)目目錄下新建upload文件夾

? 修改StudentAction.java。

@Controller@RequestMapping("/student")public class StudentAction { public StudentAction(){ System.out.println("---StudentAction構(gòu)造方法被調(diào)用---"); } @Resource ServletContext application; @RequestMapping("/save") public String save(Student student) { System.out.println("save方法已注入student對(duì)象:"+student); MultipartFile[] files=student.getFiles(); System.out.println("真實(shí)路徑:"+application.getRealPath("/")); for(MultipartFile file:files){ if(file.isEmpty()){ System.out.println("文件為空"); }else{ System.out.println("文件不為空!"); System.out.println("格式:" + file.getContentType()); System.out.println("原名:" + file.getOriginalFilename()); System.out.println("大小:" + file.getSize()); System.out.println("表單控件的名稱" + file.getName()); try { FileUtils.copyInputStreamToFile(file.getInputStream(), new File(application.getRealPath("/")+"upload/"+file.getOriginalFilename())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } System.out.println("---調(diào)用業(yè)務(wù)邏輯進(jìn)行業(yè)務(wù)處理---"); //直接使用字符串,返回視圖,進(jìn)行結(jié)果展現(xiàn)等 return "forward:/jsp/main.jsp"; }}

其它代碼同上一章節(jié),可以在application.getRealPath(“/”)+”upload/”目錄下查看到文件。

文件上傳優(yōu)化

編寫文件上傳工具類

FileUploadUtil.java

@Component(value="fileUploadUtils") //普通的bean注入public class FileUploadUtils { /* * 注入字符串,#{}為spel語(yǔ)言,其中uploadProperties,是xml配置文件中注入properties文件的bean id, * path為properties文件的其中一個(gè)key ,也可以通過下邊的set方法注入 */ @Value("#{uploadProperties.path}") private String path; //private String path="e:/testupload"; //path也可以通過set方法注入// @Value("#{uploadProperties.path}") // public void setPath(String path) {// this.path = path;// } private String getExtName(MultipartFile file){ return FilenameUtils.getExtension(file.getOriginalFilename()); } private String createNewName(MultipartFile file){ return UUID.randomUUID().toString()+"."+getExtName(file); } public String uploadFile(MultipartFile file){ try { String newName=createNewName(file); FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path,newName )); return newName; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } }}
修改StudentAction.java

主要修改save方法,使用自已的文件上傳工具類進(jìn)行文件上傳。

@Controller@RequestMapping(value="/student")public class StudentAction { @Resource private ServletContext application; @Resource private FileUploadUtils fileUploadUtils; public StudentAction(){ System.out.println("---StudentAction構(gòu)造方法被調(diào)用---"); } @RequestMapping(value="/save") public String save(Student student,Map<String, Student> paramMap) { System.out.println("save方法已注入student對(duì)象:"+student); MultipartFile[] files=student.getFiles(); for(MultipartFile file:files){ if(file.isEmpty()){ System.out.println("文件為空"); }else{ System.out.println("文件不為空!"); fileUploadUtils.uploadFile(file); } } System.out.println("---調(diào)用業(yè)務(wù)邏輯進(jìn)行業(yè)務(wù)處理---"); paramMap.put("student",student); //直接使用字符串,返回視圖,進(jìn)行結(jié)果展現(xiàn)等 return "forward:/jsp/main.jsp"; }}
添加upload.properties文件

配置文件上傳后的存放目錄

path=e/://testdir//upload//
修改spring-mvc.xml配置文件

注入配置文件的信息

<!--PropertiesFactoryBean對(duì)properties文件可用 ,可以用來注入properties配置文件的信息 --> <bean id="uploadProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="location" value="classpath:upload.properties"></property> </bean>

綜合示例(登陸)

攔截器使用

編寫攔截器類

LoginInterceptor.java,需要實(shí)現(xiàn)HandlerInterceptor接口

public class LoginInterceptor implements HandlerInterceptor { @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // TODO Auto-generated method stub System.out.println("---訪問請(qǐng)求資源后不管理有沒有異常都一定執(zhí)行此方法---"); } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO Auto-generated method stub System.out.println("---訪問請(qǐng)求資源后,如果沒有異常,將執(zhí)行此方法---"); } @Override public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { // TODO Auto-generated method stub System.out.println("---訪問請(qǐng)求資源前執(zhí)行,如果此方法返回false,將不能訪問請(qǐng)求資源---"); return true; }}
配置文件中添加攔截器
<!-- 配置spring mvc攔截器 --> <mvc:interceptors> <!-- 默認(rèn)攔截DispatcherServlet指定的后綴(這里是.action) --> <bean class="cn.itcast.interceptor.LoginInterceptor"/> </mvc:interceptors>

登陸示例

編寫及配置攔截器

添加攔截器類及攔截器配置信息,如上面。

修改攔截器類preHandle方法
@Override public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { // TODO Auto-generated method stub System.out.println("---訪問請(qǐng)求資源前執(zhí)行,如果此方法返回false,將不能訪問請(qǐng)求資源---"); if(arg0.getsession().getAttribute("user")==null){ arg1.sendRedirect(arg0.getContextPath()+"/login.jsp"); return false; } return true; }
編寫登陸頁(yè)面

login.jsp,本頁(yè)面已模仿了登陸

<%@page import="cn.itcast.entity.Student"%><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><html> <head> <title>My JSP 'index.jsp' starting page</title> </head> <body> <% session.setAttribute("user", new Student(1001,"zcf","admin",20)); %> <!-- 這里正常應(yīng)該跳到action再到頁(yè)面 ,為了演示,這里簡(jiǎn)略--> <a href="index.jsp">已登陸,返回首頁(yè)</a> </body></html>

json交互

使用上面的源碼,暫時(shí)去掉攔截器的登陸權(quán)限處理

導(dǎo)入json包及jquery的js文件

修改action文件

@Controller@RequestMapping(value="/student")public class StudentAction { public StudentAction(){ System.out.println("---StudentAction構(gòu)造方法被調(diào)用---"); } @RequestMapping("/doAjax") @ResponseBody //如果返回json格式,需要這個(gè)注解 public Object doAjax(Student student){ System.out.println("---doAjax.student:"+student); student.setStuName("1001name"); return student; }}

修改訪問頁(yè)面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML><html><head><% pageContext .setAttribute("basePath", request.getContextPath() + "/");%><title></title></head><script type="text/Javascript" src="${basePath }js/jquery/jquery-1.3.js"></script><script type="text/javascript"> $(function() { $("#login").click(function() { $.ajax({ url : "student/doAjax.action", type : "post", dataType : "json", data : { "stuName" : "sss", "stuPwd" : "sss" }, success : function(ajax) { alert(ajax.stuName + ajax.stuPwd); } }); }); }); $( function(){ $("#bt1").click( function(){ $.post( "student/doAjax.action", {stuName:"name1001",stuPwd:"pwd1001"}, function(json){alert(json.stuName+"||"+json.stuPwd);}, "json" ); } ); } );</script><body> <button id="login">testajax</button> <button id="bt1">testajax</button></body></html>
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 富裕县| 德清县| 镇原县| 新和县| 沙雅县| 青川县| 苍山县| 青浦区| 铜陵市| 垣曲县| 蒙自县| 会昌县| 牟定县| 江孜县| 桃园市| 永安市| 佳木斯市| 子洲县| 阳山县| 二连浩特市| 张家界市| 简阳市| 伊吾县| 开鲁县| 台州市| 同心县| 古交市| 巩义市| 易门县| 怀安县| 柳林县| 库伦旗| 关岭| 崇文区| 镇安县| 大悟县| 弥勒县| 朝阳县| 唐河县| 得荣县| 洞口县|