Spring mvc异步示例

你本来就很二

Spring MVC 异步交互一些demo:

注:博主使用的是jar包如图:

s

1.项目布局

s

2.web.xml

<span style="font-size:18px;"><span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>mySpringMVC</display-name>
  <welcome-file-list>
    <welcome-file>index.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>
  
  <!-- 监听器 -->
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app></span></span>

3.applicationContext.xml

<span style="font-size:18px;"><span style="font-size:14px;"><?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:p="http://www.springframework.org/schema/p"
    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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
	
	<!-- ajax乱码 -->
	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean class="org.springframework.http.converter.StringHttpMessageConverter">
				<constructor-arg>
					<bean class="java.nio.charset.Charset" factory-method="forName">
						<constructor-arg value="UTF-8"/>
					</bean>
				</constructor-arg>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>
	
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
	<context:property-placeholder location="classpath:jdbc.properties" />
	
	<!-- 扫描注解的包,包括子集 -->
    <context:component-scan base-package="pers.youtoo"/>
	
<!-- 	<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
		<property name="mediaTypes">
			<map>
				告诉视图解析器,返回的类型为json格式
				<entry key="json" value="application/json" />
			</map>
		</property>
		<property name="defaultViews">
			<list>
				ModelAndView里的数据变成JSON
				<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
			</list>
		</property>
	</bean> -->
	
</beans></span></span>

4.index.jsp

<span style="font-size:18px;"><span style="font-size:14px;"><%@ 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>
	<script type="text/javascript" src="js/jquery-1.11.3.js"></script>
	<script type="text/javascript">
		$(function(){
			$("#bu1").click(function(){
				$.get("user/ajax1.do", 
						{ username: "John", password: "2pm" },
						function(data){
					    	alert("Data Loaded: " + data);
						});
			});
			$("#bu2").click(function(){
				$.get("user/ajax2.do", 
						{ username: "John", password: "2pm" },
						function(data){
					    	alert("Data Loaded: " + data);
						});
			});
			$("#bu3").click(function(){
				$.get("user/ajax3.do", 
						{ username: "John", password: "2pm" },
						function(data){
					    	alert("Data Loaded: " + data);
						});
			});
			$("#bu4").click(function(){
				alert();
				$.ajax( {
					type : "GET",
					url : "user/ajax4.do",
					data : { username: "John", password: "2pm" },
					dataType: "text",
					success : function(msg) {
						alert(msg);
					}
				});
			});
			$("#bu5").click(function(){
				alert();
				$.ajax( {
					type : "POST",
					url : "user/ajax5.do",
					data : { username: "John", password: "2pm" },
					dataType: "text",
					success : function(msg) {
						alert(msg);
					}
				});
			});
			$("#bu6").click(function(){
				alert();
				$.ajax( {
					type : "GET",
					url : "user/ajax6.do",
					data : { username: "John", password: "2pm" },
					dataType: "text",
					success : function(msg) {
						alert(msg);
						var array=jQuery.parseJSON(msg);
						var str = "";
						for(var i=0;i<array.length;i++){
							var u = array[i];
							str += "<tr><td>" + u.id + "</td><td>" + u.name + "</td></tr>";
						}
						$("#tb").fadeIn(1000);
						$("#tb").html(str);
					}
				});
			});
		});
	</script>
</head>
<body>
	<center>
		<br>
		<h2>GET/POST方式提交参数三种方式</h2>
		<button id="bu1">Ajax1</button>
		<button id="bu2">Ajax2</button>
		<button id="bu3">Ajax3</button>
		<br>
		<h2>GET/POST返回对象</h2>
		<button id="bu4">get</button>
		<button id="bu5">post</button>
		<br>
		<h2>GET/POST返回List</h2>
		<button id="bu6">Ajax6</button>
		<table id="tb" style="display: none" border="1px">
			<tr><td colspan="1">table</td></tr>
		</table>
	</center>
</body>
</html></span></span>

5.Controller

<span style="font-size:18px;"><span style="font-size:14px;">package pers.youtoo.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
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.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import pers.youtoo.entity.User;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@RequestMapping(value = "ajax1", method = RequestMethod.GET)
	public @ResponseBody String ajax1(@RequestParam(value="username", required=true) String username, 
					@RequestParam(value="password", required=true) String password){
		System.out.println("ajax");
		System.out.println(username);
		System.out.println(password);
		System.out.println("ok");
		return "ass我是谁";
	}
	
	@RequestMapping(value="ajax2", method = RequestMethod.GET)
	public @ResponseBody String ajax2(HttpServletRequest request){
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(username);
		System.out.println(password);
		return "哈哈哈";
	}
	
	@RequestMapping(value="ajax3", method = RequestMethod.GET)
	public @ResponseBody void ajax3(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(username);
		System.out.println(password);
		
		//解决乱码
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.write("哈哈哈");
	}
	
	@RequestMapping(value="ajax4", method = RequestMethod.GET)
	public @ResponseBody String ajax4(@RequestParam(value="username", required=true) String username, 
			@RequestParam(value="password", required=true) String password){
		System.out.println("ajax7");
		System.out.println(username);
		System.out.println(password);
		return JSON.toJSONString(new User(1, "我试试"));
	}
	
	@RequestMapping(value="ajax5", method = RequestMethod.POST)
	public @ResponseBody String ajax5(@RequestParam(value="username", required=true) String username, 
			@RequestParam(value="password", required=true) String password){
		System.out.println("ajax7");
		System.out.println(username);
		System.out.println(password);
		return JSON.toJSONString(new User(1, "我试试"));
	}

	@RequestMapping(value="ajax6", method = RequestMethod.GET)
	public @ResponseBody String ajax6(){
		System.out.println("ajax6");
		List<User> userList = new ArrayList<User>();
		userList.add(new User(1, "我试试"));
		userList.add(new User(2, "阿达"));
		userList.add(new User(3, "a都是"));
		return JSON.toJSONString(userList);
	}
}
</span></span>

6.User类

<span style="font-size:18px;"><span style="font-size:14px;">package pers.youtoo.entity;

public class User {
	
	private int id;
	private String name;
	
	public User() {
	}
	
	public User(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + "]";
	}
}</span>
</span>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lanicc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值