发表于: 2020-05-29 23:10:39

1 1617


今天完成的事情:SpringMVC数据绑定,解决中文乱码,ModelAndview的用法
明天计划的事情:实现接口文档,用Json Tag-lib生成假数据,用日志记录并运用Jetty
遇到的问题:
解决tomcat启动时的中文乱码问题

在Tomcat安装目录的conf中打开logging.properties ,打开后大约在50行左右找到java.util.logging.ConsoleHandler.encoding = UTF-8,修改为java.util.logging.ConsoleHandler.encoding = GBK;

收获:

Spring MVC

1.数据绑定(URL Mapping)

URL Mapping是指将url 与Controller方法绑定,SpringMVC就可以通过Tomcat对外进行暴露服务了

URL Mapping 注解 

@GetMapping 绑定Get请求    @PostMapping  绑定Post请求       @RequestMapping  通用绑定

@GetMapping("/get")
@ResponseBody
public String getMapping(){
   return "This is get method!";
}
@PostMapping("/post")
@ResponseBody
public String postMapping(){
   return "This is post method!";
}

出现了405问题,对应是请求的类型出错。post是提交请求。可以写个表单等有提交内容的给post请求


@RequestMapping  通用绑定

@Controller
@RequestMapping("/school")//作用在类上就是该类全局的url地址
public class URLMappingController {
//    @GetMapping("/get")
   @RequestMapping("/get")//作用在方法上就是无论是get还是post都可以接收
   @ResponseBody
   public String getMapping(){
       return "This is get method!";
   }

2.接受请求参数(当登录模块有用户名和密码以及当用户注册会有诸多详细内容都需要传递诸多参数),有两种方法接受

1)使用Controller方法参数接受,当传递的参数和Controller内接受的命名不一样时候,可以用下面get请求的@RequestParam("页面参数")

@Controller
public class URLMappingController {
   
   @GetMapping("/get")
   @ResponseBody
   public String getMapping(@RequestParam("User_name") String username,Long password){
       return "This is RequestMapping method!";
   }
   @PostMapping("/post")
   @ResponseBody
   public String postMapping(String username,Long password){
       return "This is post method!";
   }
}

2)使用Java Bean接受数据    (直接省下了手动实体类创建,以及参数的动态注入)

直接新建一个实体类,然后属性要和前台页面传递的参数名字一样,不然接受不到。

<html>
<body>
//默认的首页index.html
<form action="/post" method="post">
   <input name="username"><br/>
   <input name="password"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
@PostMapping("/post")
@ResponseBody
public String postMapping(User user){
   System.out.println(user.getUsername() + ":" + user.getPassword());
   return "This is post method!";
}

3. 复合数据的传递

URl绝对路径和相对路径

<form action=”./apply” method=”post”> 

当前页面地址:  http://localhost:8080/[上下问路径]/form.html 

表单提交地址:  http://localhost:8080/[上下文路径]/apply           地址/在前面都为绝对路径,./为当前路径


1).利用数组或者List接受请求中的复合数据

@PostMapping("/post2")
@ResponseBody
public void postMappingsArry(String name,Integer[] number){
}
@PostMapping("/post3")
@ResponseBody
public void postMappingList(String name, @RequestParam List<Integer> number){
}

2)  .利用RequestParam为参数设置默认值,就是当传过来的是空值时,可以设置默认值

@PostMapping("/post4")
@ResponseBody
public void postMappingsRequest(@RequestParam(value = "n",defaultValue = "Anun") String name,Integer number){
}

3) .使用Map对象接受请求参数及注意事项

@PostMapping("/post5")
@ResponseBody
public void postMappingMap(@RequestParam Map map){
}

---当使用List和Map时候都要在前面加@RequestParam

---Map接受复合数据类型,只会保留第一个数据

---当使用实体类接受参数可以配合List一起使用,list写在实体类中

---如果接受复合数据 可以使用数组接受,也可以使用List集合接受,Map数据类型只能接受单个数据,形成Key - Value的形式


