ssm框架整合+Ajax异步验证

SSM框架是目前企业比较常用的框架之一,它的灵活性、安全性相对于SSH有一定的优势。说到这,谈谈SSM和SSH的不同点,这也是企业常考初级程序员的面试题之一。说到这两套框架的不同,主要是持久层框架Hibernate和MyBatis的不同和控制层框架SpringMVC和Struts2的不同。

 

Hibernate和MyBatis的不同主要体现这么几点:

1.自动化和半自动化:Hibernate的SQL语句自动生成不需要程序员编写,而MyBatis需要编写。

2.学习上:Hibernate入门比较难,而MyBatis入门非常容易。

3.可移植性:Hibernate可移植性好,对应不同的数据库通过改变方言可以直接用,而MyBatis可移植性差,对应不同的数据库需要书写不同的SQL语句

4.关系维护上:Hibernate映射关系复杂,而MyBatis相对简单。

5.缓存:Hibernate有更好的二级缓存,可以使用第三方缓存,而MyBatis本身缓存就不好。

 

 

SpringMVC和Struts2的不同点如下:

1.入口不同:SpringMVC的入口是Servlet,Struts的入口是Filter。

2.性能上:spring3 mvc是方法级别的拦截,拦截到方法后根据参数上的注解,把request数据注入进去,在spring3 mvc中,一个方法对应一个request上下文。而struts2框架是类级别的拦截,每次来了请求就创建一个Action,然后调用setter getter方法把request中的数据注入;struts2实际上是通 setter getter方法与request打交道的;struts2中,一个Action对象对应一个request上下文。  

3.拦截器实现机制上,Struts2有以自己的interceptor机制,SpringMVC用的是独立的AOP方式,这样导致Struts2的配置文件量还是比SpringMVC大。

4. 设计思想上,Struts2更加符合OOP的编程思想, SpringMVC就比较谨慎,在servlet上扩展。

5.SpringMVC集成了Ajax,使用非常方便,只需一个注解@ResponseBody就可以实现,然后直接返回响应文本即可,而Struts2拦截器集成了Ajax,在Action中处理时一般必须安装插件或者自己写代码集成进去,使用起来也相对不方便。

6.Spring MVC和Spring是无缝的。从这个项目的管理和安全上也比Struts2高(当然Struts2也可以通过不同的目录结构和相关配置做到SpringMVC一样的效果,但是需要xml配置的地方不少)。

第一步:导包(这一步只要成功,可以说成功了80%,【maven项目,就只需要导入这些依赖】)

aopalliance.jar
aspectjweaver-1.5.4.jar
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
commons-logging-1.1.3.jar
fastjson-1.2.13.jar
jstl-1.2.jar
mail.jar
mybatis-3.3.1.jar
mybatis-spring-1.2.4.jar
mysql-connector-java-5.1.26-bin.jar
spring-aop-4.2.3.RELEASE.jar
spring-aspects-4.2.3.RELEASE.jar
spring-beans-4.2.3.RELEASE.jar
spring-context-4.2.3.RELEASE.jar
spring-context-support-4.2.3.RELEASE.jar
spring-core-4.2.3.RELEASE.jar
spring-expression-4.2.3.RELEASE.jar
spring-instrument-4.2.3.RELEASE.jar
spring-instrument-tomcat-4.2.3.RELEASE.jar
spring-jdbc-4.2.3.RELEASE.jar
spring-jms-4.2.3.RELEASE.jar
spring-messaging-4.2.3.RELEASE.jar
spring-orm-4.2.3.RELEASE.jar
spring-oxm-4.2.3.RELEASE.jar
spring-test-4.2.3.RELEASE.jar
spring-tx-4.2.3.RELEASE.jar
spring-web-4.2.3.RELEASE.jar
spring-webmvc-4.2.3.RELEASE.jar
spring-webmvc-portlet-4.2.3.RELEASE.jar
spring-websocket-4.2.3.RELEASE.jar

第二步:写Spring主配置文件以及MyBatis主配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 起别名 -->
<typeAliases>
<package name="com.blog.entity"/>
</typeAliases>
   
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
<!-- 自动扫描注解 -->
 <context:component-scan base-package="com.blog.service"></context:component-scan> 

