Maven+SSM(Spring+SpringMVC+Mybatis)实现登录功能

一 用IDEA构建一个空的Maven web项目

重点截图:
Maven+SSM(Spring+SpringMVC+Mybatis)实现登录功能_第1张图片
然后下一步直到完成(设置项目名和maven地址)

二 搭建环境

1 添加依赖

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>com.testgroupId>
  <artifactId>testMavenartifactId>
  <packaging>warpackaging>
  <version>1.0-SNAPSHOTversion>
  <name>testMaven Maven Webappname>
  <url>http://maven.apache.orgurl>

  <properties>
    <spring.version>4.2.4.RELEASEspring.version>
    <mysql.version>5.1.32mysql.version>
    <dbcp.version>1.4dbcp.version>
    <mybatis.version>3.3.0mybatis.version>
    <mybatis-spring.version>1.2.3mybatis-spring.version>
    <slf4j.version>1.7.5slf4j.version>
    <javassist.version>3.16.1-GAjavassist.version>
    <cglib.version>2.2.2cglib.version>
    <junit.version>4.10junit.version>
    <servlet.version>2.5servlet.version>
    <jsp.version>2.0jsp.version>
    <jstl.version>1.2jstl.version>
  properties>

  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>3.8.1version>
      <scope>testscope>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aspectsartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-ormartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-context-supportartifactId>
      <version>${spring.version}version>
    dependency>

    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>${mysql.version}version>
    dependency>

    
    <dependency>
      <groupId>commons-dbcpgroupId>
      <artifactId>commons-dbcpartifactId>
      <version>${dbcp.version}version>
    dependency>

    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>${mybatis.version}version>
    dependency>
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>${mybatis-spring.version}version>
    dependency>

    
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>${slf4j.version}version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
      <version>${slf4j.version}version>
    dependency>


    
    <dependency>
      <groupId>org.javassistgroupId>
      <artifactId>javassistartifactId>
      <version>${javassist.version}version>
    dependency>
    <dependency>
      <groupId>cglibgroupId>
      <artifactId>cglibartifactId>
      <version>${cglib.version}version>
    dependency>

    
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>${junit.version}version>
      <scope>testscope>
    dependency>

    
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>servlet-apiartifactId>
      <version>${servlet.version}version>
      <scope>providedscope>
    dependency>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>jsp-apiartifactId>
      <version>${jsp.version}version>
      <scope>providedscope>
    dependency>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>jstlartifactId>
      <version>${jstl.version}version>
    dependency>
    
      <dependency>
          <groupId>commons-fileuploadgroupId>
          <artifactId>commons-fileuploadartifactId>
          <version>1.3.1version>
      dependency>
  
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>fastjsonartifactId>
      <version>1.2.32version>
    dependency>
  dependencies>
  <build>
    <finalName>testMavenfinalName>
  build>
project>

2 建立对应的目录文件夹

Maven+SSM(Spring+SpringMVC+Mybatis)实现登录功能_第2张图片

3 写配置文件

db.properties

#数据源的配置信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/testweb?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

log4j.properties

log4j.rootLogger=DEBUG, stdout
log4j.appender.CONSOLE.Encoding=UTF-8
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d[%t]%-5p[%c]-%m%n
log4j.appender.syslog.encoding=UTF-8

spring-context.xml


<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" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
                        http://www.springframework.org/schema/tx
                          http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                          http://www.springframework.org/schema/aop
                          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    
    

    
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:db.propertiesvalue>
            list>
        property>
        <property name="fileEncoding" value="utf-8"/>
    bean>

    
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        
    bean>

    
    <bean id = "sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource">property>
        <property name="mapperLocations" value="classpath:/mapping/*.xml">property>
        
        <property name="typeAliasesPackage" value="com.manage.model">property>
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.manage.dao"/>
    bean>

    
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    bean>

    
    <tx:annotation-driven transaction-manager="transactionManage"/>
    
    <bean id = "transactionManage" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource">property>
    bean>

    
    <context:component-scan base-package="com.manage.service" />
beans>

spring-mvc.xml