4.关联对象参数接收(实体类a的属性是一个对象b)

这种情况,在页面的表单中有个对象b的属性name,那么就要写成b.name传递到a中

5. 日期的转换

@DateTimeFormat();指定特定规则的日期格式,加在类的属性上也能生效

@PostMapping("/post")
@ResponseBody
public String getMapping(@DateTimeFormat(pattern = "yyyy-MM-dd") Date createTime){
   System.out.println(createTime);
   return "This is DateTimeFormat method!";
}

如果让全局都能日期格式正确,可以建一个日期转换类

1). 自定义一个MyDateConverter时间转换类

public class MyDateConverter implements Converter<String ,Date> {
   @Override
   public Date convert(String s) {
       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
       try {
           Date d = format.parse(s);
           return d;
       } catch (ParseException e) {
           return null;
       }
   }

2)在applicationContext中定义该类的bean

<!--启动mvc注解开发模式 并且开启日期转换器-->
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
   <property name="converters">
       <set>
           <bean class="com.hyx.springmvc.converter.MyDateConverter"></bean>
       </set>
   </property>
</bean>
@GetMapping("/get")
@ResponseBody
public String getMapping(Date createTime){
   System.out.println(createTime);
   return "This is get method!";
}

控制台输出


6.中文乱码(Tomcat中默认使用字符集ISO-8859-1 西欧字符集)需要转换为UTF-8,Controller中请求与响应都需要设置UTF-8字符集

1) Get请求乱码---修改server.xml,位置在tomcat安装目录的/conf/server.xml   ,tomcat8以上版本不用设置,默认就是

 2)Post请求乱码---web.xml配置CharacterEncodingFilter

<!--定义post请求为UTF-8字符集-->
<filter>
 <filter-name>characterFilter</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>characterFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>

3) Response响应乱码---Spring配置StringHttpMessageConverter

<!--启动mvc注解开发模式 并且开启日期转换器-->
<mvc:annotation-driven conversion-service="conversionService">
   <!--设置响应字符集-->
   <mvc:message-converters>
       <bean class="org.springframework.http.converter.StringHttpMessageConverter">
           <property name="supportedMediaTypes">
               <list>
                   <!--类似于response.setContentType("text/html;charset=utf-8")-->
                   <value>text/html;charset=utf-8</value>
               </list>
           </property>
       </bean>
   </mvc:message-converters>
</mvc:annotation-driven>

7.响应输出结果内容  @ResponseBody 和ModelAndView对象的用法

1)@ResponseBody 

@ResponseBody直接产生响应体的数据,过程不涉及任何视图,可产生标准字符串/JSON/XML等格式数据 ,@ResponseBody(产生字符)被StringHttpMessageConverter(配置响应中文乱码)所影响


2)ModelAndView  "模型(数据)"与"视图(界面)"对象,ModeAndView将数据与视图进行绑定,同时完成了解耦

mav.addObject()方法设置的属性默认存放在当前请求中 

默认ModelAndView使用请求转发(forward)至页面 

@GetMapping("/view")
public ModelAndView view(String username,Long password){
   ModelAndView model = new ModelAndView("/view.jsp");//默认请求转发
   User user = new User();
   user.setUsername(username);
   user.setPassword(password);
   //mav.addObject()方法设置的属性默认存放在当前请求中
   model.addObject("u",user);
   return model;
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>抬头</title>
</head>
<body>
<h1>这是一个页面!</h1><hr>
<h3>Username:${u.username}</h3><hr>
<h3>Password:${u.password}</h3>
</body>
</html>

重定向使用 new ModelAndView("redirect:/index.jsp")重定向就是两次提交,所以url发生了变化

3) .其他应用的场景,不使用ModelAndView的时候,直接返回String类型和使用ModelMap处理数据


RESTful

1. 开发规范

1)使用URL作为用户交互入口 2)明确的语义规范(GET|POST|PUT|DELETE) 3)只返回数据(JSON|XML),不包含任何展现

2. 命名要求





返回列表 返回列表
评论

    分享到