【Ajax】ajax 访问 Servlet 和 访问 springMVC的Controller

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ca1m0921/article/details/90714923

分两种情况来写。

1. 首先是 html 页面 使用 ajax 访问 Servlet:

目录结构:

web.xml 不用修改,因为 Test_Servlet.java 中 配置了 @WebServlet("/test") 。

 index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
	<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
	<script type="text/javascript">
		function ajax1(){
			alert("3333");
			$.ajax({
				type : "post",
				url : "test", // 此处的路径 与 springmvc-servlet.xml 中保持一致
				success : function(result){
					alert("666");
					$(window).attr("location",result);
				}
			});
		}
	</script>
</head>
<body>
	<form action="">
		<input type="button" value="submit2" onclick="ajax1()">
	</form>
</body>
</html>

Test_Servlet.java

package test;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

@WebServlet("/test")
public class Test_Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("1111");
		request.setAttribute("message", "doGet");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("2222");
		request.setAttribute("message", "doPost");
	}


}

会看到 输出:

 

 

 

2.  html 页面 使用 ajax 访问 SpringMVC 的Controller : 

先附上 目录结构:

涉及到  web.xml    springmvc-servlet.xml    index.html    TestController 四个文件

需要导入 springmvc 的一些jar包。这里提供完整下载:http://how2j.cn/k/springmvc/springmvc-springmvc/615.html

web.xml:  配置了 springmvc 解析

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Servlet</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

	<servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

</web-app>

springmvc-servlet.xml

<?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">


	<bean id="simpleUrlHandlerMapping"
		class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<props>
				<prop key="/test.do">testController</prop>
			</props>
		</property>
	</bean>
	<bean id="testController" class="controller.TestController"></bean>

</beans>


 

index.html :  很简单的程序

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
	<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
	<script type="text/javascript">
		function ajax1(){
			alert("3333");
			$.ajax({
				type : "post",
				url : "test.do", // 此处的路径 与 springmvc-servlet.xml 中保持一致
				success : function(result){
					alert("666");
					$(window).attr("location",result);
				}
			});
		}
	</script>
</head>
<body>
	<form action="">
		<input type="button" value="submit2" οnclick="ajax1()">
	</form>
</body>
</html>

TestController.java:

package controller;

import javax.servlet.http.HttpServletRequest;

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

@Controller
public class TestController {

	@RequestMapping("/test.do")
	@ResponseBody
	public String test(HttpServletRequest req){
		
		System.out.println("TEST_CONTROLLER...");
		
		String[] result = new String[2];
		result[0] = "result.html";
		result[1] = "访问 Controller 成功,返回信息 result.html 到 ajax,通过 ajax 转发到 result.html 页面";

		return "result.html";
	}
}

result.html:

<!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>
	ajax 访问 controller 成功,转发到 此处。
</body>
</html>

访问的原理:  

web.xml 首先被解析,发现有  springmvc 的 servlet,开始寻找  springmvc-xxx.xml 的配置文件,

springmvc-xxx.xml 的配置文件 配置了 bean  和 访问路径映射,可以找到 controller 的 java 文件,

Testcontroller.java 文件中 写了  @RequsetMapping(“xxx”)访问路径指向的方法,会执行该方法。 

控制台输出:

页面输出:

 

 

 

 

展开阅读全文

为什么$.ajax 访问不到servlet

01-28

想写个jQuery 无刷新验证用户登录 但是最后找不到servlet 大家帮看怎么解决解决rnlogin.jsp代码rn[code=Java]rn<%@ page language="java" contentType="text/html; charset=UTF-8"rn pageEncoding="UTF-8"%>rnrnrnrn rn Insert title herern rn rn rnrnrn rn rn 用户登录rn rn rn rn 登陆帐号:rn rn rn rn 登陆密码:rn rn rn rn 验证码:rn rnrn看不清楚?rn rn rn rn rn rnrnrn[/code]rnrnloginServlet代码rn[code=Java]rnpackage com.Pluto.servelt;rnrnimport java.io.IOException;rnimport java.io.PrintWriter;rnrnimport javax.servlet.ServletException;rnimport javax.servlet.http.HttpServletRequest;rnimport javax.servlet.http.HttpServletResponse;rnrn/**rn * Servlet implementation class for Servlet: loginServletrn *rn */rn @SuppressWarnings("serial")rnpublic class loginServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet rn /* (non-Java-doc)rn * @see javax.servlet.http.HttpServlet#HttpServlet()rn */rn public loginServlet() rn super();rn rn rn rn protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException rn request.setCharacterEncoding("UTF-8");rn PrintWriter out=response.getWriter();rn System.out.println("访问到");rn @SuppressWarnings("unused")rn String message="";rn @SuppressWarnings("unused")rn String name=request.getParameter("username");rn System.out.println(name);rn @SuppressWarnings("unused")rn String pass=request.getParameter("password");rn System.out.println(pass);rn String num=request.getParameter("rand");rn String rand=(String)(request.getSession().getAttribute("rand"));rn rn rn /* (non-Java-doc)rn * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)rn */rn protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException rn login(request,response);rn rn rn /* (non-Java-doc)rn * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)rn */rn protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException rn login(request,response);rn rnrnrn[/code] 论坛

jquery ajax 方式踢人 访问servlet 无响应。

03-09

可以在页面取到文本框的值,但在servlet中取不到,根本不走servlet!rnrnjquery ajax:rn[code=html] rn [/code]rnrnservlet:rnrn[code=java]public class KickServlet extends HttpServlet rnrn /**rn * rn */rn private static final long serialVersionUID = 1L;rn public void doGet(HttpServletRequest request, HttpServletResponse response)rn throws ServletException, IOException rnrn doPost(request,response);rn rnrn rn //当前在线用户列表rn rn @SuppressWarnings("unchecked")rn public void doPost(HttpServletRequest request, HttpServletResponse response)rn throws ServletException, IOException rnrn response.setContentType("text/html");rn response.setCharacterEncoding("utf-8");rn PrintWriter out = response.getWriter();rn //获取要踢出的号码rn String number = request.getParameter("number");rn System.out.println("号码:"+number);rn HttpSession session = request.getSession(false);rn //当前客户的客户号码rn String usernames = (String) session.getAttribute("number");rn rn //输入的名字不是登录的名字rn if(!number.equals(usernames))rn rn String ip = request.getRemoteAddr();rn if (!ip.equals("127.0.0.1")) rn response.getWriter().print("您没有踢人的权限!");rn rn rn rn UserBean currUser = (UserBean) request.getSession().getAttribute("user");rn // 如果当前用户就是被踢用户,那么就是自己踢自己rn if(currUser.getNumber().equals(number)) rn response.getWriter().print("您是不是有病,为什么要踢自己呢!");rn rn rn rn // 从在线名单中获取被踢的用户rn Map onlineUsers = (Map) thisrn .getServletContext().getAttribute("onlineUsers");rn UserBean userbean = onlineUsers.get(currUser);rn System.out.println("号码:"+number);rn // 获取当前用户的session,再从session中移除当前用户rn userbean.getSession().removeAttribute("user");rn // 重定向到users.jsp显示在线用户名单rn response.sendRedirect(request.getContextPath() + "/loginsuccess.jsp");rn System.out.println("踢人成功!");rn rn rn out.print("" + "count:" + 1 + "");rn out.close();rn rnrn[/code] 论坛

没有更多推荐了,返回首页