<!-- 配置连接池 -->
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/blog_002"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>

<!-- 配置mybatis工厂 -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>

<!-- 注解事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 开启注解事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>

<!-- 动态扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.blog.mapper"></property>

</bean>

</beans>

第三步:创建实体类

package com.blog.entity;
 
public class User {
 
     
    private Integer Id;
    private String email;
    private String userName;
    private String password;
    private Integer power;
    public Integer getId() {
        return Id;
    }
    public void setId(Integer id) {
        Id = id;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Integer getPower() {
        return power;
    }
    public void setPower(Integer power) {
        this.power = power;
    }
     
}

第四步:创建接口以及SQL映射文件(通过动态代理的方式绑定)

package com.blog.mapper;
 
import org.apache.ibatis.annotations.Param;
 
import com.blog.entity.User;
 
public interface UserMapper {
 
     
    User Login(String email);
     
    User Login2(@Param("email") String email,@Param("password") String password);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="com.blog.mapper.UserMapper">
  
 <select id="Login" parameterType="String" resultType="User">
 select * from b_user where email=#{email}
 </select>
  
  <select id="Login2" resultMap="logins">
 select * from b_user where email=#{email} and password=#{password}
 </select>
 <resultMap type="User" id="logins">
     <id column="Id" property="Id"/>
     <result column="email" property="email"/>
    <result column="password" property="password"/>
 </resultMap>
  
  
 </mapper>

 

第五步:创建Service接口以及实现类

package com.blog.service;
 
import com.blog.entity.User;
 
public interface UserService {
 
     
    User Login(String email);
 
    User Login2(String email,String password);
     
     
}
package com.blog.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.blog.entity.User;
import com.blog.mapper.UserMapper;
import com.blog.service.UserService;

@Service
public class UserServiceImpl implements UserService{

    @Resource
    private UserMapper userMapper;
    
    
    @Override
    public User Login(String email) {
        // TODO Auto-generated method stub
        return userMapper.Login(email);
    }


    @Override
    public User Login2(String email, String password) {
        // TODO Auto-generated method stub
        return userMapper.Login2(email, password);
    }

    
    
}

第六步:写测试类测试上述方法

package com.blog.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.blog.entity.User;
import com.blog.mapper.UserMapper;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class testMapper {

    @Resource
    private UserMapper userMapper;
    
    
    
    @Test
    public void testName() throws Exception {
        
        User user=userMapper.Login("1933108196@qq.com");
        System.out.println(user);
         
        
        
        
    }
    
    @Test
    public void testName2() throws Exception {
        
        User user=userMapper.Login2("1933108196@qq.com", "kangri123");
        System.out.println(user.getUserName());
        
        
        
        
    }
    
}

 

第七步:测试成功后,开始设置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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Demo_Model</display-name>
  
