结合Spring+SpringMVC+Mybatis

踩了好多坑,搭起来的框架

Spring+SpringMVC+Mybatis+MySQL+Maven

1、文件目录,还配置了一点redis的东西

2、用maven配置各种包,在pom.xml,在https://mvnrepository.com/ 这里可以找到各种需要的包

<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.happy</groupId>
    <artifactId>SpringMVC_SSH</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>SpringMVC_SSH Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.14.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax/javaee-api -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <!--        &lt;!&ndash; https://mvnrepository.com/artifact/mysql/mysql-connector-java &ndash;&gt;-->
        <!--        <dependency>-->
        <!--            <groupId>mysql</groupId>-->
        <!--            <artifactId>mysql-connector-java</artifactId>-->
        <!--            <version>5.1.38</version>-->
        <!--        </dependency>-->
        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>


        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>SpringMVC_SSH</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <resources>
            <resource>
                <directory>src/main/Java</directory>
                <includes>
                    <include>**/mapper/*Mapper.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

3、配置web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
  <!-- 1.针对Spring配置:读取配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath*:/applicationContext.xml,
        </param-value>
    </context-param>
    <!-- 注册ServletContext监听器 创建容器对象,并且将Application对象放到Application域 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 针对SpringMVC的配置 前端控制器:本质上一个servlet 配置SpringMVC -->
    <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*:/applicationContext-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
  <!-- 解决乱码的过滤器 -->
  <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>
      <init-param>
          <param-name>forceEncoding</param-name>
          <param-value>true</param-value>
      </init-param>
  </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  <display-name>Archetype Created Web Application</display-name>
</web-app>

4、配置 applicationContext.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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 01.配置数据源 -->
    <context:property-placeholder location="classpath*:/jdbc.properties" ignore-resource-not-found="true" ignore-unresolvable="true"/>

    <context:component-scan base-package="cn">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    

    <!-- 连接池 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.jdbcUrl}"></property>
        <property name="username" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!-- SqlSessionFactory配置 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 别名 -->
        <property name="typeAliasesPackage" value="cn.jpp.entity"></property>
        <!-- 加载mybatis的全局配置文件 -->
        <property name="mapperLocations" value="classpath*:cn/jpp/mapper/*.xml" />
    </bean>

    <!-- mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开  -->
        <property name="basePackage" value="cn.jpp.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

    <!-- 06.配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 07.配置开启事务操作 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 指定在连接方法上应用的事务属性 -->
            <tx:method name="add*" isolation="DEFAULT" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="edit*" propagation="REQUIRED"/>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="new*" propagation="REQUIRED"/>
            <tx:method name="set*" propagation="REQUIRED"/>
            <tx:method name="remove*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="change*" propagation="REQUIRED"/>
            <tx:method name="check*" propagation="REQUIRED"/>
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="find*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="load*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- aop配置 -->
    <aop:config>

        <aop:pointcut id="stockPointcut" expression="execution(* cn.jpp.*.*(..))"/>
<!--        <aop:pointcut id="stockPointcut" expression="execution(* *..service.*.*(..))"/>-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="stockPointcut"/>
    </aop:config>
</beans>

5、配置applicationContext-mvc.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.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"
       default-lazy-init="true">

    <context:property-placeholder location="classpath*:/jdbc.properties" ignore-resource-not-found="true" ignore-unresolvable="true" />

<!--    <context:component-scan base-package="cn" use-default-filters="false">-->
<!--        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />-->
<!--    </context:component-scan>-->
    <!-- 使用注解开发,不用配置controller,需要配置一个组件扫描器 -->
    <context:component-scan base-package="cn.jpp">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <mvc:annotation-driven>
        <!-- 注册默认的convert -->
        <mvc:message-converters register-defaults="true">
            <!-- 配置RequestMappingHandlerAdapter 需要用到的HttpMessageConvert, 重新制定其supportedMediaTypes 解决@responsebody中文乱码 -->
            <!-- String convert -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <!-- json convert -->
            <bean
                    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>


    <mvc:interceptors>
        <!-- 懒加载用 -->
<!--        <mvc:interceptor>-->
<!--            <mvc:mapping path="/**" />-->
<!--            <bean id="openSessionInViewInterceptor" class="org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor">-->
<!--                <property name="entityManagerFactory" ref="entityManagerFactory" />-->
<!--            </bean>-->
<!--        </mvc:interceptor>-->

<!--        <mvc:interceptor>-->
<!--            <mvc:mapping path="/common/**" />-->
<!--            <bean id="hyLoginInterceptor" class="cn.jpp.interceptor.LoginInterceptor" />-->
<!--        </mvc:interceptor>-->


        <mvc:interceptor>
            <mvc:mapping path="/common/**" />
            <bean id="LoginInterceptor" class="cn.jpp.interceptor.LoginInterceptor" />
        </mvc:interceptor>


    </mvc:interceptors>



    <!-- 配置freeMarker视图解析器 -->
    <!--	<bean id="viewResolverFtl" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
            <property name="contentType" value="text/html; charset=UTF-8" />
            <property name="suffix" value="${template.suffix}" />
            <property name="order" value="0" />
        </bean>-->


    <!-- 20180521 xyy -->
    <!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 -->
    <mvc:default-servlet-handler />
    <!-- 静态资源映射 -->
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/" />

    <!--JSP视图解析器 -->
    <bean id="viewResolverJsp" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

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

<!--    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">-->
<!--        <property name="defaultErrorView" value="/common/error" />-->
<!--    </bean>-->

    <!-- 静态资源文件的访问 -->
    <mvc:resources location="/resources/" mapping="/resources/**" />
    <mvc:resources location="/Javascripts/" mapping="/Javascripts/**" />
    <mvc:resources location="/Themes/" mapping="/Themes/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/upload/" mapping="/upload/**" />
    <mvc:resources location="/favicon.ico" mapping="/favicon.ico" />
    <mvc:resources location="/index.html" mapping="/index.html" />
</beans>

6、配置applicationContext-Redis.xml,redis配置,和SSM框架无关

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <!-- 导入redis.properties -->
         <bean id="propertyConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location" value="classpath:redis.properties" />
         </bean>

         <!-- redis 数据源 -->
        <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
             <!-- 定义最大连接数 -->
             <property name="maxTotal" value="${redis.maxTotal}" />
             <!-- 定义最大空闲链接数 -->
             <property name="maxIdle" value="${redis.maxIdle}" />
             <!-- 定义最长等待时间 -->
             <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
             <!-- 在获取连接时检查是否有效性 -->
             <property name="testOnBorrow" value="${redis.testOnBorrow}" />
         </bean>

         <!-- redis 链接池 -->
         <bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy" depends-on="poolConfig">
             <!-- redis 主机IP -->
             <constructor-arg name="host" value="${redis.host}" />
             <!-- redis 端口 -->
             <constructor-arg name="port" value="${redis.port}" />
             <!-- 加载JedisPool配置信息 -->
             <constructor-arg name="poolConfig" ref="poolConfig" />
         </bean>

</beans>

6、配置jdbc.properties,数据库连接的一些配置

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/TestMySQL?useUnicode=true&characterEncoding=UTF-8
jdbc.user=root
jdbc.password=12345

7、从底向上进行

entity 实体层UserInfo

package cn.jpp.entity;

public class UserInfo {
    private Integer id;
    private String name;
    private Integer age;
    private String password;

    public Integer getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

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

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

    public void setAge(Integer age) {
        this.age = age;
    }
    public void setPassword(String password){
        this.password=password;
    }
    public String getPassword(){
        return this.password;
    }
}

8、dao层 IUserInfoDAO

package cn.jpp.dao;

import cn.jpp.entity.UserInfo;
import org.apache.ibatis.annotations.Insert;

import java.util.List;

public interface IUserInfoDAO {
    public void add(UserInfo info);

    public List<UserInfo> getAllInfo();
    public List<UserInfo> getName(String name);
}

9、service层 IUserInfoService

package cn.jpp.service;

import cn.jpp.dao.IUserInfoDAO;
import cn.jpp.entity.UserInfo;

import java.util.List;

public interface IUserInfoService  {
    public void add(UserInfo info);
    public List<UserInfo> getAllInfo();
    public List<UserInfo> getName(String name);
}

IUserInfoServiceImpl

package cn.jpp.service.Impl;

import cn.jpp.dao.IUserInfoDAO;
import cn.jpp.entity.UserInfo;
import cn.jpp.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service(value = "IUserInfoServiceImpl")
public class IUserInfoServiceImpl implements IUserInfoService {
//    @Resource(name = "IUserInfoDAOImpl")
    @Autowired
    private IUserInfoDAO dao;

    @Override
    public void add(UserInfo info){
        System.out.println("进入这里");
        dao.add(info);
    }

    @Override
    public List<UserInfo> getAllInfo() {
        List<UserInfo>res=dao.getAllInfo();
        return res;
    }

    @Override
    public List<UserInfo> getName(String name) {
        List<UserInfo>res=dao.getName(name);
        return res;
    }

}

10、Controller IUserController

package cn.jpp.controller;

import cn.jpp.Json;
import cn.jpp.entity.UserInfo;
import cn.jpp.service.IUserInfoService;

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

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/common/submit")
public class UserInfoController {
    @Resource(name = "IUserInfoServiceImpl")
    private IUserInfoService service;


    @RequestMapping(value = "/add")
    @ResponseBody
    public Json addUser(String name, Integer age) throws Exception {
        Json json = new Json();
        try {
            System.out.println("name:"+name+"age:"+age);
            if (name == null || age == 0) {
                throw new Exception("姓名或年龄或密码不能为空");
            }
            UserInfo userInfo = new UserInfo();
            userInfo.setName(name);
            userInfo.setAge(age);
            service.add(userInfo);
            json.setSuccess(true);
            json.setMsg("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
        }

        return json;
    }
    @RequestMapping(value = "/getList")
    @ResponseBody
    public Json getList(String name){
        Json json=new Json();
        List<UserInfo>arr=new ArrayList<>();
        try {
            if(name==null){
                System.out.println("name==null");
                arr=service.getAllInfo();
            }else{
                arr=service.getName(name);
            }
            json.setMsg("获取成功");
            json.setSuccess(true);
            json.setObj(arr);
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("获取失败");
            json.setSuccess(false);
        }

        return json;
    }
//    public ModelAndView handleRequest(HttpServletRequest request,
//                                      HttpServletResponse response) throws Exception {
//
//        String uname=request.getParameter("name");
//        Integer uage=Integer.valueOf(request.getParameter("age"));
//
//        UserInfo info=new UserInfo();
//        info.setAge(uage);
//        info.setName(uname);
//
//        service.add(info);
//        return new ModelAndView("/welcome.jsp");
//    }


}

11、将dao和sql映射起来

UserMapper.xml

<?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="cn.jpp.dao.IUserInfoDAO">
    <insert id="add" parameterType="cn.jpp.entity.UserInfo">
        insert into user(name,age) values(#{name},#{age})
    </insert>

    <select id="getAllInfo" resultType="cn.jpp.entity.UserInfo">
        select * from user
    </select>

    <select id="getName" resultType="cn.jpp.entity.UserInfo" parameterType="java.lang.String">
        select name,age,password from user where name= #{name}
    </select>
</mapper>

12、index.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%>">
    <style type="text/css">
        form{
            margin:0px auto;

            width:500px;
            padding:20px;
        }
    </style>
    <title></title>
</head>

<body>
<h1>启动成功</h1>

</body>
</html>

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值