• SpringMVC


    一、

    1.entity

     1 package com.zhidi.entity;
     2 
     3 import java.util.Date;
     4 
     5 import org.springframework.format.annotation.DateTimeFormat;
     6 
     7 import com.fasterxml.jackson.annotation.JsonFormat;
     8 import com.fasterxml.jackson.annotation.JsonIgnore;
     9 import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
    10 
    11 //忽略一系列的属性,在类上加@JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
    12 //避免延迟加载的关联对象在转换为JSON数据时出现异常。
    13 @JsonIgnoreProperties({"age","id"})
    14 public class Student {
    15     
    16     //用在属性上,表示忽略此属性
    17     @JsonIgnore
    18     private Integer id;
    19     private String userName;
    20     private String sex;
    21     private Integer age;
    22     /*@DateTimeFormat(pattern="yyyy-MM-dd")*/
    23     //格式化时间
    24     @JsonFormat(pattern="yyyy_MM_dd")
    25     private Date date;
    26     public Integer getId() {
    27         return id;
    28     }
    29     public void setId(Integer id) {
    30         this.id = id;
    31     }
    32     public String getUserName() {
    33         return userName;
    34     }
    35     public void setUserName(String userName) {
    36         this.userName = userName;
    37     }
    38     public String getSex() {
    39         return sex;
    40     }
    41     public void setSex(String sex) {
    42         this.sex = sex;
    43     }
    44     public Integer getAge() {
    45         return age;
    46     }
    47     public void setAge(Integer age) {
    48         this.age = age;
    49     }
    50     public Date getDate() {
    51         return date;
    52     }
    53     public void setDate(Date date) {
    54         this.date = date;
    55     }
    56     @Override
    57     public String toString() {
    58         return "Student [id=" + id + ", userName=" + userName + ", sex=" + sex + ", age=" + age + ", date=" + date
    59                 + "]";
    60     }
    61 
    62 }
    View Code
     1 package com.zhidi.entity;
     2 
     3 import org.hibernate.validator.constraints.Email;
     4 import org.hibernate.validator.constraints.NotEmpty;
     5 
     6 public class User {
     7     
     8     private Integer id;
     9     @NotEmpty(message="{name.notNull}")
    10     private String name;
    11     @NotEmpty(message="{password.notNull}")
    12     private String password;
    13     @Email(message="{email.error}")
    14     private String email;
    15     public Integer getId() {
    16         return id;
    17     }
    18     public void setId(Integer id) {
    19         this.id = id;
    20     }
    21     public String getName() {
    22         return name;
    23     }
    24     public void setName(String name) {
    25         this.name = name;
    26     }
    27     public String getPassword() {
    28         return password;
    29     }
    30     public void setPassword(String password) {
    31         this.password = password;
    32     }
    33     public String getEmail() {
    34         return email;
    35     }
    36     public void setEmail(String email) {
    37         this.email = email;
    38     }
    39     @Override
    40     public String toString() {
    41         return "User [id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + "]";
    42     }
    43     
    44 
    45 }
    View Code

    2.util

     1 package com.zhidi.util;
     2 import java.text.ParseException;
     3 import java.text.SimpleDateFormat;
     4 import java.util.Date;
     5 
     6 import org.springframework.core.convert.converter.Converter;
     7 /*
     8  * 自定义日期转化器
     9  */
    10 public class DateFormat implements Converter<String, Date> {
    11 
    12     @Override
    13     public Date convert(String date) {
    14         SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    15         try {
    16             return sf.parse(date);
    17         } catch (ParseException e) {
    18             e.printStackTrace();
    19         }
    20         return null;
    21     }
    22 
    23 }
    View Code
     1 package com.zhidi.util;
     2 
     3 import java.text.ParseException;
     4 import java.text.SimpleDateFormat;
     5 import java.util.Date;
     6 
     7 import org.springframework.core.convert.converter.Converter;
     8 
     9 public class DateFormat1 implements Converter<String, Date>{
    10     
    11     private String pattern;
    12 
    13     @Override
    14     public Date convert(String date) {
    15         SimpleDateFormat sf=new SimpleDateFormat(pattern);
    16         try {
    17             return sf.parse(date);
    18         } catch (ParseException e) {
    19             e.printStackTrace();
    20         }
    21         
    22         return null;
    23     }
    24     
    25     public void setPattern(String pattern) {
    26         this.pattern = pattern;
    27     }
    28 
    29 }
    View Code
     1 package com.zhidi.util;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 import java.util.HashMap;
     6 import java.util.Map;
     7 
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 
    11 import org.springframework.web.servlet.HandlerExceptionResolver;
    12 import org.springframework.web.servlet.ModelAndView;
    13 
    14 import com.fasterxml.jackson.databind.ObjectMapper;
    15 
    16 /*
    17  * 实现HandlerExceptionResolver接口的自定义异常处理器
    18  */
    19 public class ExceptionResolver implements HandlerExceptionResolver{
    20 
    21     @Override
    22     public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
    23             Exception e) {
    24         
    25         //获得请求头信息中的X-Requested-With值,判断是非为json数据(XMLHttpRequest)
    26         String xrw=    request.getHeader("X-Requested-With");
    27         if(xrw!=null&&"XMLHttpRequest".equalsIgnoreCase(xrw))
    28         {
    29             //设置请求头信息
    30             response.setContentType("application/json;charset=utf-8");
    31             //获取流
    32             try {
    33                 PrintWriter out=response.getWriter();
    34                 Map<Object, Object> map=new HashMap<>();
    35                 map.put("success", false);
    36                 map.put("msg", e.getMessage());
    37                 
    38                 //通过ObjectMapper转化为json数据并输出
    39                 ObjectMapper mapper=new ObjectMapper();
    40                 mapper.writeValue(out, map);
    41                 out.flush();
    42                 out.close();
    43                 return null;
    44                 
    45             } catch (IOException e1) {
    46                 e1.printStackTrace();
    47             }
    48         }
    49         
    50         //创建ModelAndView对象
    51         ModelAndView view=new ModelAndView();
    52         //设置异常页面
    53         view.setViewName("error");
    54         view.addObject("error", "傻逼");
    55         return view;
    56     }
    57 
    58 }
    View Code

    3.controller

     1 package com.zhidi.controller;
     2 
     3 import org.springframework.stereotype.Controller;
     4 import org.springframework.web.bind.annotation.RequestBody;
     5 import org.springframework.web.bind.annotation.RequestMapping;
     6 
     7 import com.zhidi.entity.Student;
     8 
     9 @Controller
    10 public class JsonController {
    11 
    12     @RequestMapping("/toJson")
    13     public String toJson() {
    14         return "json";
    15     }
    16 
    17     @RequestMapping("/json")
    18     public String json(@RequestBody Student student) {
    19         System.out.println(student);
    20         return "success";
    21     }
    22     
    23     
    24 }
    View Code
     1 package com.zhidi.controller;
     2 
     3 import java.util.ArrayList;
     4 import java.util.Date;
     5 import java.util.HashMap;
     6 import java.util.List;
     7 import java.util.Map;
     8 
     9 import org.springframework.stereotype.Controller;
    10 import org.springframework.web.bind.annotation.RequestMapping;
    11 import org.springframework.web.bind.annotation.ResponseBody;
    12 
    13 import com.zhidi.entity.Student;
    14 
    15 @Controller
    16 @ResponseBody
    17 @RequestMapping("/json")
    18 public class JsonController1 {
    19     
    20     @RequestMapping("/json")
    21     public Student json()
    22     {
    23         Student stu=new Student();
    24         stu.setUserName("张三");
    25         stu.setSex("男");
    26         stu.setId(2);
    27         stu.setDate(new Date());
    28         
    29         return stu;
    30     }
    31     
    32     
    33     @RequestMapping("/map")
    34     public Map<Object, Object> map()
    35     {
    36         Map<Object, Object> map=new HashMap<>();
    37         map.put("name", "尼古拉斯");
    38         List<Object> list=new ArrayList<>();
    39         list.add("赵四");
    40         list.add("刘能");
    41         list.add("杀驴逼");
    42         map.put("list", list);
    43         return map;
    44                 
    45     }
    46     
    47 
    48 }
    View Code
     1 package com.zhidi.controller;
     2 
     3 import java.io.IOException;
     4 import java.io.PrintWriter;
     5 import java.util.HashMap;
     6 import java.util.Map;
     7 
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 
    11 import org.springframework.stereotype.Controller;
    12 import org.springframework.ui.ModelMap;
    13 import org.springframework.web.bind.annotation.ModelAttribute;
    14 import org.springframework.web.bind.annotation.RequestMapping;
    15 import org.springframework.web.servlet.ModelAndView;
    16 
    17 import com.zhidi.entity.Student;
    18 
    19 @Controller
    20 public class ReturnController {
    21 
    22     // 返回类型为ModelAndView,在页面可以通过el表达式获得
    23     @RequestMapping("/mv")
    24     public ModelAndView mv() {
    25         ModelAndView mv = new ModelAndView();
    26         //为其指定逻辑视图名
    27         mv.setViewName("welcome");
    28         //将数据封装到mv中
    29         mv.addObject("name", "张三");
    30         return mv;
    31     }
    32     
    33     
    34     @RequestMapping("/stu")
    35     public Student pojo(Student stu)
    36     {        
    37         stu.setUserName("赵虎");    
    38         stu.setAge(33);
    39         return stu;
    40     }
    41     
    42     
    43     @RequestMapping("/void")
    44     public void returnVoid(HttpServletRequest request,HttpServletResponse response) throws IOException
    45     {
    46         response.setContentType("application/json; charset=utf-8");
    47         PrintWriter out=response.getWriter();
    48         out.println("{"name":"张三"}");
    49         out.flush();
    50         out.close();
    51     }
    52 
    53     @RequestMapping("/modelMap")
    54     public ModelMap modelMap(ModelMap modelMap)
    55     {
    56         modelMap.put("name", "赵四");
    57         return modelMap;
    58     }
    59     
    60     @RequestMapping("/map")
    61     public Map<Object, Object> map()
    62     {
    63         HashMap<Object, Object> map=new HashMap<>();
    64         map.put("name", "刘能");
    65         return map;
    66     }
    67     
    68     
    69     @ModelAttribute("stu")
    70     public Student model()
    71     {
    72         Student stu=new Student();
    73         stu.setId(12);        
    74         return stu;
    75     }
    76     
    77     @RequestMapping("/edit")
    78     public Student edit(@ModelAttribute("stu") Student stu1)
    79     {
    80         System.out.println(stu1);
    81         stu1.setId(111);
    82         return stu1;
    83     }
    84     
    85     
    86         
    87     
    88 }
    View Code
     1 package com.zhidi.controller;
     2 
     3 import org.springframework.stereotype.Controller;
     4 import org.springframework.ui.Model;
     5 import org.springframework.web.bind.annotation.ModelAttribute;
     6 import org.springframework.web.bind.annotation.RequestMapping;
     7 import org.springframework.web.bind.annotation.SessionAttributes;
     8 import org.springframework.web.bind.support.SessionStatus;
     9 
    10 import com.zhidi.entity.Student;
    11 
    12 @Controller
    13 //@SessionAttributes("stu")指定将特定的user模型数据添加到session中
    14 @SessionAttributes("stu")
    15 public class SessionController {
    16     
    17     @RequestMapping("/login")
    18     public String login(Student stu,Model model)
    19     {
    20         if(stu!=null)
    21         {
    22             model.addAttribute("stu",stu);
    23             return "success";
    24         }
    25         return "login";
    26     }
    27     
    28     @RequestMapping("/toLogin")
    29     public String toLogin()
    30     {
    31         return "login";
    32     }
    33     
    34 
    35     @RequestMapping("/modify")
    36     public String modify(@ModelAttribute("stu") Student stu)
    37     {    
    38         System.out.println(stu);
    39         return "success";
    40     }
    41     
    42     @RequestMapping("/logout")
    43     public String logout(@ModelAttribute("stu") Student stu,SessionStatus status)
    44     {
    45         System.out.println(stu);
    46         status.setComplete();
    47         return "login";
    48     }
    49 }
    View Code
     1 package com.zhidi.controller;
     2 
     3 import java.util.HashMap;
     4 import java.util.Map;
     5 
     6 import javax.servlet.http.HttpServletRequest;
     7 
     8 import org.springframework.stereotype.Controller;
     9 import org.springframework.web.bind.annotation.ExceptionHandler;
    10 import org.springframework.web.bind.annotation.RequestMapping;
    11 import org.springframework.web.bind.annotation.ResponseBody;
    12 
    13 @Controller
    14 public class TestExceptionController {
    15 
    16     //@ExceptionHandler只能处理当前的异常 
    17     /*@ExceptionHandler
    18     public String handler(HttpServletRequest request,Exception e)
    19     {
    20         request.setAttribute("e", e);
    21         return "success";
    22     }*/
    23     
    24     
    25     
    26     @RequestMapping("/test")
    27     public String test()
    28     {
    29         int[] a={};
    30         System.out.println(a[3]);
    31         
    32         return "success";
    33     }
    34     
    35     //调到json页面
    36     @RequestMapping("/toAjax")
    37     public String tojson()
    38     {
    39         return "ajax";
    40     }
    41     
    42     @ResponseBody
    43     @RequestMapping("/ajax")
    44     public Map<String, Object> ajax()
    45     {
    46         int[] arrays = new int[10];
    47         System.out.println(arrays[100]);
    48         Map<String, Object> result = new HashMap<String, Object>();
    49         result.put("success", true);
    50         result.put("msg", "123");
    51         
    52         return result;
    53     }
    54     
    55     
    56     
    57 }
    View Code
      1 package com.zhidi.controller;
      2 
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.IOException;
      6 import java.io.InputStream;
      7 import java.io.OutputStream;
      8 import java.io.UnsupportedEncodingException;
      9 
     10 import javax.servlet.http.HttpServletRequest;
     11 import javax.servlet.http.HttpServletResponse;
     12 
     13 import org.apache.commons.io.FileUtils;
     14 import org.springframework.http.HttpHeaders;
     15 import org.springframework.http.HttpStatus;
     16 import org.springframework.http.MediaType;
     17 import org.springframework.http.ResponseEntity;
     18 import org.springframework.stereotype.Controller;
     19 import org.springframework.ui.Model;
     20 import org.springframework.web.bind.annotation.RequestMapping;
     21 import org.springframework.web.multipart.MultipartFile;
     22 
     23 @Controller
     24 public class UpLoadController {
     25     
     26     //跳转到文件上传页面
     27     @RequestMapping("/toUpLoad")
     28     public String toUpLoad()
     29     {
     30         return "upLoad";
     31     }
     32     
     33     //单文件上传
     34     @RequestMapping("/upLoad")
     35     public String upLoad(MultipartFile img) throws IllegalStateException, IOException
     36     {
     37         //获取原始文件名
     38         String source=img.getOriginalFilename();
     39         //获取文件的大小
     40         long size= img.getSize();
     41         //获取文件的类型     
     42         String type= img.getContentType();
     43         System.out.println(source+"	"+size+"	"+type);
     44         
     45         /*
     46         //保存的路劲有可能不存在
     47         File savePath=new File("D:\upload");
     48         
     49         if(!savePath.exists())
     50         {
     51             //如果不存在就创建文件夹
     52             savePath.mkdirs();
     53         }
     54         
     55          img.transferTo(new File(savePath,source));*/
     56         
     57        
     58         if(!img.isEmpty())
     59         {
     60             img.transferTo(new File("D:\",source));
     61         }
     62         return "success";
     63     }
     64     
     65     //多文件上传
     66     @RequestMapping("/upLoad1")
     67     public String upLoad1(MultipartFile[] imgs) throws IllegalStateException, IOException
     68     {
     69         if(imgs!=null)
     70         {
     71              //保存的路劲有可能不存在
     72             File savePath=new File("D:\upload");
     73             
     74             if(!savePath.exists())
     75             {
     76                 //如果不存在就创建文件夹
     77                 savePath.mkdirs();
     78             }
     79             
     80              for(MultipartFile img:imgs)
     81              {
     82                 //获取原始文件名
     83                  String source=img.getOriginalFilename();
     84                  //获取文件的大小
     85                  long size= img.getSize();
     86                  //获取文件的类型     
     87                  String type= img.getContentType();
     88                  System.out.println(source+"	"+size+"	"+type);
     89                  //将文件保存到指定路径
     90                  img.transferTo(new File(savePath,source));
     91              }
     92         }
     93         return "success";
     94     }
     95 
     96 
     97     //单文件上传并显示图片
     98     @RequestMapping("/load")
     99     public String load(MultipartFile imgs,HttpServletRequest request,Model model) throws IllegalStateException, IOException
    100     {
    101          //获取文件的原始名字
    102          String    fileName=imgs.getOriginalFilename();
    103         
    104          //得到项目文件的真实路径
    105          String    realPath=request.getServletContext().getRealPath("upload");
    106          if(!imgs.isEmpty())
    107          {
    108              imgs.transferTo(new File(realPath, fileName));
    109          }
    110          //上传到服务器下文件的路径
    111          String path= request.getContextPath()+"/upload/"+fileName;
    112          model.addAttribute("path",path);
    113          return "success";
    114         
    115     }
    116     
    117     
    118     
    119     //文件下载1
    120     @RequestMapping("/downLoad")
    121     public void downLoad(HttpServletResponse response) throws IOException
    122     {
    123         File file=new File("D://图片//645.jpg");
    124         //乱码解决
    125         String fileName=new String(file.getName().getBytes("UTF-8"),"ISO-8859-1" );
    126         //设置响应内容信息
    127         response.setContentType("application/octet-stream");
    128         //设置响应头信息
    129         response.setHeader("content-disposition", "attachment;filename="+fileName);
    130         //获取输出流
    131         OutputStream out=response.getOutputStream();
    132         //创建输入流
    133         InputStream in=new FileInputStream(file);
    134         //数据写出
    135         byte[] b=new byte[1024];
    136         int len=0;
    137         while((len=in.read(b))!=-1)
    138         {
    139             out.write(b, 0, len);
    140         }
    141         
    142         out.close();
    143         in.close();
    144     }
    145     
    146     /*
    147      * 将二进制数据封装到响应中
    148      */
    149     //文件下载2
    150     @RequestMapping("/downLoad2")
    151     public ResponseEntity<byte[]> downLoad2() throws IOException
    152     {
    153         File file=new File("D://图片//645.jpg");
    154         //乱码解决
    155         String fileName=new String(file.getName().getBytes("UTF-8"),"ISO-8859-1" );
    156         //创建HttpHeader对象
    157         HttpHeaders headers=new HttpHeaders();
    158         headers.setContentDispositionFormData("attachment", fileName);
    159         headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    160         //创建字节数组
    161         byte[] b=FileUtils.readFileToByteArray(file);
    162         //创建ResponseEntity对象
    163         ResponseEntity<byte[]> entity=new ResponseEntity<byte[]>(b,headers, HttpStatus.OK);
    164         return entity;
    165     }
    166 }
    View Code
     1 package com.zhidi.controller;
     2 
     3 import org.springframework.stereotype.Controller;
     4 import org.springframework.ui.ModelMap;
     5 import org.springframework.validation.Errors;
     6 import org.springframework.validation.annotation.Validated;
     7 import org.springframework.web.bind.annotation.RequestMapping;
     8 
     9 import com.zhidi.entity.User;
    10 
    11 @Controller
    12 public class ValidationCotroller {
    13     
    14     //其中@Valid或@Validated注解用于指定对User数据进行校验
    15     //其中Errors用于存储校验时的错误信息,如果hasErrors()返回true,说明本次校验存在不符合校验规则的错误信息。
    16     //Errors要紧跟在对象后面
    17     @RequestMapping("/valid")
    18     public String valid(@Validated User user,Errors error,ModelMap model)
    19     {
    20         if(error.hasErrors())
    21         {
    22             model.put("error",error );
    23             
    24             return "error";
    25         }
    26         System.out.println(user);
    27         return "success";
    28     }
    29 
    30 }
    View Code
      1 package com.zhidi.controller;
      2 
      3 import java.util.Date;
      4 
      5 import javax.servlet.http.HttpServletRequest;
      6 import javax.servlet.http.HttpServletResponse;
      7 import javax.servlet.http.HttpSession;
      8 
      9 import org.springframework.format.annotation.DateTimeFormat;
     10 import org.springframework.stereotype.Controller;
     11 import org.springframework.ui.ModelMap;
     12 import org.springframework.web.bind.annotation.PathVariable;
     13 import org.springframework.web.bind.annotation.RequestMapping;
     14 import org.springframework.web.bind.annotation.RequestMethod;
     15 import org.springframework.web.bind.annotation.RequestParam;
     16 import com.zhidi.entity.Student;
     17 
     18 //在类上使用@RequestMapping相当于相对路径,访问时为http://localhost:8080/springmvc01/user/hello4.do
     19 @RequestMapping("/user")
     20 @Controller
     21 public class WelController {
     22     // 方法上使用@RequestMapping相当于绝对路径
     23     @RequestMapping("/hello")
     24     public String hello() {
     25         return "welcome";
     26     }
     27 
     28     // 限于当前方法只用于get方式请求,并且请求参数中包含参数username(访问时要加上参数)
     29     @RequestMapping(value = "/hello1", method = RequestMethod.GET, params = "username")
     30     public String hello1() {
     31         return "welcome";
     32     }
     33 
     34     @RequestMapping("/hello2")
     35     public String hello2(HttpServletRequest request, HttpServletResponse response) {
     36         // 通过请求对象获取请求参数
     37         String name = request.getParameter("username");
     38         request.setAttribute("username", name);
     39         return "welcome";
     40     }
     41 
     42     @RequestMapping("/hello3")
     43     public String hello3(HttpSession session) {
     44         session.setAttribute("username", "赵四");
     45         return "welcome";
     46     }
     47 
     48     @RequestMapping("/hello4")
     49     public String hello4(ModelMap map) {
     50         map.addAttribute("username", "刘能");
     51         return "welcome";
     52     }
     53 
     54     // 普通参数设定
     55     @RequestMapping("/hello5")
     56     public String hello5(String username) {
     57         System.out.println(username);
     58         return "welcome";
     59     }
     60 
     61     // 当URL的参数名和方法里的形参名不一致时用@RequestParam,里面的值要和URL的参数名一致
     62     @RequestMapping("/hello6")
     63     public String hello6(@RequestParam("name") String username) {
     64         System.out.println(username);
     65         return "welcome";
     66     }
     67 
     68     // 访问表单
     69     @RequestMapping("/hello7")
     70     public String hello7() {
     71         return "welcome";
     72     }
     73 
     74     // 将请求参数传到pojo上
     75     @RequestMapping("/hello8")
     76     public String hello8(Student stu) {
     77         System.out.println(stu);
     78         return "welcome";
     79     }
     80 
     81     @RequestMapping("/hello9")
     82     public String hello9(@PathVariable("id") Integer id) {
     83         System.out.println(id);
     84         return "welcome";
     85     }
     86 
     87     @RequestMapping("/test")
     88     public String test(@DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
     89         System.out.println(date);
     90         return "welcome";
     91     }
     92 
     93     // 自定义时间转化
     94     @RequestMapping("/test1")
     95     public String test1(Date date) {
     96         System.out.println(date);
     97         return "welcome";
     98     }
     99     
    100     //将URL中占位符的值绑定到方法的形参上,访问路径为http://localhost:8080/springmvc01/user/2/test2.do
    101     @RequestMapping("/{id}/test2")
    102     public String test2(@PathVariable("id")Integer id)
    103     {
    104         System.out.println(id);
    105         return "welcome";
    106     }
    107     
    108     //http://localhost:8080/springmvc01/user/2/test3/admin.do
    109     @RequestMapping("/{id}/test3/{name}")
    110     public String test3(@PathVariable("id")Integer id,@PathVariable("name")String name)
    111     {
    112         System.out.println(id+":"+name);
    113         return "welcome";
    114     }
    115     
    116     //通过”forward:逻辑视图” 指定以转发形式转向到对应物理视图
    117     @RequestMapping("/forward")
    118     public String forward()
    119     {
    120         return "forward:2/test3/admin.do";
    121     }
    122     
    123     //通过”redirect:逻辑视图” 指定以重定向形式转向到对应物理视图
    124     @RequestMapping("/redirect")
    125     public String redirecr()
    126     {
    127         return "redirect:toInfo.do";
    128     }
    129     
    130     @RequestMapping("/toInfo")
    131     public String toInfo()
    132     {
    133         return "welcome";
    134     }
    135     
    136     
    137     
    138 }
    View Code

    4.配置文件

    1 name.notNull=u540Du5B57u4E0Du80FDu4E3Au7A7A
    2 password.notNull=u5BC6u7801u4E0Du80FDu4E3Au7A7A
    3 email.error=u90AEu7BB1u683Cu5F0Fu4E0Du5BF9
    View Code
     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
     4     xmlns:context="http://www.springframework.org/schema/context"
     5     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
     6         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
     7         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
     8     <!-- 扫描控制器所在的包 -->
     9     <context:component-scan base-package="com.zhidi.controller" />
    10     <!-- 开启springmvc注解 -->
    11     <mvc:annotation-driven conversion-service="conversionService"
    12         validator="validator" />
    13 
    14     <!-- 视图解析器配置 -->
    15     <bean
    16         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    17         <!-- 前缀 -->
    18         <property name="prefix" value="/WEB-INF/page/" />
    19         <!-- 后缀 -->
    20         <property name="suffix" value=".jsp" />
    21     </bean>
    22 
    23     <!--将自定义时间转化器纳入Spring IOC容器 配置固定的 -->
    24     <!-- <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 
    25         <property name="converters"> <bean class="com.zhidi.util.DateFormat" /> </property> 
    26         </bean> -->
    27     <!-- 将自定义转换器纳入Spring IOC容器管理,在配置文件端改变时间格式 -->
    28     <bean id="conversionService"
    29         class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    30         <property name="converters">
    31             <bean class="com.zhidi.util.DateFormat1">
    32                 <property name="pattern" value="yyyy-MM-dd" />
    33             </bean>
    34         </property>
    35     </bean>
    36 
    37     <!-- 配置MultipartResolver文件上传 -->
    38     <bean id="multipartResolver"
    39         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    40         <property name="defaultEncoding" value="UTF-8" />
    41         <!-- 设置最大上传文件大小 -->
    42         <property name="maxUploadSize" value="5242880" />
    43     </bean>
    44 
    45     <!-- 注册验证工厂 -->
    46     <bean id="validator"
    47         class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    48         <!-- 适应hibernate验证 -->
    49         <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
    50         <!-- 如果不指定,会默认去找classpath下的validationMessage -->
    51         <property name="validationMessageSource" ref="messageSource" />
    52     </bean>
    53 
    54     <!-- 国际化消息文件 -->
    55     <bean id="messageSource"
    56         class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    57         <!-- 指定消息文件的路径,要在src下 -->
    58         <property name="basename" value="classpath:message" />
    59         <property name="defaultEncoding" value="UTF-8" />
    60         <property name="cacheSeconds" value="60" />
    61         <property name="useCodeAsDefaultMessage" value="false" />
    62     </bean>
    63 
    64     <!--方法一:简单异常从处理器 -->
    65     <!-- <bean
    66         class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    67         定义默认的异常处理页面
    68         <property name="defaultErrorView" value="error" />
    69         定义需要处理的异常 key用类名或完整的路径,异常页面作为值
    70         <property name="exceptionMappings">
    71             <props>
    72                 <prop key="java.lang.ArrayIndexOutOfBoundsException">error1</prop>
    73             </props>
    74         </property>
    75         定义用来获取异常信息的变量名 默认为 exception
    76         <property name="exceptionAttribute" value="ex"></property>
    77     </bean> -->
    78     
    79     <!-- 方法二:配置实现HandlerExceptionResolver接口的自定义异常处理器 -->
    80      <bean class="com.zhidi.util.ExceptionResolver"></bean> 
    81     
    82     <!--方法三: 通过注解来处理异常的配置 -->
    83     <!-- <bean class="com.zhidi.controller.TestExceptionController"></bean> -->
    84 </beans>
    View Code
     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3     xmlns="http://java.sun.com/xml/ns/javaee"
     4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     5     id="WebApp_ID" version="3.0">
     6     <!-- spring mvc前端控制器 -->
     7     <servlet>
     8         <servlet-name>springmvc</servlet-name>
     9         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    10         <!--如果没有设置参数,会在WEB-INF下查找前端控制器名-servlet.xml作为SpringMVC的默认配置文件 -->
    11         <init-param>
    12             <param-name>contextConfigLocation</param-name>
    13             <param-value>classpath:spring-mvc.xml</param-value>
    14         </init-param>
    15         <load-on-startup>1</load-on-startup>
    16     </servlet>
    17     <servlet-mapping>
    18         <servlet-name>springmvc</servlet-name>
    19         <url-pattern>*.do</url-pattern>
    20     </servlet-mapping>
    21 
    22     <!-- 异常处理 -->
    23     <error-page>
    24     <!-- 异常的状态 -->
    25     <error-code>404</error-code>
    26     <location>/exception.jsp</location>
    27     <!-- 异常的类型 -->
    28     <!--  <exception-type >java.lang.NullPiontException</exception-type>
    29      <location>/exception.jsp</location>
    30       -->
    31     </error-page>
    32    
    33 </web-app>
    View Code

    5.前端页面

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <%
     4     String path = request.getContextPath();
     5     String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
     6             + path + "/";
     7 %>
     8 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     9 <html>
    10 <script type="text/javascript" src="static/jquery/jquery.min.js"></script>
    11 <head>
    12 <base href="<%=basePath%>">
    13 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    14 <title>Insert title here</title>
    15 </head>
    16 <body>
    17     <button type="button" id="b1">点击</button>
    18     <script type="text/javascript">
    19         $("#b1").click(function() {
    20 
    21             $.ajax({
    22 
    23                 url : "ajax.do",
    24                 data : {},
    25                 dateType : "JSON",
    26                 type : "POST",
    27                 contentType : "application/json",
    28                 success : function(data) {
    29                     if (data.success) {
    30                         alert(data.msg);
    31                     } else {
    32                         alert(data.msg);
    33                     }
    34 
    35                 },
    36 
    37             });
    38 
    39         });
    40     </script>
    41 </body>
    42 </html>
    View Code
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10 <a href="/springmvc/downLoad2.do">文件下载</a>
    11 </body>
    12 </html>
    View Code
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10 ${stu.id }
    11 </body>
    12 </html>
    View Code
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
     4 <%
     5     String path = request.getContextPath();
     6     String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
     7             + path + "/";
     8 %>
     9 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    10 <html>
    11 <head>
    12 <base href="<%=basePath%>">
    13 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    14 <title>Insert title here</title>
    15 </head>
    16 
    17 ${error }
    18 <body>
    19     <form:form commandName="user">
    20         <form:errors path="name" />
    21         <form:errors path="password" />
    22         <form:errors path="email" />
    23 
    24     </form:form>
    25 </body>
    26 </html>
    View Code
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3     <%
     4     String path = request.getContextPath();
     5     String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
     6             + path + "/";%>
     7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     8 <html>
     9 <head>
    10 <base href="<%=basePath%>">
    11 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    12 <title>Insert title here</title>
    13 </head>
    14 <body>
    15 出错了
    16 </body>
    17 </html>
    View Code
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <%
     4     String path = request.getContextPath();
     5     String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
     6             + path + "/";
     7 %>
     8 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     9 <html>
    10 <head>
    11 <base href="<%=basePath%>">
    12 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    13 <title>Insert title here</title>
    14 </head>
    15 <script type="text/javascript" src="static/jquery/jquery.min.js"></script>
    16 <body>
    17     <button type="button" id="b1">点我哦,传JSON</button>
    18 
    19 </body>
    20 <script type="text/javascript">
    21     $("#b1")
    22             .click(
    23                     function() {
    24 
    25                         var data = '{"id":"1","userName":"admin","sex":"男","age":"33","date":"1992-2-3"}';
    26                         $.ajax({
    27 
    28                             url : "json.do",
    29                             data : data,
    30                             dateType : "JSON",
    31                             type : "POST",
    32                             contentType : "application/json",
    33                             success : function(data) {
    34                                 
    35                             },
    36 
    37                         });
    38 
    39                     });
    40 </script>
    41 </html>
    View Code
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10 <form action="/springmvc01/login.do" method="post">
    11 <input type="text" name="id"/><br>
    12 <input type="text" name="userName"><br>
    13 <input type="submit" value="提交">
    14 
    15 </form>
    16 </body>
    17 </html>
    View Code
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10 ${name }
    11 
    12 ${Student.id }
    13 </body>
    14 </html>
    View Code
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10 ${name }
    11 </body>
    12 </html>
    View Code
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10 杀驴逼
    11 ${student.userName}
    12 ${student.age }
    13 </body>
    14 </html>
    View Code
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10 成功!!!!
    11 异常信息为:<%=request.getAttribute("e") %>
    12 <img alt="" src="${path }">
    13 </body>
    14 </html>
    View Code
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10 <form action="/springmvc01/load.do" enctype="multipart/form-data" method="post">
    11 请选择文件:<input type="file" name="imgs"><br>
    12         <!--   <input type="file" name="imgs"><br> -->
    13 <input type="submit" value="上传文件">
    14 
    15 </form>
    16 </body>
    17 </html>
    View Code
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10 
    11 ${username}
    12 ${name}
    13 
    14 <form action="/springmvc01/user/hello8.do" method="post">
    15 序号:<input type="text" name="id"/><br/>
    16 姓名:<input type="text" name="userName"/><br/>
    17 性别:<input type="radio" value="0" name="sex">18      <input type="radio" value="1" name="sex">女<br/>
    19 年龄:<input type="text" name="age"/><br/>
    20 生日:<input type="text" name="date"><br/>
    21 <input type="submit" value="提交">
    22 
    23 </form>
    24 </body>
    25 
    26 </html>
    View Code
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3     <%
     4     String path = request.getContextPath();
     5     String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
     6             + path + "/";%>
     7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     8 <html>
     9 <head>
    10 <base href="<%=basePath%>">
    11 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    12 <title>Insert title here</title>
    13 </head>
    14 <body>
    15 出异常了
    16 </body>
    17 </html>
    View Code

    6.布局和导包

     

    二、

    1.controller

     1 package com.zhidi.controller;
     2 
     3 import javax.servlet.http.HttpServletRequest;
     4 import javax.servlet.http.HttpServletResponse;
     5 
     6 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
     7 
     8 import com.zhidi.entity.User;
     9 /*
    10  * 继承于HandlerInterceptorAdapter类的自定义拦截器
    11  */
    12 public class ExtendsInterceptor extends HandlerInterceptorAdapter {
    13 
    14     @Override
    15     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    16             throws Exception {
    17         
    18         User user= (User) request.getSession().getAttribute("user");
    19         if(user!=null)
    20         {
    21             System.out.println("----------登录成功--------");
    22             return true;
    23         }
    24         System.out.println("-------请先登录------");
    25         response.sendRedirect(request.getContextPath()+"/toLogin.do?msg=123");
    26         return false;
    27     }
    28 }
    View Code
     1 package com.zhidi.controller;
     2 
     3 import javax.servlet.http.HttpServletRequest;
     4 import javax.servlet.http.HttpServletResponse;
     5 
     6 import org.springframework.web.servlet.HandlerInterceptor;
     7 import org.springframework.web.servlet.ModelAndView;
     8 /*
     9  * 实现接口HandlerInterceptor的拦截器
    10  */
    11 public class ImpInterceptor implements HandlerInterceptor {
    12 
    13     @Override
    14     public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
    15             throws Exception {
    16         
    17     }
    18 
    19     @Override
    20     public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
    21             throws Exception {
    22         
    23     }
    24 
    25     @Override
    26     public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
    27         return false;
    28     }
    29 
    30 }
    View Code
     1 package com.zhidi.controller;
     2 
     3 import java.util.HashMap;
     4 import java.util.Map;
     5 
     6 import org.springframework.web.bind.annotation.RequestMapping;
     7 import org.springframework.web.bind.annotation.RestController;
     8 
     9 /*
    10  * RESTful风格的CRUB操作控制器
    11  */
    12 //@RestController是@Controller和@RequestBody的结合
    13 @RestController
    14 public class RestfulController {
    15     
    16     @RequestMapping("/rest")
    17     public Map<String, Object> rest()
    18     {
    19         Map map=new HashMap();
    20         return map;
    21     }
    22        
    23 }
    View Code
     1 package com.zhidi.controller;
     2 
     3 import javax.servlet.http.HttpSession;
     4 
     5 import org.springframework.stereotype.Controller;
     6 import org.springframework.web.bind.annotation.RequestMapping;
     7 import org.springframework.web.servlet.mvc.support.RedirectAttributes;
     8 
     9 import com.zhidi.entity.User;
    10 
    11 @Controller
    12 public class UserController {
    13 
    14     //去登录页面
    15     @RequestMapping("/toLogin")
    16     public String toLogin()
    17     {
    18         return "login";
    19     }
    20     
    21     //登录
    22     @RequestMapping("/login")
    23     public String login(User user,HttpSession session,RedirectAttributes attributes)
    24     {
    25         if(user!=null&&"admin".equals(user.getName())&&"123".equals(user.getPassword()))
    26         {
    27         
    28             return "success";
    29         }
    30         session.setAttribute("user", user);
    31         attributes.addFlashAttribute("msg","用户名或密码错误");
    32         return "redirect:toLogin.do";
    33     }
    34     
    35     //登出
    36     @RequestMapping("/logout")
    37     public String logout(HttpSession session)
    38     {
    39         session.invalidate();
    40         return "redirect:toLogin.do";
    41     }
    42     
    43     //测试
    44     @RequestMapping("/test")
    45     public String test()
    46     {
    47         return "success";
    48     }
    49 }
    View Code

    2.entity

     1 package com.zhidi.entity;
     2 
     3 public class User {
     4     
     5     private String name;
     6     private String password;
     7     public String getName() {
     8         return name;
     9     }
    10     public void setName(String name) {
    11         this.name = name;
    12     }
    13     public String getPassword() {
    14         return password;
    15     }
    16     public void setPassword(String password) {
    17         this.password = password;
    18     }
    19     
    20 
    21 }
    View Code

    3.配置文件

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
     4     xmlns:mvc="http://www.springframework.org/schema/mvc"
     5     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
     6         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
     7         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
     8     <!-- 扫描控制器所在的包 -->
     9     <context:component-scan base-package="com.zhidi.controller" />
    10     <!-- 开启springmvc注解 -->
    11     <mvc:annotation-driven></mvc:annotation-driven>
    12     <!-- 视图解析器配置 -->
    13     <bean
    14         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    15         <property name="prefix" value="/WEB-INF/page/" />
    16         <property name="suffix" value=".jsp" />
    17     </bean>
    18 
    19     <!-- 配置继承拦截器 -->
    20     <!-- <mvc:interceptors>
    21         定义在interceptors下的拦截器会对所有的请求进行拦截
    22         <bean class="com.zhidi.controller.Interceptor" />
    23         对特定的请求进行拦截
    24         <mvc:interceptor>
    25             拦截所有
    26             <mvc:mapping path="/**" />
    27             排除拦截
    28             <mvc:exclude-mapping path="/toLogin.do" />
    29             <mvc:exclude-mapping path="/login.do" />
    30             <bean class="com.zhidi.controller.ExtendsInterceptor" />
    31         </mvc:interceptor>
    32     </mvc:interceptors> -->
    33 
    34     <!-- 配置实现接口的拦截器 -->
    35     <!-- <mvc:interceptors>
    36         <bean class="com.zhidi.controller.ImpInterceptor" />
    37     </mvc:interceptors> -->
    38 </beans>
    View Code
     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <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">
     3  <!-- spring mvc前端控制器 -->
     4  
     5  <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
     6     <servlet>
     7         <servlet-name>springDispatcherServlet</servlet-name>
     8         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     9         <init-param>
    10             <param-name>contextConfigLocation</param-name>
    11             <param-value>classpath:spring-mvc.xml</param-value>
    12         </init-param>
    13         <load-on-startup>1</load-on-startup>
    14     </servlet>
    15 
    16     <!-- Map all requests to the DispatcherServlet for handling -->
    17     <servlet-mapping>
    18         <servlet-name>springDispatcherServlet</servlet-name>
    19         <url-pattern>*.do</url-pattern>
    20     </servlet-mapping>
    21  
    22 
    23 </web-app>
    View Code

    4.前端页面

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3     <%
     4     String path = request.getContextPath();
     5     String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
     6             + path + "/";%>
     7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     8 <html>
     9 <head>
    10 <base href="<%=basePath%>">
    11 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    12 <title>Insert title here</title>
    13 </head>
    14 <body>
    15 ${param.msg }
    16 ${msg }
    17 <form action="login.do" method="post">
    18 用户名:<input type="text" name="name"><br>
    19 密   码:<input type="password" name="password"><br>
    20 <button type="submit">登录</button>
    21 </form>
    22 </body>
    23 </html>
    View Code
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3     <%
     4     String path = request.getContextPath();
     5     String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
     6             + path + "/";%>
     7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     8 <html>
     9 <head>
    10 <base href="<%=basePath%>">
    11 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    12 <title>Insert title here</title>
    13 </head>
    14 <body>
    15 成功!!!
    16 </body>
    17 </html>
    View Code

  • 相关阅读:
    用自己的算法实现startsWith和endsWith功能
    随机生成4位验证码,由用户输入并验证是否输入正确,如果输入错误就生成新的验证码让用户重新输入,最多输入5次
    二分法(网上查找结果)
    模拟摇奖:从1-36中随机抽出8个不重复的数字
    冒泡排序
    输入年龄输出年龄段
    水仙花数
    百钱买百鸡
    百马百担的问题
    控制台输出九九乘法表
  • 原文地址:https://www.cnblogs.com/zclqian/p/7511803.html
Copyright © 2020-2023  润新知