SpringMVC详解

1.概述:SpringMVC是spring提供给Web应用的框架设计。MVC设计的首要问题时解耦各个模块。其最大的特点是结构松散,比如几乎可以在SpringMVC中使用各类视图,包括JSON、JSP、XML、PDF等,所以他能够满足手机端 、页面端和平板电脑端的各类需求,这就是现在他如此流行的原因。

2.springmvc引入-->《Spring MVC初步认识》

3.获取请求参数
涉及springmvc中的 =====获取参数、 更改请求路径 、json传参、 ajax、表单序列化、 json视图=====
===============自己累积代码使用,可读性差================

<%@ 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>
<form action="login/ulogin.do" method="post">
<input type="text" name="userName"/>
<input type="text" name="pwd"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>

springmvc配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<!-- 启用Springmvc注解驱动 -->
<mvc:annotation-driven />
<!-- 配置扫描注解的包 -->
<context:component-scan base-package="com.begin21"></context:component-scan>

<!-- 定义视图解析器,如下找到/WEB-INF目录,其中文件以jsp作为后缀的文件作为映射 -->
<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>

web.xml配置文件:

 <?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>Springmvc</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>

<servlet>
    <servlet-name>ds</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 应用启动时,加载servlet -->
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<!-- 约定优于配置,  Spring MVC框架默认加载/WEB-INF/<servlet-name/>开头-servlet.xml作为配置文件载入Web工程中-->
    <servlet-name>ds</servlet-name>
    <!-- 拦截配置 -->
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

</web-app>

Controller.java

package com.begin21.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.begin21.pojo.User;
import com.begin21.pojo.UserParams;

@Controller
@RequestMapping(value="login")
public class LoginController  {
@RequestMapping(value="login",method=RequestMethod.POST)
public ModelAndView login(){
    //执行页面跳转操作 form'表单信息获取
    //。。。。。
    
    return new ModelAndView("jsp/t");
}

@RequestMapping(value="ulogin",method=RequestMethod.POST)
public ModelAndView userLogin(HttpSession session,HttpServletRequest request){
    
    String userName = request.getParameter("userName");
    String pwd = request.getParameter("pwd");
    
    session.setAttribute("user",userName);
    session.setAttribute("pwd",pwd);
    ModelAndView mv = new ModelAndView();
    mv.setViewName("jsp/tulogin");
    return mv;
}

@RequestMapping(value="param2", method=RequestMethod.POST)
public ModelAndView param2(String userName, String pwd) {
    System.out.println(userName + ", " + pwd);
    
    ModelAndView mv = new ModelAndView();
    mv.setViewName("test");
    return mv;
}

@RequestMapping(value="param3", method=RequestMethod.POST)
public ModelAndView param2(UserParams up) {
    
    System.out.println("==================");
    
    System.out.println(up.getUserName()+ ", " + up.getPwd());
    ModelAndView mv = new ModelAndView();
    mv.setViewName("test");
    return mv;
}

@RequestMapping(value="param4", method=RequestMethod.GET)
public ModelAndView param4(@RequestParam(value="new",defaultValue="100") Integer id) {
    
    System.out.println("==================");
    
    System.out.println("ID = " + id);
    
    ModelAndView mv = new ModelAndView();
    mv.setViewName("jsp/param4_t");
    return mv;
}

@RequestMapping(value="param5", method=RequestMethod.POST)
public ModelAndView param5(@RequestParam(value="user_name") String userName, String pwd) {
    System.out.println(userName + ", " + pwd);
    ModelAndView mv = new ModelAndView();
    mv.setViewName("jsp/param4_t");
    return mv;
}



/*@RequestMapping(value="param8")
public ModelAndView param8(@RequestBody List<UserParam> userList) {
    System.out.println(userList.get(1));
    ModelAndView mv = new ModelAndView();
    mv.setViewName("jsp/param4_t");
    return mv;
}*/

@RequestMapping(value="param7")
public ModelAndView param7(@RequestBody UserParams up) {
    System.out.println(up.getUserName());
    System.out.println(up.getPageParams().getLimit());
    ModelAndView mv = new ModelAndView();
    mv.setViewName("test");
    return mv;
}

@RequestMapping(value="param8")
public ModelAndView param8(@RequestBody List<Integer> listId) {
    System.out.println(listId.size());
    System.out.println(listId.get(1));
    ModelAndView mv = new ModelAndView();
    mv.setViewName("test");
    return mv;
}

@RequestMapping(value="param9")
public ModelAndView param9(@RequestBody List<UserParams> listUser) {
    System.out.println(listUser.get(1));
    ModelAndView mv = new ModelAndView();
    mv.setViewName("test");
    return mv;
}


@RequestMapping(value="param10", method=RequestMethod.POST)
public ModelAndView param10(@RequestParam("user_name") String userName, String pwd) {
    System.out.println(userName + ", " + pwd);
    ModelAndView mv = new ModelAndView();
    mv.setViewName("test");
    return mv;
}