<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.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="com.manage.controller" />

    
    <mvc:annotation-driven />

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        
        <property name="prefix" value="/WEB-INF/page/" />
        
        <property name="suffix" value=".jsp" />
    bean>

    
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        
        <property name="maxUploadSize">
            <value>10485760value>
        property>
        
        <property name="defaultEncoding">
            <value>UTF-8value>
        property>
    bean>

    
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            
            <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8value>
                    list>
                property>
            bean>
        mvc:message-converters>
    mvc:annotation-driven>
beans>

web.xml


<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>ssmTestdisplay-name>

  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:spring-context.xmlparam-value>
  context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
  
  <servlet>
    <servlet-name>springDispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:spring-mvc.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>springDispatcherServletservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jspwelcome-file>
  welcome-file-list>

    
    <context-param>
        <param-name>log4jConfigLocationparam-name>
        <param-value>classpath:log4j.propertiesparam-value>
    context-param>
    <context-param>
        <param-name>log4jRefreshIntervalparam-name>
        <param-value>600000param-value>
    context-param>
    <listener>
        <listener-class>
            org.springframework.web.util.Log4jConfigListener
        listener-class>
    listener>
    

    
    <filter>
        <filter-name>encodingFilterfilter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        filter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    
web-app>

写登录实例

Person.java

package com.manage.model;

public class Person {
    private Long id;

    private String username;

    private String password;

    public Long getId() {
        return id;
    }

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


    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }
}

PersonMapper接口

package com.manage.dao;

import com.manage.model.Person;
import org.apache.ibatis.annotations.*;

public interface PersonMapper {

    Person select(@Param("name") String name, @Param("age") int age);

}

mapper文件



<mapper namespace="com.manage.dao.PersonMapper">

    <resultMap id="person" type="Person">
        <result property="username" column="name">result>
        <result property="password" column="age">result>
    resultMap>

    <select id="select" resultMap="person">
        SELECT * FROM tuser WHERE name=#{name} AND age=#{age}
    select>
mapper>

service接口

package com.manage.service;

import com.manage.model.Person;

public interface TestService {

    public Person login(String name,int age);
}

service实现类

package com.manage.service.impl;


import com.manage.dao.PersonMapper;
import com.manage.model.Person;
import com.manage.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by XRog
 * On 2/1/2017.12:58 AM
 */
@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private PersonMapper personMapper;

    public Person login(String name, int age) {
        return personMapper.select(name,age);
    }
}

controller

package com.manage.controller;

import com.manage.model.Person;
import com.manage.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;


/**
 * Created by XRog
 * On 2/1/2017.12:36 AM
 */
@Controller
@RequestMapping("/user")
public class MainController {

    @Autowired
    private TestService testService;

    @RequestMapping(value = "/login")
    public ModelAndView login(@RequestParam("name") String name,
                              @RequestParam("age") int age,
                              HttpServletRequest request) {
        Person person = testService.login(name, age);
        if (person == null) {
            ModelAndView modelAndView = new ModelAndView("loginError", "username", name);
            return modelAndView;
        }
        request.getSession().setAttribute("user", person);
        ModelAndView modelAndView = new ModelAndView("loginSuccess");
        return modelAndView;
    }

}

loginSuccess.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
<html>
<head>
    <title>登录成功title>
head>
<body>
    <h2>恭喜您!${sessionScope.user.username},您的年龄是${sessionScope.user.password}岁h2>
body>
html>

loginError.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
<html>
<head>
    <title>登录失败title>
head>
<body>
    <h2>很遗憾!${requestScope.username},登录失败h2>
body>
html>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="manage" value="${pageContext.request.contextPath}" />
<html>
  <head>
    <title>登录title>
  head>
  <body>
    <form action="${manage}/user/login">
      用户名:<input type="text" name="name" /><br/>
      年龄:<input type="number" name="age"><br/>
      <input type="submit" value="登录" /><br/>
    form>
  body>
html>

表结构:
Maven+SSM(Spring+SpringMVC+Mybatis)实现登录功能_第3张图片

试运行

Maven+SSM(Spring+SpringMVC+Mybatis)实现登录功能_第4张图片
Maven+SSM(Spring+SpringMVC+Mybatis)实现登录功能_第5张图片

git :[email protected]:menglinjie/maven_SSM.git

你可能感兴趣的:(ssm框架)