SpringMVC入门
配置web.xml文件
前端控制器
DispatcherServlet:org.springframework.web.servlet.DispatcherServlet
dispatcherServlet
org.springframework.web.servlet.DispatcherServlet
参数
类路径下的:classpath:springmvc.xml
contextConfigLocation
classpath:springmvc.xml
1
dispatcherServlet
/
配置解决中文乱码的过滤器
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
characterEncodingFilter
/*
配置springmvc.xml文件
开启注解的扫描
视图解析器
自定义类型转换器
转换器类
public class StringToConverter implements Converter {
/**
*
* @param source 传入的字符串
* @return
*/
@Override
public Date convert(String source) {
//判断
if(source == null){
throw new RuntimeException("请传入数据");
}
SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
//把字符串传换成日期
return dataFormat.parse(source);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
前端控制器,哪些静态资源不拦截
开起springMVC框架注解的支持
注解
控制器
@Controller
路径的注解
@RequestMapping("/user")
@RequestMapping(path = "/hello")
@RequestMapping("/testRequestMapping")
@Controller
@RequestMapping("/user")
public class HelloController {
@RequestMapping(path = "/hello")
public String sayHello(){
System.out.println("hello springMVC");
return "success";
}
// @RequestMapping(path = "/testRequestMapping")
@RequestMapping("/testRequestMapping")
//@RequestMapping(value = "/testRequestMapping",params = {"username==heihei"})
//@RequestMapping(value = "/testRequestMapping",params = {"username"})
//@RequestMapping(value = "/testRequestMapping",method = {RequestMethod.POST,RequestMethod.GET})
public String testRequestMapping(){
System.out.println("RequestMapping");
return "success";
}
}
常用注解
@Controller
@RequestMapping("/annotation")
@SessionAttributes(value = {"msg"})//存入Session中
public class AnnoController {
/**
* 当名字对应不上的时候 对应
* @param name
* @return
*/
@RequestMapping("/testRequestParam")
public String testRequestParam(@RequestParam("username") String name){
System.out.println("ok");
System.out.println(name);
return "success";
}
/**
* 获取到请求体的内容
* @return
*/
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String body){
System.out.println("ok");
System.out.println(body);
return "success";
}
/**
* PathVariable
* @return
*/
@RequestMapping(value = "/testPathVariable/{sid}")
public String testPathVariable(@PathVariable(name = "sid") String id){
System.out.println("ok");
System.out.println(id);
return "success";
}
/**
* 获取请求头的值
* @param header
* @return
*/
@RequestMapping("/testRequestHeader")
public String testRequestHeader(@RequestHeader("Accept") String header){
System.out.println("ok");
System.out.println(header);
return "success";
}
/**
* 获取Cookie中的值
* @param cookie
* @return
*/
@RequestMapping("/testCookieValue")
public String testCookieValue(@CookieValue("JSESSIONID") String cookie){
System.out.println("ok");
System.out.println(cookie);
return "success";
}
/**
* testModelAttribute 放在有返回值方法上 或者 放在没有返回值方法上的
* @return
*/
@RequestMapping("/testModelAttribute")
public String testModelAttribute(@ModelAttribute("abc") User user){
System.out.println("testModelAttribute is ok");
System.out.println(user);
return "success";
}
/**
* ModelAttribute
* 方法优先执行
* @return
*/
/*
@ModelAttribute
public User ShowUser(String uname){
System.out.println("showUser is ok");
User user = new User();
user.setUname(uname);
user.setAge(10);
user.setDate(new Date());
return user;
}
*/
@ModelAttribute
public void ShowUser(String uname, Map map){
System.out.println("showUser is ok");
User user = new User();
user.setUname(uname);
user.setAge(10);
user.setDate(new Date());
map.put("abc",user);
}
/**
* SessionAttributes 放在类上 把数据存如Session中 @SessionAttributes(value = {"msg"})
* @return
*/
@RequestMapping("/testSessionAttributes")
public String testSessionAttributes(Model model){
System.out.println("testSessionAttributes is ok");
//底层存储到Request域中
model.addAttribute("msg","美美");
return "success";
}
@RequestMapping("/getSessionAttribute")
public String getSessionAttribute(ModelMap modelMap,HttpServletRequest request){
String msg = (String) modelMap.get("msg");
System.out.println("modelMap:"+msg);
String attribute = (String) request.getSession().getAttribute("msg");
System.out.println("session:"+attribute);
return "success";
}
/**
* 清除Session中的数据
* @param sessionStatus
* @return
*/
@RequestMapping("/deleteSessionAttribute")
public String deleteSessionAttribute(SessionStatus sessionStatus){
sessionStatus.setComplete();
return "success";
}
}
Response
请求转发
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("testVoid方法执行了...");
// 编写请求转发的程序
// request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
// 重定向
// response.sendRedirect(request.getContextPath()+"/index.jsp");
// 设置中文乱码
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
// 直接会进行响应
response.getWriter().print("你好");
return;
}
ModelAndView
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
// 创建ModelAndView对象
ModelAndView mv = new ModelAndView();
System.out.println("testModelAndView方法执行了...");
// 模拟从数据库中查询出User对象
User user = new User();
user.setUsername("小凤");
user.setPassword("456");
user.setAge(30);
// 把user对象存储到mv对象中,也会把user对象存入到request对象
mv.addObject("user",user);
// 跳转到哪个页面
mv.setViewName("success");
return mv;
}
使用关键字的方式进行转发或者重定向
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect(){
System.out.println("testForwardOrRedirect方法执行了...");
// 请求的转发
// return "forward:/WEB-INF/pages/success.jsp";
// 重定向
return "redirect:/index.jsp";
}
文件上传
配置springmvc.xml文件解析对象
配置文件解析器对象,要求id名称必须是multipartResolver
三种文件上传的格式
/**
* 文件上传
* @return
*/
@RequestMapping("/fileLoad1")
public String fileLoad1(HttpServletRequest request) throws Exception {
System.out.println("文件上传");
//使用fileUpload组件
String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
File file = new File(realPath);
if(!file.exists()){
file.mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List fileItems = upload.parseRequest(request);
for (FileItem fileItem : fileItems) {
if(fileItem.isFormField()){
//普通表单
}else{
//说明上传文件
String fileItemName = fileItem.getName();
fileItem.write(new File(realPath,fileItemName));
fileItem.delete();
}
}
return "success";
}
/**
* SpringMVC文件上传
* @return
*/
@RequestMapping("/fileLoad2")
public String fileLoad2(HttpServletRequest request, MultipartFile upload) throws IOException {
System.out.println("SpringMVC方式的文件上传...");
// 先获取到要上传的文件目录
String path = request.getSession().getServletContext().getRealPath("/uploads");
// 创建File对象,一会向该路径下上传文件
File file = new File(path);
// 判断路径是否存在,如果不存在,创建该路径
if(!file.exists()) {
file.mkdirs();
}
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
// 把文件的名称唯一化
filename = uuid+"_"+filename;
// 上传文件
upload.transferTo(new File(file,filename));
return "success";
}
@RequestMapping("/fileLoad3")
public String fileLoad3(HttpServletRequest request, MultipartFile upload) throws IOException {
System.out.println("跨服务器方式的文件上传...");
// 定义图片服务器的请求路径
String path = "http://localhost:9090/day02_springmvc5_02image/uploads/";
// 获取到上传文件的名称
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
// 把文件的名称唯一化
filename = uuid+"_"+filename;
// 向图片服务器上传文件
// 创建客户端对象
Client client = Client.create();
// 连接图片服务器
WebResource webResource = client.resource(path+filename);
// 上传文件
webResource.put(upload.getBytes());
return "success";
}
配置异常处理器
配置springmvc.xml的配置文件
设置异常类
public class SysException extends Exception{
private String message;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SysException(String message) {
this.message = message;
}
}
编写异常处理器
用ModelAndView对象把异常信息存储到域中
public class SysExceptionResolver implements HandlerExceptionResolver {
/**
* 处理异常的业务逻辑
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param e
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
SysException exception = null;
if(e instanceof SysException){
exception = (SysException) e;
}else {
exception = new SysException("系统整在维护");
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("errorMsg",exception.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
配置拦截器
配置springmvc.xml的配置文件
/**
* 自定义拦截器1
*/
public class MyInterceptor1 implements HandlerInterceptor {
/**
* 预处理
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器执行了......前1");
//response.sendRedirect(request.getContextPath()+"/error.jsp");
return true;
}
/**
* 后处理的方法 controller方法执行后执行 success.jsp执行之前
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("拦截器执行了......后1");
//response.sendRedirect(request.getContextPath()+"/error.jsp");
}
/**
* 在success.jsp方法后执行
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("拦截器执行了......最后1");
}
}
/**
* 自定义拦截器2
*/
public class MyInterceptor2 implements HandlerInterceptor {
/**
* 预处理
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器执行了......前2");
//response.sendRedirect(request.getContextPath()+"/error.jsp");
return true;
}
/**
* 后处理的方法 controller方法执行后执行 success.jsp执行之前
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("拦截器执行了......后2");
//response.sendRedirect(request.getContextPath()+"/error.jsp");
}
/**
* 在success.jsp方法后执行
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("拦截器执行了......最后2");
}
}