springmvc学习日志二

一、当接受的参数为日期类型时

 1.建立jsp页面,向Controller类传入参数

1.1当传入的参数为单个时

<body>    
    <form action="user/toDate.do" method="post">
        生日:<input type="date" name="date" /><br>
        <input type="submit" value="提交"/>
    </form>
    
</body>

1.2当传入的参数为多个时

<body>

    <form action="user/register.do" method="post">
        姓名:<input type="text" name="name" /><br>
        年龄:<input type="text" name="age" /><br>
        生日:<input type="date" name="birthday" /><br>  //这里name中的值要与实体类中的属性名相同
        <input type="submit" value="提交"/>
    </form>
    
</body>

2.在Controller类中接受传入的日期类型的参数

2.1当只传入单个参数时

@Controller
@RequestMapping("/user") 
public class MyController1 {
    
    //当参数为单个日期参数时
    @RequestMapping("/toDate.do")
    public String toDate(Date date) { //参数一定要和请求的参数名相同
        System.out.println(date);
        return "login";//默认请求转发到login页面
    }

    //当参数为日期类型时
    //1.使用initBinds 当你接受的参数为日期类型时先经过该方法进行处理。只能接受单个参数
    @InitBinder
   public void initBinder(ServletRequestDataBinder binder){
        //只要网页中传来的数据格式为yyyy-MM-dd 就会转化为Date类型
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),
              true));
    }
}

2.2当要传入多个参数时

public class User {
      private String name;
      private String password;
      private int age;
      private String sex;
      private String address;
      private String phone;
     @DateTimeFormat(pattern="yyyy-MM-dd")  //不是输出的结果格式。是接受参数的格式
     private Date birthday;
}      
@Controller
@RequestMapping("/user") 
public class MyController1 {
    
    @RequestMapping("/register.do")
    public String register(User user) {
        System.out.println(user);  //请求的参数名要和实体类中的属性名相同
        return "login";
    }

}

3.跳转转发的页面

<body>
========login
欢迎登录
</body>

二、在Controller进行数据保存

 2.1数据保存到request作用域中的方式

1.使用ModelAndView,那么该方法的返回类型必须是ModelAndView

//可以保存到ModelAndView,那么方法的返回值必须是ModelAndView
    @RequestMapping("/login1.do") //RequestMapping:表示的就是你的访问地址
    public ModelAndView list() { //参数一定要和请求的参数名相同
        ModelAndView mv=new ModelAndView("login");
        mv.addObject("name","张三");
        return mv;
    }

2.使用Model,方法的返回值还是字符串

//保存到Model中,方法的返回值还可以是字符串
    @RequestMapping("/login2.do") 
    public String list(Model model) { 
        model.addAttribute("address","李四");
        return "login";
    }

3.使用Map,方法的返回值还是字符串

//保存到Map中
    @RequestMapping("/login3.do") 
    public String list(Map<String,Object> map) { 
        map.put("name1","王五");
        return "login";
    }

4.原始的HttpServletRequest对象保存

@RequestMapping("/login5.do") 
    public String list(HttpServletRequest request) { 
        //用原始的HttpServletRequest对象保存
        request.setAttribute("name","赵六");
        return "login";
    }

2.2数据保存到session作用域中的方式

1.使用原始的HttpSession保存

//保存到原始的HttpSession对象中
    @RequestMapping("/login4.do") 
    public String list(HttpSession session) { 
        session.setAttribute("name","钱七");
        return "login";
    }

2.使用注解@SessionAttributes(names={key1,key2})

@Controller
@RequestMapping("/user") 
@SessionAttributes(names= {"name1","address"}) //键名叫:name保存的作用域为session
public class MyController2 {

}

三、静态资源的映射关系

创建jsp页面,显示静态图片

<body>
 <img alt="动态漫画" src="/springmvc2/img/bb4.gif"/>
</body>

在web.xml配置文件中

1.第一种情况时,以上的图片可正常显示

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>springmvc2</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>
  
    <filter>
         <filter-name>CharacterEncodingFilter</filter-name>
         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
         <init-param>
                 <param-name>encoding</param-name>
                 <param-value>UTF-8</param-value>
         </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!-- 容器启动时加载springmvc的配置文件, 删除的话就是在访问时加载配置文件, 最好不要删可提高效率 -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
<!--         只有后缀为do才经过DispatcherServlet -->
      <url-pattern>*.do</url-pattern> 

    </servlet-mapping>
</web-app>

2.第二种情况,图片不可以正常显示

<servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!-- 容器启动时加载springmvc的配置文件, 删除的话就是在访问时加载配置文件, 最好不要删可提高效率 -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
<!--         /表示任何请求都要经过DispatcherServlet -->
            <url-pattern>/</url-pattern>
    </servlet-mapping>

3.解决第二种情况,在springmvc的配置文件中添加如下代码

<!-- 静态资源的释放 -->
    <mvc:default-servlet-handler/>

四、SpringMVC完成Ajax功能。

1.Jquery中ajax使用的几种方式

Jquery: 
   $.get(url,data,callback,type);
Url:服务器的路径
Data: 请求参数
Callback: 回调函数
Type: 响应数据的类型。 (html, json)
  $.post(url,data,callback,type);
  
  $.ajax({
     Url:
     Data:
     Type:
     Success:
     Error:
     Async:是否异步
     dataType:     
});

2.在SpringMVC使用ajax要加入jackson的jar包

springmvc学习日志二

 3.在响应的方法上加上@ResponseBody :java对象转化为json对象。方法的返回值可以是对象、集合、字符串

@Controller
@RequestMapping("ajax")
public class AjaxController {
     
    @RequestMapping(value="Ajax1",produces="text/html;charset='UTF-8'")
    @ResponseBody //1.把hello作为内容响应给客户了
    public String ajax1(String name) {
        System.out.println(name);
        return "张三";//表达的是把这个hello作为内容返回给回调函数,类似于out.print("hello")
    }
    @RequestMapping("Ajax2")
    @ResponseBody //2.把java对象转化为json对象  需要使用jackson的jar包
    public User ajax2(String name) {
        User user=new User("张三","123456",20);
        return user;
    }
    @RequestMapping("Ajax3")
    @ResponseBody //2.把java对象转化为json对象  需要使用jackson的jar包
    public List<User> ajax3(String name) {
        User user1=new User("张三1","123456",20);
        User user2=new User("张三2","123456",20);
        User user3=new User("张三3","123456",20);
        List<User> user=new ArrayList<User>();
        user.add(user1);
        user.add(user2);
        user.add(user3);
        return user;
    }
}

五、当Ajax返回的为字符串,且字符串中含有汉字,那么就会出现字符乱码

1.第一种解决方法

@Controller
@RequestMapping("ajax")
public class AjaxController {
 //当出现乱码时    
//在@RequestMapping中添加属性produces
@RequestMapping(value="Ajax1",produces="text/html;charset='UTF-8'")
    @ResponseBody //1.把hello作为内容响应给客户了
    public String ajax1(String name) {
        System.out.println(name);
        return "张三";//表达的是把这个hello作为内容返回给回调函数,类似于out.print("hello")
    }
}

2.第二种在springmvc的配置文件中添加如下代码

<!-- 2.开启注解驱动AnnotationHandlerMapping  设置字符编码-->
    <mvc:annotation-driven>
<!-- 当出现乱码时 --> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <!-- 通过构造方法给该类属性赋值 index表示构造方法的第一个参数。value第一个参数的值 --> <constructor-arg index="0" value="utf-8"></constructor-arg> </bean> </mvc:message-converters> </mvc:annotation-driven>