手把手搭建一个SSM项目(适合新手)

ssm项目整合(Spring+SpringMVC+Mybatis)

 

该项目实现的功能有

1.用户登录

2.新增用户信息

3.返回所有用户信息

4.更新用户信息

5删除用户信息


项目源码下载

项目结构:

 


 

 

 

具体搭建步骤:

创建数据库和对应的表结构

 

 
  1. SET FOREIGN_KEY_CHECKS=0;

  2.  
  3. -- ----------------------------

  4. -- Table structure for `adminuser`

  5. -- ----------------------------

  6. DROP TABLE IF EXISTS `adminuser`;

  7. CREATE TABLE `adminuser` (

  8. `id` int(11) NOT NULL AUTO_INCREMENT,

  9. `username` varchar(255) DEFAULT NULL,

  10. `password` varchar(255) DEFAULT NULL,

  11. PRIMARY KEY (`id`)

  12. ) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

  13.  
  14. -- ----------------------------

  15. -- Records of adminuser

  16. -- ----------------------------

  17. INSERT INTO `adminuser` VALUES ('1', '小落', 'qwe');


 

 


1.新建一个web项目  在WebRoot/WEB-INF/lib下导入必须的jar包

 

 
  1. aopalliance-1.0.jar

  2. aspectjweaver-1.7.1.jar

  3. commons-fileupload-1.2.2.jar

  4. commons-logging-1.1.1.jar

  5. druid-0.2.9.jar

  6. jstl-1.2.jar

  7. junit-4.11.jar

  8. mybatis-3.1.1.jar

  9. mybatis-spring-1.1.1.jar

  10. mysql-connector-java-5.1.21.jar

  11. servlet-api-3.0-alpha-1.jar

  12. spring-aop-3.2.0.RELEASE.jar

  13. spring-beans-3.2.0.RELEASE.jar

  14. spring-context-3.2.0.RELEASE.jar

  15. spring-core-3.2.0.RELEASE.jar

  16. spring-expression-3.2.0.RELEASE.jar

  17. spring-jdbc-3.1.1.RELEASE.jar

  18. spring-test-3.2.0.RELEASE.jar

  19. spring-tx-3.1.1.RELEASE.jar

  20. spring-web-3.2.0.RELEASE.jar

  21. spring-webmvc-3.2.0.RELEASE.jar



2.创建db.properties数据库连接配置文件

 

db.properties

 

 
  1. #hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

  2. #driverClassName=com.mysql.jdbc.Driver

  3. #来验证数据库连接的有效性

  4. validationQuery=SELECT 1

  5. jdbc_url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull

  6. jdbc_username=root

  7. jdbc_password=root


 

 


3.创建包结构
com.jsx.controller 
com.jsx.dao
com.jsx.mapping
com.jsx.model
com.jsx.service
com.jsx.service.impl
4.创建spring.xml配置文件

spring.xml

 

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

  2. <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" xsi:schemaLocation="

  3. http://www.springframework.org/schema/beans

  4. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

  5. http://www.springframework.org/schema/context

  6. http://www.springframework.org/schema/context/spring-context-3.0.xsd

  7. ">

  8. <!-- 引入属性文件 -->

  9. <context:property-placeholder location="classpath:db.properties" />

  10. <!-- 自动扫描(自动注入) -->

  11. <context:component-scan base-package="com.jsx.service..*" />

  12.  
  13. </beans>



5.创建spring-mybatis.xml配置文件

 

