首页 > 技术文章 > SpringMVC补充

wxbblogs 2017-08-01 16:14 原文

1.URL模板映射  2.@requestParam参数传递  3.转发和重定向  4.json数据处理

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>    
  <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>
  <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:springmvc.xml</param-value>
      </init-param>
  </servlet>
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

URL模板映射

普通带参:localhost:8080/springmvcpj/user/deleteUser.do?id=2

REST风格:localhost:8080/springmvcpj/user/deleteUser/2

@requestParam参数传递

value的值必须和表单input的name属性值一样
required:true 必须传参,否则就报400错误

user.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <a href="${pageContext.request.contextPath}/re/delUser/3/admin.do">删除</a><br/>
    
    <form action="${pageContext.request.contextPath}/re/addUser.do">
        用户名:<input name="name"/><br/>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

cn.bdqn.controller.RestController.java

package cn.bdqn.controller;

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;

@Controller
@RequestMapping("/re")
public class RestController {
    @RequestMapping("/delUser/{uid}/{uname}")
    public String delUser(@PathVariable Integer uid,@PathVariable String uname){
        System.out.println("删除"+uid+"的用户");
        System.out.println(uname);
        return "index";
    }
    @RequestMapping("addUser")
    //value的值必须和表单input的name属性值一样
    public String addUser(@RequestParam(value="name",required=false) String uname){  //required属性 true 必须传参,否则就报400错误
        System.out.println(uname);
        return "index";
    }
}

index.jsp

  <body>
        ${age}
  </body>

转发和重定向

springMVC跳转页面默认是转发

转发也可写作 "forward:/index.jsp";

重定向:

@RequestMapping("/setAtr")
public String setAtr(HttpServletRequest request){
request.setAttribute("age", 15);
return "redirect:/index.jsp";  //重定向至index.jsp页面
}

json数据处理

spingmvc添加json支持(jackson) jar文件

jackson-core-asl-1.9.11.jar

jackson-mapper-asl-1.9.11.jar

@RequestBody接受前台json数据,把json数据自动封装javaBean。@responseBody把后台pojo转换json对象,返回到页面。

ajaxJson.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script>
</head>
<body>
    <h4>发送json和响应json</h4>
    <input type="button" id="btn" value="点击"/>
    
    <script type="text/javascript">
        $(function(){
            var jsonData = JSON.stringify({"uid":101,"uname":"李四","age":15}); //JSON.stringify 将json对象转为字符串形式
            $("#btn").click(function(){
                $.ajax({
                    type:"post",
                    url:"${pageContext.request.contextPath}/json/getJsonBean.do",
                    contentType:"application/json;charset=UTF-8",
                    data:jsonData,
                    success:function(repData){
                        alert(repData);
                    }
                });
            });
        });
    </script>
</body>
</html>

/getJsonBean.do

@Controller
@RequestMapping("/json")
public class JsonController {
    @RequestMapping("getJsonBean")
    //@responseBody把后台pojo转换json对象,返回到页面
    public @ResponseBody User getJsonBean(@RequestBody User user){ //@RequestBody接受前台json数据,把json数据自动封装javaBean
        System.out.println(user);
        return user;
    }

 

推荐阅读