spring_mvc配置javascript
所需jar包:html
commons-logging-1.1.3.jarjava
spring-aop-4.1.6.RELEASE.jarjquery
spring-beans-4.1.6.RELEASE.jarweb
spring-context-4.1.6.RELEASE.jarajax
spring-context-support-4.1.6.RELEASE.jarspring
spring-core-4.1.6.RELEASE.jarexpress
spring-expression-4.1.6.RELEASE.jarjson
spring-web-4.1.6.RELEASE.jarapi
spring-webmvc-4.1.6.RELEASE.jar
web.xml(myeclise path:/projectname/WebRoot/WEB-INF/web.xml)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <!-- 配置spring_mvc --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--改變springmvc配置文件默認位置--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:mvc.xml</param-value> </init-param> <!-- 加載順序,數值越大越日後 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
註解方式:
mvc.xml(默認命名規則爲:默認在WEB-INF下添加[DispatcherServletName]-servlet.xml,servlet中配置contextConfigLocation後可改變其路徑)
<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置渲染器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 結果視圖的前綴 --> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 結果視圖的後綴 --> <property name="suffix" value=".jsp"/> </bean> <!-- 掃描該包下的註解 --> <context:component-scan base-package="com.springmvc.controller"></context:component-scan> </beans>
編寫Controller
package com.springmvc.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class HelloController { @RequestMapping("/hello") public ModelAndView handlerRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception{ ModelAndView mv = new ModelAndView(); mv.addObject("msg", "hello springmvc_annotation!"); mv.setViewName("hello"); return mv; } }
配置文件方式:
<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置HandlerMapping --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean> <!-- 配置HandlerAdapter --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean> <!-- 配置渲染器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 結果視圖的前綴 --> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 結果視圖的後綴 --> <property name="suffix" value=".jsp"/> </bean> <!-- 配置請求和處理器 --> <bean name="/hello.do" class="com.springmvc.controller.HelloController"></bean> </beans>
controller的4種配置方式:
<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 1.該配置方位/hello.do時就會尋找name爲hello.do的bean --> <!-- 配置HandlerMapping <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean> 配置HandlerAdapter <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean> --> <!-- 2.該類配置,訪問/hello.do時,spring會把請求分配helloController進行處理 --> <!-- <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> key對應url請求名,value對應處理器id <prop key="/hello.do">helloController</prop> </props> </property> </bean> 配置請求和處理器 <bean id="helloController" class="com.springmvc.controller.HelloController"></bean> --> <!-- 3.url匹配bean,請求爲hello*.do都將被匹配,根據controller類開頭去匹配 --> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"></bean> <!-- 配置請求和處理器 --> <bean id="helloController" class="com.springmvc.controller.HelloController"></bean> <!-- 4.註解 --> <!-- <context:component-scan base-package="com.springmvc.controller"></context:component-scan> --> <!-- 配置渲染器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 結果視圖的前綴 --> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 結果視圖的後綴 --> <property name="suffix" value=".jsp"/> </bean> </beans>
result的4種跳轉方式:
1. 設置ModelAndView對象。根據View的名稱和視圖解析器跳轉到指定的頁面。
頁面:視圖解析器的前綴+view name+視圖解析器的後綴
<!-- 配置渲染器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 結果視圖的前綴 --> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 結果視圖的後綴 --> <property name="suffix" value=".jsp"/> </bean>
2. 經過ServletAPI對象來實現。該方式不須要配置視圖解析器。
經過HttpServletResponse來進行輸出
@Controller public class HelloController { @RequestMapping("/hello") public void hello(HttpServletResponse resp) throws IOException { resp.getWriter().println("hello springmvc use httpservlet api"); } }
經過HttpServletResponse來重定向
@Controller public class HelloController { @RequestMapping("/hello") public void hello(HttpServletRequest req, HttpServletResponse resp) throws IOException { // 重定向 System.out.println(req.getContextPath()); resp.sendRedirect(req.getContextPath()+"/index.jsp"); } }
經過HttpServletRequest實現轉發
@Controller public class HelloController { @RequestMapping("/hello") public void hello(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // 轉發 req.setAttribute("msg", "servlet api forward"); req.getRequestDispatcher("/index.jsp").forward(req, resp); } }
3.經過springmvc來實現轉發和重定向。——沒有視圖解析器
轉發實現方式1
@Controller public class SpringmvcController { @RequestMapping("/hello1") public String hello() { // 轉發1 return "hello1.jsp"; } }
轉發實現方式2
@Controller public class SpringmvcController { @RequestMapping("/hello1") public String hello() { // 轉發2 System.out.println("轉發2"); return "forward:hello1.jsp"; } }
重定向實現
@Controller public class SpringmvcController { @RequestMapping("/hello1") public String hello() { // 重定向 return "redirect:hello1.jsp"; } }
4. 經過springmvc來實現轉發和重定向。——有視圖解析器
轉發實現
@Controller public class SpringmvcController2 { @RequestMapping("/hello2") public String hello() { // 轉發 return "hello2"; } }
重定向實現
注意:重定向視圖解析無效,因此只能重定向到另外一個請求。
@Controller public class SpringmvcController2 { @RequestMapping("/hello2") public String hello() { // 轉發 //return "hello2"; // 重定向 return "redirect:hello1.do"; } }
文件上傳
所需jar包:
commons-fileupload-1.3.2.jar
commons-io-2.2.jar
1. 配置文件上傳解析器:
<!-- 文件上傳解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property> <!-- 最大文件上傳大小 --> <property name="maxUploadSize" value="104857600"/> <!-- 緩存大小 --> <property name="maxInMemorySize" value="40960"></property> </bean>
2. jsp頁面
<form action="upload.do" method="post" enctype="multipart/form-data"> 文件:<input type="file" name="file" /><input type="submit" value="上傳" /> </form>
3. controller
@Controller public class FileuploadController { @RequestMapping("/upload") public String fileupload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest req) throws IOException { // 獲取文件名 System.out.println(file.getOriginalFilename()); // 獲取上傳文件的路徑 String path = req.getRealPath("/fileupload"); InputStream is = file.getInputStream(); OutputStream os = new FileOutputStream(new File(path, file.getOriginalFilename())); int len = 0; byte[] buffer = new byte[400]; while((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } os.close(); is.close(); return "/index.jsp"; } }
ajax處理
使用HttpServletResponse
controoller
@Controller public class AjaxController { @RequestMapping("/ajax") public void ajax(String name, HttpServletResponse resp) throws IOException { resp.setCharacterEncoding("utf-8"); if("bjsxt".equals(name)) { resp.getWriter().print("用戶名已存在!"); }else { resp.getWriter().print("無人使用,能夠註冊!"); } } }
jsp
<script type="text/javascript" src="js/jquery-3.0.0.min.js"></script> <script type="text/javascript"> $(function() { $("#txtName").blur(function() { $.post("ajax.do", { 'name':$("#txtName").val() }, function(data) { $("#txtSpan").text(data); }); }) }); </script> </head> <body> 用戶名:<input type="text" id="txtName" /> <span id="txtSpan"></span> </body>
json處理
所需jar包:
jackson-annotations-2.5.4.jar
jackson-core-2.5.4.jar
jackson-databind-2.5.4.jar
配置json轉換器
mvc.xml
<!-- 用於將對象轉換爲JSON --> <bean id="messageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="messageConverter"/> <ref bean="jsonConverter"/> </list> </property> </bean>
controller
@Controller public class JsonController { @RequestMapping("/json") @ResponseBody public List<User> json() { List<User> list = new ArrayList<User>(); list.add(new User(1, "張三", "111")); list.add(new User(2, "李四", "222")); list.add(new User(3, "王五", "333")); return list; } }
jsp
<script type="text/javascript"> $(function() { $("#btn").click(function() { $.post("json.do", function(data){ //console.info(data); var html = ""; for(var i=0; i<data.length;i++) { html += "<tr><td>" + data[i].id + "</td><td>"+data[i].name+"</td><td>"+data[i].pwd+"</td></tr>" } $("#content").html(html); }); }); }); </script> </head> <body> <input id="btn" type="button" value="獲取json數據" /> <table width="80%" align="center"> <tr> <td>編號</td> <td>姓名</td> <td>密碼</td> </tr> <tbody id="content"></tbody> </table> </body>
亂碼解決
post亂碼,經過過濾器來解決
<filter> <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping>
get亂碼,則需修改tomcat配置文件解決。