 /* //json视图
@RequestMapping(value="jsonview")
public ModelAndView jsonView() {
    User user = new User();
    user.setId(11);
    user.setName("张三");
    user.setCardId("888888");
    
    ModelAndView mv = new ModelAndView();
    
    Map<String,Object> map = new HashMap<String, Object>();
    map.put("name", "张三");
    map.put("user", user);
    mv.addObject(map);
    
    
    mv.setView(new MappingJackson2JsonView());
    return mv;
}*/

//视图2
@RequestMapping(value="jsonview")
public ModelAndView jsonView(){
    User user = new User();
    user.setId(11);
    user.setName("李四");
    user.setCardId("12345");
    
    ModelAndView mv = new ModelAndView();
     mv.addObject(user);
    //mv.addObject("uu", user);
    mv.setView(new MappingJackson2JsonView());
    
    return mv;
    
}
   }

json.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>

 <!-- 导入js文件 -->
<script type="text/javascript" src="jquery/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
function postData() {
var data = {
        userName:'张三',
        pwd:'123456',
        pageParams:{
            start:5,
            limit:6
        }
}
$.post({
//  请求到哪个地址
   url:'login/param7.do',
   // 对发送数据格式的说明
   contentType:'application/json',
   // 将json对象转成json字符串,发送的数据需要是字符串才行
   data:JSON.stringify(data),
   // 发送成功,服务正常接收并返回后执行此方法
   success:function(result) {
       // result响应内容
       alert('success')
   },
   // 发送失败,运行出错执行此方法
   error:function(error) {
       // error错误描述信息
       alert("error")
   }
})
 }


function postIdList() {
var data = [1,2,3]
$.post({
//  请求到哪个地址
   url:'login/param8.do',
   // 对发送数据格式的说明
   contentType:'application/json',
   // 将json对象转成json字符串,发送的数据需要是字符串才行
   data:JSON.stringify(data),
   // 发送成功,服务正常接收并返回后执行此方法
   success:function(result) {
       // result响应内容
       alert('success')
   },
   // 发送失败,运行出错执行此方法
   error:function(error) {
       // error错误描述信息
       alert("error")
   }
})
}

 function postList(){
   
   var listData = [{username:'abc',pwd:'123123'},{username:'asd', pwd:'234234' }]
   
   $.post({
    //  请求到哪个地址
       url:'login/param9.do',
       // 对发送数据格式的说明
       contentType:'application/json',
       // 将json对象转成json字符串,发送的数据需要是字符串才行
       data:JSON.stringify(listData),
       // 发送成功,服务正常接收并返回后执行此方法
       success:function(result) {
           // result响应内容
          // alert('success')
          $('#success').show();
       },
       // 发送失败,运行出错执行此方法
       error:function(error) {
           // error错误描述信息
          // alert("error")
           $('#fail').show();
       }
   })
   }   
</script>


 </head>
 <body>

  <button onclick="postData()">发送数据</button>
  <button onclick="postIdList()">发送ID集合数据</button>
  <button onclick="postList()">发送对象集合数据</button>
  <p id="success" style="display:none">发送成功</p>
 <p id="fail" style="display:none">发送失败</p>
 </body>
 </html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容