zoukankan      html  css  js  c++  java
  • 使用SMM框架开发企业级应用-----MVC参数传递

    处理乱码
    关于页面传值到后台和后台传值到页面,首先要解决的是中文乱码

    post乱码
    在web.xml中加入过滤器

    <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>
    get乱码
    有两种处理方法

      第一种

    修改tomcat配置文件添加编码与工程编码一致,要修改的配置文件在

    第二种

    对参数进行重新编码

    String userName=new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8");
    ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码

    此时后台获取到的userName是经过ISO8859-1编码过的。现在需要做的是按照ISO8859-1的编码方式把userName再变成最原始的字节码(即刚从浏览器端传过来的东西,没有经过编码过的),然后再把这个字节码通过utf-8的方式进行编码。
     

    SpringMVC参数之间的传递主要有这两种 需求

    在Controller接收从jsp传递过来的数据
    将Controller的数据传递到jsp页面
    在Controller接收从jsp传递过来的数据
    首先解决中文乱码,在web.xml文件中配置

    <filter>
    <filter-name>encoding</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>encoding</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
     1、 基本数据类型:
      1.1 jsp代码:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>添加用户</title>
    </head>
    <body>
    <form action="addUser" method="post">
    姓名<input type="text" name="name"/><br>
    性别<input type="text" name="age"/><br>
    <input type="submit" value="提交"/>
    </form>
    </body>
    </html>
    1.2 controller代码

    package com.example.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;

    @Controller
    public class UserController {

    @RequestMapping("/addUser")
    public String addUser(String name,int age){
    System.out.println("用户名:" +name+" 年龄"+age);
    return "main.jsp";
    }
    }
    注意:默认保证参数名称和请求中传递的参数名相同

          但是,有些情况下,前端代码是由前端设计师设计,参数名不对应,则使用@RequestParam()赋值,

    package com.example.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;

    @Controller
    public class UserController {
    @RequestMapping("/addUser")
    public String addUser(@RequestParam(value="name1")String name,@RequestParam(value="age1")int age){
    System.out.println("用户名:" +name+" 年龄"+age);
    return "main.jsp";

    }
    }
    如果方法参数是基本数据类型( 不是封装类) 可以通过@RequestParam 设置默认值.防止没有参数报500错误

    package com.example.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;

    @Controller
    public class UserController {
    @RequestMapping("/addUser")
    public String addUser(@RequestParam(defaultValue="韩信")String name,@RequestParam(defaultValue="22")int age){
    System.out.println("用户名:" +name+" 年龄"+age);
    return "main.jsp";

    }
    }
    如果强制要求必须有某个参数

    package com.example.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;

    @Controller
    public class UserController {
    @RequestMapping("/addUser")
    public String addUser(@RequestParam(required=true)String name,@RequestParam(required=true)int age){
    System.out.println("用户名:" +name+" 年龄"+age);
    return "main.jsp";

    }
    }
    2、对象类型
    2.1 jsp代码同上

    2.2 创建对象类

    package com.example.entity;
    public class UserEntity {
    private String name;
    private int age;

    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }
    @Override
    public String toString() {
    return "UserEntity [name=" + name + ", age=" + age + "]";
    }
    }
    2.3 controller代码

    package com.example.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import com.example.entity.UserEntity;
    @Controller
    public class UserController {
    @RequestMapping("/addUser")
    public String addUser(UserEntity entity){
    System.out.println("用户:" +entity);
    return "main.jsp";
    }
    }
    注意:前台传递的参数名与对象的属性名一致,且生成get与set方法

    3、请求参数中包含多个同名参数的获取方式
    页面代码

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>添加用户</title>
    </head>
    <body>
    <form action="addUser" method="post">
    姓名<input type="text" name="name"/><br>
    性别<input type="text" name="age"/><br>
    兴趣爱好
    <input type="checkbox" name="interest" value="读书">
    <input type="checkbox" name="interest" value="记笔记"/>
    <input type="checkbox" name="interest" value="背单词"/>
    <input type="submit" value="提交"/>
    </form>
    </body>
    </html>
    两种方式:

        第一、兴趣爱好也包含在对象中,在对象中用集合或者数组的形式声明,对象类:

    package com.example.entity;

    import java.util.Arrays;
    import java.util.Date;

    public class UserEntity {

    private String name;
    private int age;
    private String[] interest;
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }
    public String[] getInterest() {
    return interest;
    }
    public void setInterest(String[] interest) {
    this.interest = interest;
    }
    @Override
    public String toString() {
    return "UserEntity [name=" + name + ", age=" + age + ", interest=" + Arrays.toString(interest) + "]";
    }
    }
    控制器类:

      

    package com.example.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;

    import com.example.entity.UserEntity;

    @Controller
    public class UserController {

    @RequestMapping("addUser")
    public String addUser(UserEntity userEntity){
    System.out.println(userEntity);
    return "main.jsp";
    }
    }
    第二种:

    package com.example.controller;

    import java.util.List;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;

    import com.example.entity.UserEntity;

    @Controller
    public class UserController {

    @RequestMapping("addUser")
    public String addUser(String name,int age,@RequestParam("interest")List<String> list){
    System.out.println(name+" "+age+" "+list);
    return "main.jsp";

    }
    }
    4、请求参数中对象.属性格式
    页面代码

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>添加用户</title>
    </head>
    <body>
    <form action="addUser" method="post">
    姓名<input type="text" name="user.name"/><br>
    性别<input type="text" name="user.age"/><br>
    <input type="submit" value="提交"/>
    </form>
    </body>
    </html>
    实体类

    package com.example.entity;

    public class User {

    private String name;
    private int age;
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }
    @Override
    public String toString() {
    return "User [name=" + name + ", age=" + age + "]";
    }

    }
    应用类

    对象名和参数中点前面的名称对应,点后面的名称与User中的属性名对应

    package com.example.entity;

    import java.util.Arrays;
    import java.util.Date;

    public class UserEntity {

    private User user;

    public User getUser() {
    return user;
    }

    public void setUser(User user) {
    this.user = user;
    }

    @Override
    public String toString() {
    return "UserEntity [user=" + user + "]";
    }

    }
    控制器

    package com.example.controller;

    import java.util.List;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;

    import com.example.entity.UserEntity;

    @Controller
    public class UserController {

    @RequestMapping("addUser")
    public String addUser(UserEntity userEntity){
    System.out.println(userEntity);
    return "main.jsp";

    }
    }
    5、在请求参数中传递集合对象类型参数
    页面代码

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>添加用户</title>
    </head>
    <body>
    <form action="addUser" method="post">
    姓名<input type="text" name="user[0].name"/><br>
    性别<input type="text" name="user[0].age"/><br>
    姓名1<input type="text" name="user[1].name"/><br>
    性别1<input type="text" name="user[1].age"/><br>
    <input type="submit" value="提交"/>
    </form>
    </body>
    </html>
    应用类

    package com.example.entity;

    import java.util.Arrays;
    import java.util.Date;
    import java.util.List;

    public class UserEntity {

    private List<User> user;
    public List<User> getUser() {
    return user;
    }
    public void setUser(List<User> user) {
    this.user = user;
    }
    @Override
    public String toString() {
    return "UserEntity [user=" + user + "]";
    }
    }
    6、日期类型传值
       springMVC没有提供默认的对日期类型的绑定,需要自定义日期类型的绑定。

    第一种

    如果查询类使我们自己写,那么在属性前面加上@DateTimeFormat(pattern = "yyyy-MM-dd")  ,即可将String转换为Date类型,如下

    public class UserController{

    @RequestMapping("addUser")
    public String addUser(@DateTimeFormat(pattern="yyyy-MM-dd")Date date){
    String simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd").format(date);
    System.out.println(simpleDateFormat);
    return "main.jsp";
    }
    }
    第二种   

    如果我们只负责web层的开发,就只需要在controller中加入数据绑定:

    public class UserController{

    @RequestMapping("addUser")
    public String addUser(Date date){
    String simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd").format(date);
    System.out.println(simpleDateFormat);
    return "main.jsp";
    }
    @InitBinder
    public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
    }
    第三种

    可以在系统中加入一个全局类型转换器

    建立一个CustomDateConverter .java类

    public class CustomDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);
    try {
    return dateFormat.parse(source);
    } catch (ParseException e) {
    e.printStackTrace();
    }
    return null;
    }
    在springmvc.xml中配置

    <!-- 配置注解驱动 -->
    <mvc:annotation-driven conversion-service="conversionService"/>
    <!-- 转换器 -->
    <bean id="conversionService"
    class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
    <list>
    <bean class="com.example.controller.CustomDateConverter"/>
    </list>
    </property>
    </bean>
    控制器类

    @Controller
    public class UserController{
    @RequestMapping("addUser")
    public String addUser(Date date){
    String simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd").format(date);
    System.out.println(simpleDateFormat);
    return "main.jsp";
    }
    }
    配置转换类去除空格
    还可以配置一个转换类,把通过http请求传过来的字符串的两边去除空格。

    public class StringTrimConverter implements Converter<String,String>{

    @Override
    public String convert(String source) {
    try {
    //去掉字符串两边的空格,如果去除后为空设置为null
    if (source!=null) {
    source=source.trim();
    if (source.equals("")) {
    return null;
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    return source;
    }
    }
    在springmvc.xml中配置

    <!-- 转换器 -->
    <bean id="conversionService"
    class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
    <list>
    <bean class="cn.itcast.springmvc.first.converter.CustomDateConverter"/>
    <bean class="cn.itcast.springmvc.first.converter.StringTrimConverter"/>
    </list>
    </property>
    </bean>
    7、restful 传值方式
    一般情况传递参数的形式是<a hidden="addUser?name=张三&age=22">登录</a>

    restful 传值方式可以简化 jsp 中参数编写格式,在 jsp 中设定特定的格式

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>添加用户</title>
    </head>
    <body>
    <a href="addUser?name=abc&age=22">登录</a>
    <a href="addUser1/abc/22">登录1</a>
    </body>
    </html>
    登录1的href是一个标准的控制器格式,

    在控制器中

    package com.example.controller;

    import java.util.List;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;

    import com.example.entity.UserEntity;

    @Controller
    public class UserController {

    @RequestMapping("addUser")
    public String addUser(String name,int age){
    System.out.println(name+" "+age);
    return "main.jsp";
    }
    @RequestMapping("addUser1/{name1}/{age}")
    public String addUser1(@PathVariable("name1") String name,@PathVariable int age){
    System.out.println(name+" "+age);
    return "main.jsp";

    }
    }
    使用restful 传值方式:

    在@RequestMapping 中一定要和请求格式对应
    {名称} 中名称自定义名称
    @PathVariable 获取@RequestMapping 中内容,默认按照方法参数名称去寻找
    在浏览器点击登录1效果如下:

    这个404是在控制器执行完跳转提示在该地址下找不到main.jsp

    原因是控制器在跳转页面时没有找到对应的页面,

    所有应该改为全路径return "/main.jsp"

  • 相关阅读:
    新建txt文件新增内容并打印出
    使用 universalimageloader 缓存图片的配置类及使用方法
    Android 一个Activity 里面放置多个 Fragment 实现点击切换的Tab 页面效果
    Vuejs学习笔记(一)
    opencv3 学习笔记(二)
    opencv3 学习笔记(一)
    python 3.6 + numpy + matplotlib + opencv + scipy 安装
    MUI + Spring MVC 实现多图片上传
    maven 构建spring boot + mysql 的基础项目
    Git 基本命令行操作
  • 原文地址:https://www.cnblogs.com/haohanwuyin/p/11839158.html
Copyright © 2011-2022 走看看