java:Springmvc框架2(Ajax,Interceptor,)

Posted 咫尺天涯是路人丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java:Springmvc框架2(Ajax,Interceptor,)相关的知识,希望对你有一定的参考价值。

1.springmvcAjax:

 

  

 

  springmvc.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-4.3.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">
     
     
 
     <!-- 注解扫描!!!-->
      <context:component-scan base-package="cn.zzsxt"></context:component-scan>
      
      
      
      <!-- 配置视图解析器 -->
    <!-- InternalResourceViewResolver:支持JSP视图解析 -->
    <!-- viewClass:JstlView表示JSP模板页面需要使用JSTL标签库,所以classpath中必须包含jstl的相关jar包; -->
    <!-- prefix 和suffix:查找视图页面的前缀和后缀,最终视图的址为: -->
    <!-- 前缀+逻辑视图名+后缀,逻辑视图名需要在controller中返回ModelAndView指定,比如逻辑视图名为hello,-->
    <!-- 则最终返回的jsp视图地址 "WEB-INF/view/hello.jsp" -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
  
  
       <!-- 注解映射器
        说明 :对类中标记@ResquestMapping的方法进行映射,根据ResquestMapping定义的url匹配
        ResquestMapping标记的方法,匹配成功返回HandlerMethod对象给前端控制器,HandlerMethod对象中封装url对应的方法Method
    -->
    <!--
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
    -->
    <!-- 注解适配器
         说明:注解式处理器适配器,对标记@ResquestMapping的方法进行适配。
    -->
    <!--
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
    -->
    <!-- springmvc使用<mvc:annotation-driven> -->
    <!-- 自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter, -->
    <!-- 可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。 -->
    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
   
   
    
    <!-- 自定义类型转换器 -->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="cn.zzsxt.converter.CustomDateConverter"></bean>
            </list>
        </property>
    </bean>
    
    
    
     <!-- 处理静态资源 让静态资源可以直接访问-->
    <!--<mvc:resources mapping="/js/**" location="/js/"/> -->
    <!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源  -->
     <mvc:default-servlet-handler/>
</beans>

  

  web.xml:

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


  <!-- 解决post提交乱码问题 -->
  <filter>
      <filter-name>encodingFilter</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>encodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
 
 
 
  <!-- spring mvc的前端控制器,类似struts2的核心过滤器 -->
  <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  
  
  
      <!-- 通过contextConfigLocation参数指定配置文件的位置,默认在WEB-INF/查找名称为 [servlet-name]-servlet.xml -->
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:springmvc.xml</param-value>
      </init-param>
  
  
  
      <!-- servlet随web容器而启动 -->
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

 

    UserController.java:

package cn.zzsxt.controller;

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

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.ResponseBody;

import cn.zzsxt.model.Userinfo;
import cn.zzsxt.service.UserService;
import cn.zzsxt.service.impl.UserServiceImpl;
import cn.zzsxt.vo.ResultMessage;

@Controller
@RequestMapping("/user")
public class UserController {
    private UserService userService = new UserServiceImpl();
    
    @RequestMapping(value="login",method=RequestMethod.GET)
    public String login(){
        return "login";
    }
    
    @RequestMapping(value="register",method=RequestMethod.GET)
    public String register(){
        return "register";
    }
    /**
     * @ResponseBody:将java对象转换为json对象
     * @RequestBody:将json对象转换为java对象
     * @param userName
     * @return
     */
    @RequestMapping(value="check",method=RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> check(@RequestBody String userName){
        boolean isExist = userService.checkUserName(userName);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("isExist", isExist);
        return map;
    }
    
    
    @RequestMapping(value="register",method=RequestMethod.POST)
    @ResponseBody
    public ResultMessage register(@RequestBody Userinfo user){  //此处@RequestBody出错的话不加?
        boolean success = userService.add(user);
        String message=success?"添加成功!":"添加失败!";
        ResultMessage rm = new ResultMessage();
        rm.setSuccess(success);
        rm.setMessage(message);
        return rm;
    }

}

  CustomDateConverter.java:

package cn.zzsxt.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.core.convert.converter.Converter;
/**
 * 自定义类型转换器
 * @author Think
 *
 */
public class CustomDateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String source) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(source);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

}

  ResultMessage.java:

package cn.zzsxt.vo;

public class ResultMessage {
    private boolean success;//是否新增成功
    private String message;//操作完成后的提升消息
    
    public boolean isSuccess() {
        return success;
    }
    public void setSuccess(boolean success) {
        this.success = success;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    
}

  login.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP \'login.jsp\' starting page</title>
    <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        $(function(){
            $("#userName").blur(function(){
                var userName = $("#userName").val();
                $.get("user/check?userName="+userName,function(data){
                    if(data.isExist==true){
                        $("#msg").html("<font color=red>用户名已存在!</font>");
                        $("#submitBtn").attr("disabled",true);
                    }else{
                        $("#msg").html("<font color=green>用户名可用!</font>");
                        $("#submitBtn").attr("disabled",false);
                    }
                });
                
            });
        })
    </script>
  </head>
  
  <body>
      <form action="" method="post">
          用户名:<input type="text" name="userName" id="userName"/><span id="msg"></span> <br>
          密码:<input type="text" name="userPass"/><br>
          <input type="submit" value="登录" id="submitBtn">
      </form>
  </body>
</html>

  register.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP \'login.jsp\' starting page</title>
    <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        $(function(){
            //单机注册按钮
            $("#submitBtn").click(function(){
                //获取表单元素的值
                var userName = $("#userName").val();
                var userPass = $("#userPass").val();
                var address = $("#address").val();
                var birthday = $("#birthday").val();
                var jsonData = \'{"userName":"\'+userName+\'","userPass":"\'+userPass+\'","address":"\'+address+\'","birthday":"\'+birthday+\'"}\'; 
//                 alert(jsonData);
                $.ajax({
                         type:"POST",
                         url:"user/register",
                         contentType:"application/json",
                         data:jsonData,
                         success: function(msg){
//                              alert( "Data Saved: " + msg );
                            alert(msg.message);
                         }
                    });
            });
        })
    </script>
  </head>
  
  <body>
      <form action="" method="post">
          用户名:<input typejava框架--springmvc --ajax-json-upload+maven

spring,springmvc,mybatis框架实现用户修改密码功能,用ajax来提交表单数据

怎么用springmvc处理form表单的ajax验证

springMVC框架中的ajax验证

SpringMVC框架的学习

利用SpringMVC框架,通过Ajax与jQuery实现网站登录用户名和密码的校验