SpringMVC快速入门

创建maven web工程,引入依赖

 
 
    5.0.2.RELEASE
 
 
     
        org.springframework 
        spring-context 
        ${spring.version} 
     
     
        org.springframework 
        spring-web 
        ${spring.version} 
     
    
         org.springframework 
        spring-webmvc 
        ${spring.version} 
     
     
        javax.servlet
         servlet-api
         2.5 
        provided 
     
     
        javax.servlet.jsp 
        jsp-api 
        2.0 
        provided 
      

在wweb.xml中配置前端控制器(最重要),配置中文乱码过滤器




  Archetype Created Web Application

  
  
    dispatcherServlet
    org.springframework.web.servlet.DispatcherServlet
     
    
      contextConfigLocation
      classpath:springmvc.xml
    
    
    1
  
  
    dispatcherServlet
    /
  

  
  
    characterEncodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
      UTF-8
    
  
  
    characterEncodingFilter
    /*
  


编写springMVC的配置文件




    
    

    
    
        
        
    
    
    
    
    
    
    
    
    
    
        
            
            
            
         
        
            
            
            
        

    
    
    

编写index.jsp和HelloController

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


    

入门程序

testString
testVoid
testModelAndView
testException

拦截器

testInterceptor
@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/testString")
    public String testString(Model model) {
        System.out.println("testString方法执行了");

        //模拟从数据库查出来用户
        User user = new User();
        user.setUsername("小明");
        user.setPassword("1234");
        user.setAge(19);

        //存到model对象
        model.addAttribute("user", user);
        return "success";
    }

    @RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("testVoid方法执行了");
//        request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
//        response.sendRedirect(request.getContextPath()+"/index2.jsp");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println("

你好

"); return; } @RequestMapping("/testModelAndView") public ModelAndView testModelAndView() { System.out.println("testModelAndView方法执行了"); ModelAndView mv = new ModelAndView(); User user = new User(); user.setUsername("小丑"); user.setPassword("1234"); user.setAge(19); mv.addObject("user", user); mv.setViewName("success"); return mv; } @RequestMapping("/testAjax") public @ResponseBody User testAjax(@RequestBody User user) { System.out.println("testAjax方法执行了"); System.out.println(user); //响应,模拟查询数据库 user.setUsername("Rose"); user.setAge(33); return user; } @RequestMapping("/fileUpload1") public String fileUpload1(HttpServletRequest request) throws Exception { System.out.println("fileUpload1方法执行了"); String path = request.getSession().getServletContext().getRealPath("/uploads/"); File file = new File(path); if (!file.exists()) { file.mkdirs(); } DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List fileItems = upload.parseRequest(request); for (FileItem item : fileItems) { if (item.isFormField()) { //普通 } else { //文件 String name = item.getName(); String s = UUID.randomUUID().toString().replace("-", ""); name = s + name; item.write(new File(path, name)); item.delete(); } } return "success"; } @RequestMapping("/fileUpload2") public String fileUpload2(HttpServletRequest request, MultipartFile upload) throws Exception { System.out.println("fileUpload2方法执行了"); String path = request.getSession().getServletContext().getRealPath("/uploads/"); File file = new File(path); if (!file.exists()) { file.mkdirs(); } String name = upload.getOriginalFilename(); String s = UUID.randomUUID().toString().replace("-", ""); name = s + name; upload.transferTo(new File(path, name)); return "success"; } @RequestMapping("/fileUpload3") public String fileUpload3(MultipartFile upload) throws Exception { System.out.println("fileUpload3方法执行了"); //定义上传服务器的路径 String path = "http://localhost:8081/uploads/"; String name = upload.getOriginalFilename(); String s = UUID.randomUUID().toString().replace("-", ""); name = s + name; //跨服务器上传 //创建客户端对象 Client client = Client.create(); //和服务器连接 WebResource resource = client.resource(path + name); //上传 resource.put(upload.getBytes()); return "success"; } @RequestMapping("/testException") public String testException() throws SysException { System.out.println("testException方法执行了"); try { int a = 10 / 0; } catch (Exception e) { e.printStackTrace(); throw new SysException("查询所有用户出现错误"); } return "success"; } @RequestMapping("/testInterceptor") public String testInterceptor() { System.out.println("testInterceptor方法执行了"); return "success"; } }

在WEB-INF目录下创建pages文件夹,编写success.jsp的成功页面

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>


    Title



    

执行成功

${user.username} ${user.password} ${user.age} <% System.out.println("success.jsp执行了"); %>

启动Tomcat服务器,进行测试

项目结构

SpringMVC快速入门_第1张图片

你可能感兴趣的:(SpringMVC快速入门)