spring-mybatis.xml

 

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

  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="

  3. http://www.springframework.org/schema/beans

  4. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

  5. http://www.springframework.org/schema/tx

  6. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

  7. http://www.springframework.org/schema/aop

  8. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

  9. ">

  10.  
  11. <!-- 配置数据源

  12. Druid是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。

  13. -->

  14. <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">

  15. <property name="url" value="${jdbc_url}" />

  16. <property name="username" value="${jdbc_username}" />

  17. <property name="password" value="${jdbc_password}" />

  18.  
  19. <!-- 初始化连接大小 -->

  20. <property name="initialSize" value="0" />

  21. <!-- 连接池最大使用连接数量 -->

  22. <property name="maxActive" value="20" />

  23. <!-- 连接池最大空闲 -->

  24. <property name="maxIdle" value="20" />

  25. <!-- 连接池最小空闲 -->

  26. <property name="minIdle" value="0" />

  27. <!-- 获取连接最大等待时间 -->

  28. <property name="maxWait" value="60000" />

  29. <!-- mysql 不支持 poolPreparedStatements-->

  30. <!--

  31. <property name="poolPreparedStatements" value="true" />

  32. <property name="maxPoolPreparedStatementPerConnectionSize" value="33" />

  33. -->

  34. <!-- 验证数据库连接的查询语句,这个查询语句必须是至少返回一条数据的SELECT语句。 -->

  35. <property name="validationQuery" value="${validationQuery}" />

  36. <!-- 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 -->

  37. <property name="testOnBorrow" value="false" />

  38. <!-- 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 -->

  39. <property name="testOnReturn" value="false" />

  40. <!-- 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,

  41. 如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 -->

  42. <property name="testWhileIdle" value="true" />

  43.  
  44. <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->

  45. <property name="timeBetweenEvictionRunsMillis" value="60000" />

  46. <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->

  47. <property name="minEvictableIdleTimeMillis" value="25200000" />

  48. <!-- 打开removeAbandoned功能 -->

  49. <property name="removeAbandoned" value="true" />

  50. <!-- 1800秒,也就是30分钟 -->

  51. <property name="removeAbandonedTimeout" value="1800" />

  52. <!-- 关闭abanded连接时输出错误日志 -->

  53. <property name="logAbandoned" value="true" />

  54. <!-- 开启Druid的监控统计功能 监控数据库

  55. <property name="filters" value="stat" /> -->

  56. <property name="filters" value="mergeStat" />

  57. </bean>

  58.  
  59. <!-- myBatis文件

  60. 创建工厂 bean

  61. SqlSessionFactoryBean 实现了 Spring 的 FactoryBean 接口

  62. -->

  63. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

  64. <!-- 可以是任意 的 DataSource,其配置应该和其它 Spring 数据库连接是一样的。-->

  65. <property name="dataSource" ref="dataSource" />

  66. <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->

  67. <property name="mapperLocations" value="classpath:com/jsx/mapping/*.xml" />

  68. </bean>

  69. <!--

  70. Mybatis MapperScannerConfigurer 自动扫描 将Mapper接口生成代理注入到Spring

  71. MapperFactoryBean 创建的代理类实现了 UserMapper 接口,并且注入到应用程序中。

  72. 因为代理创建在运行时环境中(Runtime,译者注) ,那么指定的映射器必须是一个接口,而 不是一个具体的实现类。

  73. 缺点有很多的配置文件时 全部需要手动编写。

  74. 没有必要在 Spring 的 XML 配置文件中注册所有的映射器。相反,你可以使用一个 MapperScannerConfigurer ,

  75. 它 将 会 查 找 类 路 径 下 的 映 射 器 并 自 动 将 它 们 创 建 成 MapperFactoryBean。

  76. MapperScannerConfigurer 支 持 过 滤 由 指 定 的 创 建 接 口 或 注 解 创 建 映 射 器 。 annotationClass 属性指定了要寻找的注解名称。

  77. markerInterface 属性指定了要寻找的父 接口。如果两者都被指定了,加入到接口中的映射器会匹配两种标准。

  78. 默认情况下,这两个 属性都是 null,所以在基包中给定的所有接口可以作为映射器加载。

  79. -->

  80. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

  81. <property name="basePackage" value="com.jsx.dao" />

  82. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />

  83. </bean>

  84.  
  85. <!-- 配置事务管理器 -->

  86. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

  87. <property name="dataSource" ref="dataSource" />

  88. </bean>

  89.  
  90. <!-- 注解方式配置事物 -->

  91. <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->

  92.  
  93. <!-- 拦截器方式配置事物

  94. spring有很多事物管理,其中很多都是被淘汰的了,企业一直在用,最好配置方法如下,配置事务之后,用切面直接切入所有servic层

  95. -->

  96. <tx:advice id="transactionAdvice" transaction-manager="transactionManager">

  97. <tx:attributes>

  98. <tx:method name="add*" propagation="REQUIRED" />

  99. <tx:method name="append*" propagation="REQUIRED" />

  100. <tx:method name="insert*" propagation="REQUIRED" />

  101. <tx:method name="save*" propagation="REQUIRED" />

  102. <tx:method name="update*" propagation="REQUIRED" />

  103. <tx:method name="modify*" propagation="REQUIRED" />

  104. <tx:method name="edit*" propagation="REQUIRED" />

  105. <tx:method name="delete*" propagation="REQUIRED" />

  106. <tx:method name="remove*" propagation="REQUIRED" />

  107. <tx:method name="repair" propagation="REQUIRED" />

  108. <tx:method name="delAndRepair" propagation="REQUIRED" />

  109.  
  110. <tx:method name="get*" propagation="SUPPORTS" />

  111. <tx:method name="find*" propagation="SUPPORTS" />

  112. <tx:method name="load*" propagation="SUPPORTS" />

  113. <tx:method name="search*" propagation="SUPPORTS" />

  114. <tx:method name="datagrid*" propagation="SUPPORTS" />

  115.  
  116. <tx:method name="*" propagation="SUPPORTS" />

  117. </tx:attributes>

  118. </tx:advice>

  119. <aop:config>

  120. <aop:pointcut id="transactionPointcut" expression="execution(* com.jsx.service..*Impl.*(..))" />

  121. <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />

  122. </aop:config>

  123.  
  124.  
  125. <!-- 配置druid监控spring jdbc

  126. 至于Druid是一个用于大数据实时查询和分析的高容错、高性能开源分布式系统,旨在快速处理大规模的数据,并能够实现快速查询和分析。

  127. 尤其是当发生代码部署、机器故障以及其他产品系统遇到宕机等情况时,Druid仍能够保持100%正常运行。

  128. 创建Druid的最初意图主要是为了解决查询延迟问题,当时试图使用Hadoop来实现交互式查询分析,但是很难满足实时分析的需要。

  129. 而Druid提供了以交互方式访问数据的能力,并权衡了查询的灵活性和性能而采取了特殊的存储格式

  130.  
  131. Druid是为OLAP工作流的探索性分析而构建,它支持各种过滤、聚合和查询等类;

  132. Druid的低延迟数据摄取架构允许事件在它们创建后毫秒内可被查询到;

  133. Druid的数据在系统更新时依然可用,规模的扩大和缩小都不会造成数据丢失;

  134. Druid已实现每天能够处理数十亿事件和TB级数据;

  135. -->

  136. <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"></bean>

  137. <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">

  138. <property name="patterns">

  139. <list>

  140. <value>com.jsx.service.*</value>

  141. </list>

  142. </property>

  143. </bean>

  144.  
  145. <aop:config>

  146. <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />

  147. </aop:config>

  148. </beans>



