java:Springmvc框架2(Ajax,Json,Interceptor,Upload,Exception)
1.springmvcAjax:
springmvc.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-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注解扫描!!!-->
<context:component-scan base-package="cn.zzsxt"></context:component-scan> <!-- 配置视图解析器 -->
<!-- InternalResourceViewResolver:支持JSP视图解析 -->
<!-- viewClass:JstlView表示JSP模板页面需要使用JSTL标签库,所以classpath中必须包含jstl的相关jar包; -->
<!-- prefix 和suffix:查找视图页面的前缀和后缀,最终视图的址为: -->
<!-- 前缀+逻辑视图名+后缀,逻辑视图名需要在controller中返回ModelAndView指定,比如逻辑视图名为hello,-->
<!-- 则最终返回的jsp视图地址 "WEB-INF/view/hello.jsp" -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean> <!-- 注解映射器
说明 :对类中标记@ResquestMapping的方法进行映射,根据ResquestMapping定义的url匹配
ResquestMapping标记的方法,匹配成功返回HandlerMethod对象给前端控制器,HandlerMethod对象中封装url对应的方法Method
-->
<!--
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
-->
<!-- 注解适配器
说明:注解式处理器适配器,对标记@ResquestMapping的方法进行适配。
-->
<!--
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
-->
<!-- springmvc使用<mvc:annotation-driven> -->
<!-- 自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter, -->
<!-- 可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。 -->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> <!-- 自定义类型转换器 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="cn.zzsxt.converter.CustomDateConverter"></bean>
</list>
</property>
</bean> <!-- 处理静态资源 让静态资源可以直接访问-->
<!--<mvc:resources mapping="/js/**" location="/js/"/> -->
<!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 -->
<mvc:default-servlet-handler/>
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>springmvc01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <!-- 解决post提交乱码问题 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- spring mvc的前端控制器,类似struts2的核心过滤器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 通过contextConfigLocation参数指定配置文件的位置,默认在WEB-INF/查找名称为 [servlet-name]-servlet.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param> <!-- servlet随web容器而启动 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
UserController.java:
package cn.zzsxt.controller; import java.util.HashMap;
import java.util.Map; 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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import cn.zzsxt.model.Userinfo;
import cn.zzsxt.service.UserService;
import cn.zzsxt.service.impl.UserServiceImpl;
import cn.zzsxt.vo.ResultMessage; @Controller
@RequestMapping("/user")
public class UserController {
private UserService userService = new UserServiceImpl(); @RequestMapping(value="login",method=RequestMethod.GET)
public String login(){
return "login";
} @RequestMapping(value="register",method=RequestMethod.GET)
public String register(){
return "register";
}
/**
* @ResponseBody:将java对象转换为json对象
* @RequestBody:将json对象转换为java对象
* @param userName
* @return
*/
@RequestMapping(value="check",method=RequestMethod.GET)
@ResponseBody
public Map<String,Object> check(@RequestBody String userName){
boolean isExist = userService.checkUserName(userName);
Map<String,Object> map = new HashMap<String,Object>();
map.put("isExist", isExist);
return map;
} @RequestMapping(value="register",method=RequestMethod.POST)
@ResponseBody
public ResultMessage register(@RequestBody Userinfo user){ //此处@RequestBody出错的话不加?
boolean success = userService.add(user);
String message=success?"添加成功!":"添加失败!";
ResultMessage rm = new ResultMessage();
rm.setSuccess(success);
rm.setMessage(message);
return rm;
} }
CustomDateConverter.java:
package cn.zzsxt.converter; import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; import org.springframework.core.convert.converter.Converter;
/**
* 自定义类型转换器
* @author Think
*
*/
public class CustomDateConverter implements Converter<String, Date> { @Override
public Date convert(String source) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = sdf.parse(source);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
} }
ResultMessage.java:
package cn.zzsxt.vo; public class ResultMessage {
private boolean success;//是否新增成功
private String message;//操作完成后的提升消息 public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
} }
login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#userName").blur(function(){
var userName = $("#userName").val();
$.get("user/check?userName="+userName,function(data){
if(data.isExist==true){
$("#msg").html("<font color=red>用户名已存在!</font>");
$("#submitBtn").attr("disabled",true);
}else{
$("#msg").html("<font color=green>用户名可用!</font>");
$("#submitBtn").attr("disabled",false);
}
}); });
})
</script>
</head> <body>
<form action="" method="post">
用户名:<input type="text" name="userName" id="userName"/><span id="msg"></span> <br>
密码:<input type="text" name="userPass"/><br>
<input type="submit" value="登录" id="submitBtn">
</form>
</body>
</html>
register.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
//单机注册按钮
$("#submitBtn").click(function(){
//获取表单元素的值
var userName = $("#userName").val();
var userPass = $("#userPass").val();
var address = $("#address").val();
var birthday = $("#birthday").val();
var jsonData = '{"userName":"'+userName+'","userPass":"'+userPass+'","address":"'+address+'","birthday":"'+birthday+'"}';
// alert(jsonData);
$.ajax({
type:"POST",
url:"user/register",
contentType:"application/json",
data:jsonData,
success: function(msg){
// alert( "Data Saved: " + msg );
alert(msg.message);
}
});
});
})
</script>
</head> <body>
<form action="" method="post">
用户名:<input type="text" name="userName" id="userName"/><span id="msg"></span> <br>
密码:<input type="text" name="userPass" id="userPass"/><br>
地址:<input type="text" name="address" id="address"><br>
生日:<input type="text" name="birthday" id="birthday"><br>
<input type="button" value="注册" id="submitBtn">
</form>
</body>
</html>
2.springmvcInterceptor:
springmvc.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-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注解扫描!!!-->
<context:component-scan base-package="cn.zzsxt.controller"></context:component-scan> <!-- 配置视图解析器 -->
<!-- InternalResourceViewResolver:支持JSP视图解析 -->
<!-- viewClass:JstlView表示JSP模板页面需要使用JSTL标签库,所以classpath中必须包含jstl的相关jar包; -->
<!-- prefix 和suffix:查找视图页面的前缀和后缀,最终视图的址为: -->
<!-- 前缀+逻辑视图名+后缀,逻辑视图名需要在controller中返回ModelAndView指定,比如逻辑视图名为hello,-->
<!-- 则最终返回的jsp视图地址 "WEB-INF/view/hello.jsp" -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean> <!-- 注解映射器
说明 :对类中标记@ResquestMapping的方法进行映射,根据ResquestMapping定义的url匹配
ResquestMapping标记的方法,匹配成功返回HandlerMethod对象给前端控制器,HandlerMethod对象中封装url对应的方法Method
-->
<!--
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
-->
<!-- 注解适配器
说明:注解式处理器适配器,对标记@ResquestMapping的方法进行适配。
-->
<!--
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
-->
<!-- springmvc使用<mvc:annotation-driven> -->
<!-- 自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter, -->
<!-- 可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。 -->
<mvc:annotation-driven></mvc:annotation-driven> <!-- 处理静态资源 让静态资源可以直接访问-->
<!--<mvc:resources mapping="/jquery-ui-1.12.1.custom/**" location="/jquery-ui-1.12.1.custom/"/> -->
<!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 -->
<mvc:default-servlet-handler/> <!--配置拦截器, 多个拦截器,顺序执行 -->
<mvc:interceptors> <mvc:interceptor>
<!-- 匹配的是url路径, 如果不配置或/**,将拦截所有的Controller -->
<mvc:mapping path="/**"/>
<bean class="cn.zzsxt.interceptor.MyCustomInterceptor"></bean>
</mvc:interceptor> <!-- 当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandle和afterCompletion方法 -->
<mvc:interceptor>
<!-- 配置拦截的匹配路径 -->
<mvc:mapping path="/**"/>
<!-- 配置放行的匹配路径 -->
<mvc:exclude-mapping path="/user/login"/>
<bean class="cn.zzsxt.interceptor.LoginInterceptor"></bean>
</mvc:interceptor> </mvc:interceptors>
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>springmvc01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <!-- 解决post提交乱码问题 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- spring mvc的前端控制器,类似struts2的核心过滤器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 通过contextConfigLocation参数指定配置文件的位置,默认在WEB-INF/查找名称为 [servlet-name]-servlet.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param> <!-- servlet随web容器而启动 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
TestController.java:
package cn.zzsxt.controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
@RequestMapping("/t")
public class TestController { @RequestMapping("/hello")
public String hello(){
System.out.println("TestController中hello()方法被执行了....");
return "success";
}
}
UserController.java:
package cn.zzsxt.controller; import java.util.ArrayList;
import java.util.List; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import cn.zzsxt.model.Userinfo; @Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value="/login",method=RequestMethod.GET)
public String login(){
return "login";
}
@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(Userinfo user,HttpSession session){
if("admin".equals(user.getUserName())&&"admin".equals(user.getUserPass())){
//将用户信息保持到sesssion中
session.setAttribute("loginUser", user);
return "redirect:/user/list";
}
return "login";
} @RequestMapping(value="/list")
public String list(Model model){
//从数据库中查询用户信息
List<Userinfo> list = new ArrayList<Userinfo>();
for (int i = 1; i <=5; i++) {
Userinfo user = new Userinfo(i,"zhang"+i,"zhang"+i);
list.add(user);
}
model.addAttribute("list", list);
return "list";
} }
LoginInterceptor.java:
package cn.zzsxt.interceptor; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import cn.zzsxt.model.Userinfo; public class LoginInterceptor implements HandlerInterceptor { @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
HttpSession session = request.getSession();//获取session
//从session中获取用户信息
Userinfo user=(Userinfo)session.getAttribute("loginUser");
if(user!=null){
return true;
}else{
response.sendRedirect("login");
return false;
}
} @Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub } @Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub } }
MyCustomInterceptor.java:
package cn.zzsxt.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 MyCustomInterceptor implements HandlerInterceptor {
/**
* 在控制器方法调用前执行
* 返回值为是否中断
* true,表示继续执行(下一个拦截器或处理器)
* false则会中断后续的所有操作,所以我们需要使用response来继续响应后续请求 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
System.out.println("preHandle()方法被执行了.......");
return true;
} /**
* 在控制器方法调用后,解析视图前调用,我们可以对视图和模型做进一步渲染或修改
* 可在modelAndView中加入数据,比如当前时间 */
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView)
throws Exception {
System.out.println("postHandle()方法被执行了....."); }
/**
* 整个请求完成,即视图渲染结束后调用,这个时候可以做些资源清理工作,或日志记录
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception)
throws Exception {
System.out.println("afterCompletion方法被执行了....");
} }
3.springmvcUpload And Exception:
springmvc.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-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注解扫描!!!-->
<context:component-scan base-package="cn.zzsxt.controller"></context:component-scan> <!-- 配置视图解析器 -->
<!-- InternalResourceViewResolver:支持JSP视图解析 -->
<!-- viewClass:JstlView表示JSP模板页面需要使用JSTL标签库,所以classpath中必须包含jstl的相关jar包; -->
<!-- prefix 和suffix:查找视图页面的前缀和后缀,最终视图的址为: -->
<!-- 前缀+逻辑视图名+后缀,逻辑视图名需要在controller中返回ModelAndView指定,比如逻辑视图名为hello,-->
<!-- 则最终返回的jsp视图地址 "WEB-INF/view/hello.jsp" -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean> <!--文件上传视图解析器 ,其中此处ID必须给,并且ID名字固定写法-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--允许上传的文件最大大小 单位是byte-->
<property name="maxUploadSize" value="100000000"></property>
</bean> <!--自定义异常的解析器(处理器) -->
<bean id="handerExceptionResolver" class="cn.zzsxt.resolver.CustomResolver"></bean> <!-- 注解映射器
说明 :对类中标记@ResquestMapping的方法进行映射,根据ResquestMapping定义的url匹配
ResquestMapping标记的方法,匹配成功返回HandlerMethod对象给前端控制器,HandlerMethod对象中封装url对应的方法Method
-->
<!--
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
-->
<!-- 注解适配器
说明:注解式处理器适配器,对标记@ResquestMapping的方法进行适配。
-->
<!--
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
-->
<!-- springmvc使用<mvc:annotation-driven> -->
<!-- 自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter, -->
<!-- 可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。 -->
<mvc:annotation-driven></mvc:annotation-driven> <!-- 处理静态资源 让静态资源可以直接访问-->
<!-- <mvc:resources mapping="/jquery-ui-1.12.1.custom/**" location="/jquery-ui-1.12.1.custom/"/> -->
<!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 -->
<mvc:default-servlet-handler/> </beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>springmvc01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <!-- 解决post提交乱码问题 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- spring mvc的前端控制器,类似struts2的核心过滤器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 通过contextConfigLocation参数指定配置文件的位置,默认在WEB-INF/查找名称为 [servlet-name]-servlet.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param> <!-- servlet随web容器而启动 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
TestException.java:
package cn.zzsxt.controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import cn.zzsxt.exception.CustomException; @Controller
public class TestException { @RequestMapping("/login")
public String login(String userName) throws CustomException{
if(userName.length()<6){
throw new CustomException("用户名长度不小于6位!");
}
return "success";
}
}
UploadController.java:
package cn.zzsxt.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.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile; @Controller
public class UploadController { @RequestMapping(value="/upload",method=RequestMethod.POST)
public String upload(@RequestParam("uploadFile")MultipartFile uploadFile){
String fileName = uploadFile.getOriginalFilename();//获取上传文件的文件名称
File filePath = new File("D:\\upload");
if(!filePath.exists())
filePath.mkdirs();
try {
uploadFile.transferTo(new File(filePath,fileName));//上传
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
} /**
* 多文件上传
* @param uploadFile
* @return
*/
@RequestMapping(value="/upload2",method=RequestMethod.POST)
public String upload2(@RequestParam("uploadFile")MultipartFile[] uploadFile){
File filePath = new File("D:\\upload");
if(!filePath.exists())
filePath.mkdirs();
try {
//循环变量上传
for (MultipartFile multipartFile : uploadFile) {
String fileName = multipartFile.getOriginalFilename();//获取上传文件的文件名称
multipartFile.transferTo(new File(filePath,fileName));
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} return "success";
}
}
CustomException.java:
package cn.zzsxt.exception; public class CustomException extends Exception {
public CustomException(){
}
public CustomException(String message){
super(message);
} }
CustomResolver.java:
package cn.zzsxt.resolver; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView; import cn.zzsxt.exception.CustomException; public class CustomResolver implements HandlerExceptionResolver { @Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object,
Exception exception) {
CustomException customException = null;
if(exception instanceof CustomException){
customException = (CustomException) exception;
}else{
customException = new CustomException("系统出现未知错误,请与管理员联系!");
}
ModelAndView mv = new ModelAndView();
mv.addObject("message", customException.getMessage());
mv.setViewName("error");
return mv;
} }
upload.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>单文件上传</title>
</head> <body>
<form action="upload" method="post" enctype="multipart/form-data"> // 固定enctype="multipart/form-data"
文件:<input type="file" name="uploadFile"/><br> <input type="submit" value="上传"/> </form> </body> </html>
upload2.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>多文件上传</title>
</head> <body>
<form action="upload2" method="post" enctype="multipart/form-data">
文件1:<input type="file" name="uploadFile"/><br>
文件2:<input type="file" name="uploadFile"/><br>
文件3:<input type="file" name="uploadFile"/><br>
<input type="submit" value="上传"/>
</form>
</body>
</html>
java:Springmvc框架2(Ajax,Json,Interceptor,Upload,Exception)的更多相关文章
- springmvc框架下ajax请求传参数中文乱码解决
springmvc框架下jsp界面通过ajax请求后台数据,传递中文参数到后台显示乱码 解决方法:js代码 运用encodeURI处理两次 /* *掩码处理 */ function maskWord( ...
- springMVC框架下返回json格式的对象,list,map
原文地址:http://liuzidong.iteye.com/blog/1069343 注意这个例子要使用jQuery,但是jquery文件属于静态的资源文件,所以要在springMVC中设置静态资 ...
- SpringMVC框架下实现JSON(类方法中回传数据到jsp页面,使用jQuery方法回传)
JSON的实现,即将需要的数据回传到jsp页面: 1>.加入实现Json的三个架包到lib中:2>.目标方法上边加入注解,需要返回的值3>.在jsp页面中书写jQuery方法: ec ...
- Java SpringMVC框架学习(三)springMVC的执行流程
具体执行逻辑如下: 浏览器提交请求到中央调度器. 中央调度器将请求转给处理器映射器. 处理器映射器根据请求, 找到请求对应的处理器, 并将其封装为处理器执行链返回给中央调度器. 中央调度器根据处理器执 ...
- Java SpringMVC框架学习(二)httpServeltRequest和Model传值的区别
HttpServletRequest 为什么大多程序在controller中给jsp传值时使用model.addAttribute()而不使用httpServeletRequest.setAttrib ...
- (转)springMVC框架下JQuery传递并解析Json数据
springMVC框架下JQuery传递并解析Json数据 json作为一种轻量级的数据交换格式,在前后台数据交换中占据着非常重要的地位.Json的语法非常简单,采用的是键值对表示形式.JSON 可以 ...
- SpringMVC中使用Ajax POST请求以json格式传递参数服务端通过request.getParameter("name")无法获取参数值问题分析
SpringMVC中使用Ajax POST请求以json格式传递参数服务端通过request.getParameter("name")无法获取参数值问题分析 一:问题demo展示 ...
- SpringMVC(四)-- springmvc的系统学习之文件上传、ajax&json处理
资源:尚学堂 邹波 springmvc框架视频 一.文件上传 1.步骤: (1)导入jar包 commons-fileupload,commons-io (2)在springmvc的配置文件中配置解析 ...
- SpringMVC整合Shiro,Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能
SpringMVC整合Shiro,Shiro是一个强大易用的Java安全框架,提供了认证.授权.加密和会话管理等功能. 第一步:配置web.xml <!-- 配置Shiro过滤器,先让Shiro ...
- springMVC框架下JQuery传递并解析Json数据
springMVC框架下JQuery传递并解析Json数据
随机推荐
- vps 11步移站步骤笔记
移站是经常的事,现在把步骤写上,防止忘记命令 1.登录SSH 2.打包数据库,phpmyadmin中备份数据库,导入新数据库,数据库中域名链接进行相应替换 获取phpmyadmin root密码 ca ...
- Puppetnginx 架构图
Puppetnginx 架构图 优点 *性能:nginx因为精简,运行起来非常快速,许多人声称它的比pound更高效.*日志,调试:在这两个方面,nginx比pound更简洁.*灵活性:nginx的处 ...
- buuctf@pwn1_sctf_2016
from pwn import * sh=remote('pwn.buuoj.cn',20086) get_flag=0x08048F0D payload='I'*0x14+'a'*4+p32(get ...
- document.writeln绑定数据 --点击跳转添加样式
document.writeln(" "); document.writeln(" "); document.writeln(" "); d ...
- sql DATEDIFF函数使用
date_part abbreviations year yy, yyyy quarter qq, q month mm, m dayofyear dy, y day dd, d week wk, w ...
- qq在线咨询
<a href="http://wpa.qq.com/msgrd?v=3&uin=2395848377&site=qq&menu=yes"> & ...
- Springboot 默认静态路径
springboot 默认静态路径 代码如下所示 类ResourceProperties.class private static final String[] CLASSPATH_RESOURCE_ ...
- 智能指针之shared_ptr基本概述
1.shared_ptr允许有多个指针指向同一个对象,unique_ptr独占所指向的对象. 2.类似于vector,智能指针也是模板.创建智能指针: shared_ptr<string> ...
- 【转】稳定婚姻问题(Stable Marriage Problem)
转自http://www.cnblogs.com/drizzlecrj/archive/2008/09/12/1290176.html 稳定婚姻是组合数学里面的一个问题. 问题大概是这样:有一个社团里 ...
- Compress Words
E. Compress Words 直接套 KMP 即可(那为什么打 cf 的时候没有想到...),求出后一个单词(word)的前缀数组,然后从前面已得的字符串的末尾 - word. length ( ...