  <!--全局配置 -->  
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!-- 该监听器主要作用是随tomcat的启动,而加载context中的全局配置文件 -->  
  <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- 该过滤器主要作用是处理字符乱码 ,可拦截所有请求,处理所有乱码-->
 <filter>
 <filter-name>CharacterEncoding</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>CharacterEncoding</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>
  <!-- 
  *.do拦截所有带do的请求,对静态资源放行
  / 拦截所有带.jsp的请求,同时对静态资源拦截
  /* 拦截所有
   -->
  </servlet-mapping>
  
  
  
  
  <welcome-file-list>
    <welcome-file>Login.jsp</welcome-file>
  </welcome-file-list>
</web-app>

第八步:配置springmvc.xml(与Spring框架无缝整合)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd ">
<!--扫描Controller层 -->
<context:component-scan base-package="com.blog.controller"></context:component-scan>
 
<!-- 开启注解 -->
<mvc:annotation-driven/>
 
<!-- 配置视图解析器 -->     
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
 
</beans>

配置完毕后记得添加Controller 相关的类

package com.blog.controller;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.alibaba.fastjson.JSON;
import com.blog.entity.User;
import com.blog.service.UserService;
 
@Controller
public class UserController {
 
    @Resource
    private UserService userService;
     
    @RequestMapping(value="emailCheck2.do",method=RequestMethod.POST)
    public void emailCheck2(String email,HttpServletResponse response,HttpServletRequest request,HttpSession session,Model model) throws IOException{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
 
        User user=userService.Login(email);
        if(user!=null){
            out.println("邮箱已经存在");
        }else{
            out.println("邮箱可以使用");
        }
         
        out.flush();
        out.close();
         
    }
     
     
    @RequestMapping(value="emailCheck.do",method=RequestMethod.POST)
    public void emailCheck(String email,HttpServletResponse response,HttpServletRequest request,HttpSession session,Model model) throws IOException{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
 
        User user=userService.Login(email);
        if(user!=null){
            out.println("邮箱正确");
        }else{
            out.println("邮箱错误");
        }
         
        out.flush();
        out.close();
         
    }
     
    @RequestMapping(value="passCheck.do",method=RequestMethod.POST)
    public void emailCheck(String email,String password,HttpServletResponse response,HttpServletRequest request,HttpSession session,Model model) throws IOException{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
 
        User user=userService.Login2(email,password);
        if(user!=null){
            out.println("密码正确");
             
        }else{
            out.println("密码错误");
        }
         
        out.flush();
        out.close();
         
    }
     
     @RequestMapping(value="LoginCheck.do",method=RequestMethod.POST)
     public String LoginCheck(String email,String password,HttpServletResponse response,HttpServletRequest request,HttpSession session,Model model){
         User user=userService.Login2(email, password);
         if(user==null){
             request.setAttribute("error", "用户名或密码不能为空");
             return "Login";
         }else{
              
             model.addAttribute("user", user);
             return "index";
         }
          
     }
     
     
}

第十步:开始启动tomcat,如果控制台无报错信息,说明配置整合成功,反之失败,所以整合过程中一定要仔细


 接下来开始写登录页面做异步验证,在此之前AJax所需的jQuery插件一定要记得导,导入后,写个alert弹框测试一下,以保证在Ajax和JQuery交互的过程中不会因为插件的问题而报错

<%@ 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="js/jquery-1.12.4.min.js"></script>
<script>
    function m1() {

        $(document).ready(function() {

            var email = $("#email").val();

            if (email == null || email == "") {
                $("#nameDiv1").html("邮箱不能为空");

            } else if (email.indexOf("@") == -1) {
                $("#nameDiv1").html("邮箱格式不正确,必须包含@");

            } else if (email.indexOf(".") == -1) {
                $("#nameDiv1").html("邮箱格式不正确,必须包含.");
            } else {
                $.post("${pageContext.request.contextPath}/emailCheck.do", {
                    "email" : email
                }, function(data) {
                    $("#nameDiv1").html(data);
                }, "text");

            }

        });

    }
    
    function m2(){
        $(document).ready(function(){
            var email=$("#email").val();
            var password=$("#password").val();
            if(password==null||password==""){
                $("#nameDiv2").html("密码不能为空");
            }else if(password.length<6){
                $("#nameDiv2").html("密码长度不能小于六位");
            }else if(password.length>18){
                $("#nameDiv2").html("密码长度已经超过18位,不符合给定要求");
            }else{
                $.post(
                "${pageContext.request.contextPath}/passCheck.do",
                {"email":email,"password":password},
                function(data){
                    $("#nameDiv2").html(data);
                },
                "text"                
                );
                
            }
            
            
            
        });
    }
</script>


</head>
<body>
    <div align="center">
        <form action="LoginCheck.do" method="post">
           <h2 align="center">${error}</h2>
            <table align="center">
                <tr>
                    <td>Email:<input type="text" name="email" id="email" onblur="m1()"
                        style="width: 200px;" /></td>
                    <td><span id="nameDiv1" style="color: red; font-size: 15px;"></span></td>
                </tr>
                <tr>
                    <td>Password:<input type="password" name="password" id="password" onblur="m2()"
                        style="width: 200px;" /></td>
                    <td><span id="nameDiv2" style="color: red; font-size: 15px;"></span></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Login" /></td>
                
                </tr>
            </table>
        </form>

    </div>
</body>
</html>
<%@ 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>
${user.userName}
</body>
</html>

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值