6.创建spring-mvc.xml配置文件

 

spring-mvc.xml

 

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

  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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" xsi:schemaLocation="http://www.springframework.org/schema/beans

  3. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

  4. http://www.springframework.org/schema/context

  5. http://www.springframework.org/schema/context/spring-context-3.0.xsd

  6. http://www.springframework.org/schema/mvc

  7. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

  8.  
  9. <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->

  10. <context:component-scan base-package="com.jsx.controller" />

  11. <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 controller方法返回值+.jsp-->

  12. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />

  13.  
  14. </beans>



7.在WebRoot/WEB-INF/web.xml下配置上述配置文件和其他属性

 

web.xml

 

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

  2. <web-app version="3.0"

  3. xmlns="http://java.sun.com/xml/ns/javaee"

  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

  6. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

  7. <display-name></display-name>

  8. <!--

  9. 通过contextConfigLocation配置spring,contextConfigLocation参数定义了要装入的 Spring 配置文件。

  10. 如果想装入多个配置文件,可以在 <param-value>标记中用逗号作分隔符。

  11. 在web.xml里需配置ContextLoaderListener

  12. -->

  13. <context-param>

  14. <param-name>contextConfigLocation</param-name>

  15. <param-value>classpath:spring.xml;classpath:spring-mybatis.xml</param-value>

  16. </context-param>

  17. <!-- 过滤通过用于处理项目中的乱码问题,该过滤器位于org.springframework.web.filter包中,指向类CharacterEncodingFilter -->

  18. <filter>

  19. <description>字符集过滤器</description>

  20. <filter-name>encodingFilter</filter-name>

  21. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

  22. <init-param>

  23. <description>字符集编码</description>

  24. <param-name>encoding</param-name>

  25. <param-value>UTF-8</param-value>

  26. </init-param>

  27. </filter>

  28. <filter-mapping>

  29. <filter-name>encodingFilter</filter-name>

  30. <url-pattern>/*</url-pattern>

  31. </filter-mapping>

  32. <!--

  33. 自动装配ApplicationContext的配置信息。

  34. 因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。

  35. -->

  36. <listener>

  37. <description>spring监听器</description>

  38. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  39. </listener>

  40. <!--

  41. servlet标准不允许在web容器内自行做线程管理

  42. 主要负责处理由 JavaBeans Introspector的使用而引起的缓冲泄露。清除Introspector的唯一方式是刷新整个缓冲

  43. -->

  44. <listener>

  45. <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>

  46. </listener>

  47. <!--

  48. DispatcherServlet是前端控制器设计模式的实现,提供Spring Web MVC的集中访问点,而且负责职责的分派,

  49. 而且与Spring IoC容器无缝集成,从而可以获得Spring的所有好处。

  50.  
  51. DispatcherServlet主要用作职责调度工作,本身主要用于控制流程,主要职责如下:

  52. 1、文件上传解析,如果请求类型是multipart将通过MultipartResolver进行文件上传解析;

  53. 2、通过HandlerMapping,将请求映射到处理器(返回一个HandlerExecutionChain,它包括一个处理器、多个HandlerInterceptor拦截器);

  54. 3、通过HandlerAdapter支持多种类型的处理器(HandlerExecutionChain中的处理器);

  55. 4、通过ViewResolver解析逻辑视图名到具体视图实现;

  56. 5、本地化解析;

  57. 6、渲染具体的视图等;

  58. 7、如果执行过程中遇到异常将交给HandlerExceptionResolver来解析。

  59. -->

  60. <servlet>

  61. <description>spring mvc servlet</description>

  62. <servlet-name>springMvc</servlet-name>

  63. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

  64. <init-param>

  65. <description>spring mvc 配置文件</description>

  66. <param-name>contextConfigLocation</param-name>

  67. <param-value>classpath:spring-mvc.xml</param-value>

  68. </init-param>

  69. <load-on-startup>1</load-on-startup>

  70. </servlet>

  71. <servlet-mapping>

  72. <servlet-name>springMvc</servlet-name>

  73. <url-pattern>*.do</url-pattern>

  74. </servlet-mapping>

  75. <!--

  76. Session是由浏览器和服务器之间维护的。

  77. Session超时理解为:浏览器和服务器之间创建了一个Session,由于客户端长时间(休眠时间)没有与服务器交互,

  78. 服务器将此Session销毁,客户端再一次与服务器交互时之前的Session就不存在了。

  79. -->

  80. <session-config>

  81. <session-timeout>15</session-timeout>

  82. </session-config>

  83.  
  84. <welcome-file-list>

  85. <welcome-file>index.jsp</welcome-file>

  86. </welcome-file-list>

  87. </web-app>

  88.  



8.在model下创建User实体类

 

User.java

 

 
  1. package com.jsx.model;

  2.  
  3. public class User {

  4. private int id;

  5. private String username;

  6. private String password;

  7.  
  8. public int getId() {

  9. return id;

  10. }

  11. public void setId(int id) {

  12. this.id = id;

  13. }

  14. public String getUsername() {

  15. return username;

  16. }

  17. public void setUsername(String username) {

  18. this.username = username == null ? null : username.trim();

  19. }

  20. public String getPassword() {

  21. return password;

  22. }

  23. public void setPassword(String password) {

  24. this.password = password == null ? null : password.trim();

  25. }

  26. }



9.在mapping下创建User.xml定义实体类要实现的功能 (其中定义你的功能,对应要对数据库进行的那些操作)

 

User.xml

 

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

  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

  4.  
  5. <mapper namespace="com.jsx.dao.UserDao" >

  6. <resultMap id="UserMap" type="com.jsx.model.User" >

  7. <id column="id" property="id" jdbcType="VARCHAR" />

  8. <result column="username" property="username" jdbcType="VARCHAR" />

  9. <result column="password" property="password" jdbcType="VARCHAR" />

  10. </resultMap>

  11.  
  12. <sql id="Base_Column_List" >

  13. id, username, password

  14. </sql>

  15.  
  16. <select id="selectByPrimaryKey" resultMap="UserMap" parameterType="com.jsx.model.User" >

  17. select

  18. <include refid="Base_Column_List" />

  19. from adminuser

  20. where id = #{id}

  21. </select>

  22.  
  23. <select id="selectByUsernameAndPassword" resultMap="UserMap" parameterType="com.jsx.model.User" >

  24. select * from adminuser

  25. where username = #{username} and password = #{password}

  26. </select>

  27.  
  28. <delete id="deleteByPrimaryKey" parameterType="com.jsx.model.User" >

  29. delete from adminuser

  30. where id = #{id}

  31. </delete>

  32.  
  33. <insert id="insert" parameterType="com.jsx.model.User" useGeneratedKeys="true" keyProperty="id">

  34. insert into adminuser (username, password)

  35. values (#{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR})

  36. </insert>

  37.  
  38. <insert id="insertSelective" parameterType="com.jsx.model.User" >

  39. insert into adminuser

  40. <trim prefix="(" suffix=")" suffixOverrides="," >

  41. <if test="username != null" >

  42. username,

  43. </if>

  44. <if test="password != null" >

  45. password,

  46. </if>

  47. </trim>

  48. <trim prefix="values (" suffix=")" suffixOverrides="," >

  49. <if test="username != null" >

  50. #{username,jdbcType=VARCHAR},

  51. </if>

  52. <if test="password != null" >

  53. #{password,jdbcType=VARCHAR},

  54. </if>

  55. </trim>

  56. </insert>

  57.  
  58. <update id="updateByPrimaryKeySelective" parameterType="com.jsx.model.User" >

  59. update adminuser

  60. <set >

  61. <if test="username != null" >

  62. username = #{username,jdbcType=VARCHAR},

  63. </if>

  64. <if test="password != null" >

  65. password = #{password,jdbcType=VARCHAR},

  66. </if>

  67. </set>

  68. where id = #{id}

  69. </update>

  70.  
  71. <update id="updateByPrimaryKey" parameterType="com.jsx.model.User" >

  72. update adminuser

  73. set username = #{username,jdbcType=VARCHAR},

  74. password = #{password,jdbcType=VARCHAR}

  75. where id = #{id}

  76. </update>

  77.  
  78. <select id="getAll" resultMap="UserMap">

  79. SELECT * FROM adminuser

  80. </select>

  81.  
  82. </mapper>



10.在dao创建UserDao将将User.xml中的操作按照id映射成Java函数。

 

UserDao.java

 

 
  1. package com.jsx.dao;

  2.  
  3. import java.util.List;

  4. import com.jsx.model.User;

  5.  
  6. public interface UserDao {

  7. int insert(User user);

  8. int insertSelective(User user);

  9. int deleteByPrimaryKey(int id);

  10. int updateByPrimaryKeySelective(User user);

  11. int updateByPrimaryKey(User user);

  12. User selectByPrimaryKey(int id);

  13. List<User> getAll();

  14. User selectByUsernameAndPassword(User user);

  15. }



11.在service下创建UserService接口  (为控制层提供服务,接受控制层的参数,完成相应的功能,并返回给控制层。)

 

UserService.java

 

 
  1. package com.jsx.service;

  2.  
  3. import java.util.List;

  4. import com.jsx.model.User;

  5.  
  6. public interface UserService {

  7. String addInfo(User addInfo);

  8. List<User> getAll();

  9. String delete(int id);

  10. User findById(int id);

  11. String update(User addInfo);

  12. User login(User user);

  13. }



12.在service.impl下创建UserService接口实现类UserServiceImpl

 

UserServiceImpl.java

 

 
  1. package com.jsx.service.impl;

  2.  
  3. import java.util.List;

  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;

  6. import org.springframework.stereotype.Service;

  7.  
  8. import com.jsx.dao.UserDao;

  9. import com.jsx.model.User;

  10. import com.jsx.service.UserService;

  11.  
  12. @Service("userService")

  13. public class UserServiceImpl implements UserService{

  14. @Autowired

  15. private UserDao userDao;

  16. public UserDao getUserDao() {

  17. return userDao;

  18. }

  19. public void setUserDao(UserDao userDao) {

  20. this.userDao = userDao;

  21. }

  22.  
  23. //表示一个方法声明的目的是覆盖父类方法声明。如果一个方法是注释,该注释类型但不重写基类方法,编译器必须生成一个错误消息。

  24. @Override

  25. public String addInfo(User addInfo) {

  26. if (userDao.insertSelective(addInfo) == 1) {

  27. return "添加成功";

  28. }

  29. return "添加失败";

  30. }

  31. @Override

  32. public List<User> getAll() {

  33. return userDao.getAll();

  34. }

  35. @Override

  36. public String delete(int id) {

  37. if (userDao.deleteByPrimaryKey(id) == 1) {

  38. return "删除成功";

  39. }

  40. return "删除失败";

  41. }

  42. @Override

  43. public User findById(int id) {

  44. return userDao.selectByPrimaryKey(id);

  45. }

  46. @Override

  47. public String update(User addInfo) {

  48. if (userDao.updateByPrimaryKeySelective(addInfo) == 1) {

  49. return "更新成功";

  50. }

  51. return "更新失败";

  52. }

  53. @Override

  54. public User login(User user) {

  55. return userDao.selectByUsernameAndPassword(user);

  56. }

  57. }



13.在controller下创建UserController处理由DispatcherServlet 分发的请求

 

UserController.java

 

 
  1. package com.jsx.controller;

  2.  
  3.  
  4. import java.util.List;

  5. import java.util.UUID;

  6. import javax.servlet.http.HttpServletRequest;

  7. import org.springframework.beans.factory.annotation.Autowired;

  8. import org.springframework.stereotype.Controller;

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

  10. import com.jsx.model.User;

  11. import com.jsx.service.UserService;

  12.  
  13. @Controller

  14. public class UserController {

  15. @Autowired

  16. private UserService userService;

  17. public UserService getUserService() {

  18. return userService;

  19. }

  20. public void setUserService(UserService userService) {

  21. this.userService = userService;

  22. }

  23.  
  24. @SuppressWarnings("finally")

  25. @RequestMapping("addInfo")

  26. public String add(User user,HttpServletRequest request){

  27. try {

  28. // user.setId(UUID.randomUUID().toString());

  29. System.out.println(user.getId() + ":::::" + user.getUsername() + ":::::" + user.getPassword());

  30. String str = userService.addInfo(user);

  31. System.out.println(str);

  32. request.setAttribute("InfoMessage", str);

  33. } catch (Exception e) {

  34. e.printStackTrace();

  35. request.setAttribute("InfoMessage", "添加信息失败!具体异常信息:" + e.getMessage());

  36. } finally {

  37. return "result";

  38. }

  39. }

  40.  
  41. @RequestMapping("getAll")

  42. public String getAddInfoAll(HttpServletRequest request){

  43. try {

  44. List<User> list = userService.getAll();

  45. System.out.println("------User_list-----"+list.size());

  46. request.setAttribute("addLists", list);

  47. return "listAll";

  48. } catch (Exception e) {

  49. e.printStackTrace();

  50. request.setAttribute("InfoMessage", "信息载入失败!具体异常信息:" + e.getMessage());

  51. return "result";

  52. }

  53. }

  54.  
  55. @SuppressWarnings("finally")

  56. @RequestMapping("del")

  57. public String del(int id,HttpServletRequest request){

  58. try {

  59. String str = userService.delete(id);

  60. request.setAttribute("InfoMessage", str);

  61. } catch (Exception e) {

  62. e.printStackTrace();

  63. request.setAttribute("InfoMessage", "删除信息失败!具体异常信息:" + e.getMessage());

  64. } finally {

  65. return "result";

  66. }

  67. }

  68. @RequestMapping("modify")

  69. public String modify(int id,HttpServletRequest request){

  70. try {

  71. User user = userService.findById(id);

  72. request.setAttribute("add", user);

  73. return "modify";

  74. } catch (Exception e) {

  75. e.printStackTrace();

  76. request.setAttribute("InfoMessage", "信息载入失败!具体异常信息:" + e.getMessage());

  77. return "result";

  78. }

  79. }

  80. @SuppressWarnings("finally")

  81. @RequestMapping("update")

  82. public String update(User user,HttpServletRequest request){

  83. try {

  84. String str = userService.update(user);

  85. request.setAttribute("InfoMessage", str);

  86. } catch (Exception e) {

  87. e.printStackTrace();

  88. request.setAttribute("InfoMessage", "更新信息失败!具体异常信息:" + e.getMessage());

  89. } finally {

  90. return "result";

  91. }

  92. }

  93. @RequestMapping("login")

  94. public String login(User user,HttpServletRequest request){

  95. try {

  96. System.out.println("------login--qian----"+user.getUsername()+","+user.getPassword()+".");

  97. User loginUser = null;

  98. loginUser=userService.login(user);

  99. if(loginUser!=null){

  100. request.setAttribute("loginUser", loginUser.getUsername());

  101. return "index";

  102. }else{

  103. request.setAttribute("loginUser", "登录失败");

  104. return "index";

  105. }

  106. } catch (Exception e) {

  107. e.printStackTrace();

  108. request.setAttribute("InfoMessage", "登录失败!具体异常信息:" + e.getMessage());

  109. return "result";

  110. }

  111. }

  112.  
  113. }



   (连接页面请求和服务层,获取页面请求的参数,通过自动装配,映射不同的URL到相应的处理函数,并获取参数,对参数进行处理,之后传给服务层)
14.创建jsp页面

add.jsp

 

 

 
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  3. <html>

  4. <head>

  5. <title>添加数据</title>

  6. </head>

  7. <body>

  8. <form action="<%=request.getContextPath() %>/addInfo.do" method="post">

  9. 用户名:<input type="text" name="username">

  10. 密码:<input type="password" name="password">

  11. <input type="submit" value="提交数据">

  12. </form>

  13. </body>

  14. </html>


index.jsp

 

 

 
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  3. <html>

  4. <head>

  5. <title>My JSP 'index.jsp' starting page</title>

  6. </head>

  7. <body>

  8. <h1>---${loginUser}---</h1>

  9. <a href="add.jsp">新增数据</a>

  10. <a href="getAll.do">查看全部数据</a>

  11. </body>

  12. </html>


listAll.jsp

 

 

 
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

  2. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

  3. <%

  4. String path = request.getContextPath();

  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

  6. %>

  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  8. <html>

  9. <head>

  10. <title>所有用户所有信息</title>

  11. </head>

  12. <body>

  13. <h3><center>所有用户所有信息</center></h3>

  14. <table width="300px" border="1" cellpadding="0" cellspacing="0" align="center">

  15. <tr>

  16. <td>编号</td>

  17. <td>用户名</td>

  18. <td>密码</td>

  19. <td>操作</td>

  20. </tr>

  21. <c:forEach var="list" items="${addLists}">

  22. <tr>

  23. <td>${list.id}</td>

  24. <td>${list.username}</td>

  25. <td>${list.password}</td>

  26. <td><a href="modify.do?id=${list.id}">更新</a>    <a href="del.do?id=${list.id}">删除</a></td>

  27. </tr>

  28. </c:forEach>

  29. </table>

  30. </body>

  31. </html>


login.jsp

 

 

 
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  3. <html>

  4. <head>

  5. <title>用户登录</title>

  6. </head>

  7. <body>

  8. <form action="<%=request.getContextPath() %>/login.do" method="post">

  9. 用户名:<input type="text" name="username" >

  10. 密码:<input type="password" name="password" >

  11. <input type="submit" value="登录">

  12. </form>

  13. </body>

  14. </html>

 

 

modify.jsp

 

 
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  3. <html>

  4. <head>

  5. <title>修改数据</title>

  6. </head>

  7. <body>

  8. <form action="<%=request.getContextPath() %>/update.do" method="post">

  9. 用户名:<input type="text" name="username" value="${add.username}">

  10. 密码:<input type="password" name="password" value="${add.password}">

  11. <input type="hidden" name="id" value="${add.id }">

  12. <input type="submit" value="提交数据">

  13. </form>

  14. </body>

  15. </html>



result.jsp

 

 

 
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

  2. <%

  3. String path = request.getContextPath();

  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

  5. %>

  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  7. <html>

  8. <head>

  9. <title>结果页</title>

  10. </head>

  11. <body>

  12. ${InfoMessage}

  13. <a href="<%=basePath%>">返回首页</a>

  14. </body>

  15. </html>


 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值