你的位置:首页 > Java教程

[Java教程]java springmvc mybatis mysql


仅供参考

  java springMvc mybatis mylsq 项目搭建

1.开发环境:

  window 64、jdk 1.7.0_51、eclipse、tomcat 7

2.jdk安装与环境变量配置

  http://jingyan.baidu.com/article/6dad5075d1dc40a123e36ea3.html

3.项目搭建

  jar包: http://pan.baidu.com/s/1cyXn8E

  jar包中有poi包、pdf包等,后续能用到

  1)根据自身需求搭建

      

  2)spring-mybatis-config.

<??><beans ="http://www.springframework.org/schema/beans"  ="http://www.w3.org/2001/  ="http://www.springframework.org/schema/aop"  ="http://www.springframework.org/schema/tx"  ="http://www.springframework.org/schema/context"  xsi:schemaLocation="  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  <!-- 扫描,应用spring注解配置 -->  <context:component-scan base-package="com.springmvc.dao"/>  <context:component-scan base-package="com.springmvc.service"/>  <bean id="propertyConfigurer"     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  </bean>   <!-- 数据源 -->  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>  <property name="url" value="jdbc:mysql://localhost:3306/test"></property>  <property name="username" value="root"></property>  <property name="password" value="root"></property>  <property name="maxActive" value="100"></property>  <property name="maxIdle" value="30"></property>  <property name="maxWait" value="500"></property>  <property name="defaultAutoCommit" value="true"></property>  </bean>  <!-- 工厂 -->  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">    <property name="dataSource" ref="dataSource" />  <!-- MyBatis 映射器 -->     <property name="mapperLocations" value="classpath*:com/springmvc/sqlmap/*. />  </bean>    <!-- SQLsession -->  <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">    <constructor-arg index="0" ref="sqlSessionFactory" />  </bean>   <!-- 配置事务 -->  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   <property name="dataSource" ref="dataSource" />  </bean>   <!-- 事物配置 -->   <aop:config>     <aop:advisor pointcut="execution(* com.springmvc..service..*.*(..))" advice-ref="txAdvice"/>   </aop:config>  <tx:advice id="txAdvice" transaction-manager="transactionManager">     <tx:attributes>       <tx:method name="*" propagation="REQUIRED"/>      <tx:method name="get*" read-only="false"/>       <tx:method name="find*" read-only="false"/>      <tx:method name="select*" read-only="false"/>     </tx:attributes>   </tx:advice>  <!-- 使用dao接口,自动实现dao -->  <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">   <property name="mapperInterface" value="com.springmvc.dao.UserDao" />   <property name="sqlSessionFactory" ref="sqlSessionFactory" />  </bean></beans>

配置文件

    3) User.java 实体类

 1 package com.springmvc.model; 2  3 import java.io.Serializable; 4  5 public class User implements Serializable { 6    7   private static final long serialVersionUID = -8772180261203847538L; 8    9   private Long id;10   private String name;11   private String email;12   private String isEmail;13   private String password;14   private String isDelete;15   public Long getId() {16     return id;17   }18   public void setId(Long id) {19     this.id = id;20   }21   public String getName() {22     return name;23   }24   public void setName(String name) {25     this.name = name;26   }27   public String getEmail() {28     return email;29   }30   public void setEmail(String email) {31     this.email = email;32   }33   public String getIsEmail() {34     return isEmail;35   }36   public void setIsEmail(String isEmail) {37     this.isEmail = isEmail;38   }39   public String getPassword() {40     return password;41   }42   public void setPassword(String password) {43     this.password = password;44   }45   public String getIsDelete() {46     return isDelete;47   }48   public void setIsDelete(String isDelete) {49     this.isDelete = isDelete;50   }51 52 }

User.java实体类

   4)UserDao.java 接口dao

package com.springmvc.dao;import java.util.List;import com.springmvc.model.User;public interface UserDao {  //简单一个查询  public List<User> getUser(User user);}

dao接口

   5)UserService.java 接口service

service接口

   6)UserServiceImpl.java service接口实现

package com.springmvc.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.springmvc.dao.UserDao;import com.springmvc.model.User;import com.springmvc.service.UserService;@Servicepublic class UserServiceImpl implements UserService {  @Autowired  private UserDao userDao;  @Override  public List<User> getUser(User user) {    return userDao.getUser(user);  }}

service接口实现

  7)UserEntity.

<??><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.springmvc.dao.UserDao">  <parameterMap type="com.springmvc.model.User" id="pa_user">    <parameter property="id" javaType="Long" jdbcType="NUMERIC"/>    <parameter property="name" javaType="String" jdbcType="VARCHAR" />    <parameter property="email" javaType="String" jdbcType="VARCHAR" />    <parameter property="isEmail" javaType="String" jdbcType="VARCHAR" />    <parameter property="password" javaType="String" jdbcType="VARCHAR" />    <parameter property="isDelete" javaType="String" jdbcType="VARCHAR" />  </parameterMap>  <resultMap id="rm_user" type="com.springmvc.model.User">    <result property="id" column="id" javaType="Long" jdbcType="NUMERIC" />    <result property="name" column="name" javaType="String" jdbcType="VARCHAR" />    <result property="email" column="email" javaType="String" jdbcType="VARCHAR" />    <result property="isEmail" column="isEmail" javaType="String" jdbcType="VARCHAR" />    <result property="password" column="password" javaType="String" jdbcType="VARCHAR" />    <result property="isDelete" column="isDelete" javaType="String" jdbcType="VARCHAR" />  </resultMap>  <select id="getUser" resultMap="rm_user" parameterType="com.springmvc.model.User">    select * from user     <where>      1=1       <if test="name !=null and name !=''">        <![CDATA[and name = '${name}']]>      </if>      <if test="password !=null and password !=''">        <![CDATA[and password = '${password}']]>      </if>        <![CDATA[and isEmail = '1']]>        <![CDATA[and isDelete = '0']]>    </where>  </select></mapper>

sql配置文件

  8)web.

   现在配置的访问后缀:.htm

<??><web-app ="http://www.w3.org/2001/ ="http://java.sun.com/ xsi:schemaLocation="http://java.sun.com/ id="WebApp_ID" version="3.0"> <display-name>springmvc</display-name>    <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath*:spring-mybatis/spring-mybatis-config.</param-value>  </context-param>   <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <!--请求中定义编码 其中encoding是表示设置request的编码,forceEncoding表示是否同时设置response的编码  -->  <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>    <init-param>      <param-name>forceEncoding</param-name>      <param-value>true</param-value>    </init-param>  </filter>  <filter-mapping>    <filter-name>encodingFilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>      <servlet>      <servlet-name>dispatcher</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>      <load-on-startup>1</load-on-startup>   </servlet>   <servlet-mapping>    <servlet-name>dispatcher</servlet-name>    <url-pattern>*.htm</url-pattern>   </servlet-mapping>       <!-- 没有找到请求加载的页面 -->   <error-page>    <error-code>500</error-code>    <location>/500.jsp</location>  </error-page>   <error-page>    <error-code>404</error-code>    <location>/404.jsp</location>  </error-page>    <welcome-file-list>    <welcome-file>index.html</welcome-file>  </welcome-file-list></web-app>

  9)dispatcher-servlet.

<??><beans ="http://www.springframework.org/schema/beans"  ="http://www.w3.org/2001/  ="http://www.springframework.org/schema/mvc"  ="http://www.springframework.org/schema/context"   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.2.xsd">  <!-- 启用spring mvc 注解 -->   <context:annotation-config />   <!-- 设置使用注解的类所在的jar包 -->  <context:component-scan base-package="com.springmvc.action"/>   <!-- @ResponseBody JSON转换 -->   <mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">      <property name="favorPathExtension" value="false" />     <property name="favorParameter" value="false" />      <property name="ignoreAcceptHeader" value="false" />      <property name="mediaTypes" >        <value>         atom=application/atom+</value>      </property>   </bean>  <!-- 视图分解器 -->  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >    <property name="prefix" value="/WEB-INF/view/" />    <property name="suffix" value=".jsp" />  </bean></beans>

  10)页面  登入也使用bootstrap,因为可以省去画页面时间。下面的链接下载包括bootstrap、jquery、easyui等

    http://pan.baidu.com/s/1ciIn5W

  这里是在前台去的绝对路径,先写一个简单的登入功能,等后续开发时,在后台设置

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%> <!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"><jsp:include page="/WEB-INF/util/bootstrap.jsp"></jsp:include><script type="text/javascript" src="<%= basePath %>static/view/js/login.js"> </script><title>登入</title><style type="text/css">  .tab-content{    position:absolute;    height:200px;    width:300px;    margin-top:180px;    margin-left:50%;    left:-150px;  }  .login-input{    margin :20px 0px;    width : 300px;  }</style></head><body>  <div class="tab-content">    <ul class="nav nav-tabs">      <li class="active"><a href="#login" aria-controls="login" role="tab" data-toggle="tab" aria-controls="login">登录</a></li>      <li><a href="#register" aria-controls="register" role="tab" data-toggle="tab" aria-controls="register">注册</a></li>    </ul>    <!-- Tab Log in -->    <form class="tab-pane fade in active" id="login" onsubmit="return false;">      <c:if test="${!empty error }">        <c:out value="${error }"/>      </c:if>      <input id="login-email" name="email" class="form-control login-input" placeholder="邮箱">      <input type="password" name="password" id="login-password" class="form-control login-input" placeholder="密码">      <div class="checkbox">      <label class="f-white" style="color:white;">      <input type="checkbox" id="login-remember"> 记住我      </label>      <a class="pull-right" href="javascript:void(0);" style="color:#33B74B;">忘记密码</a>      </div>      <button class="btn btn-lg btn-primary btn-block" onclick="loginFunction.loginSubmit();">登录</button>    </form>    <!-- Tab Register -->    <form class="tab-pane fade" id="register" onsubmit="return false;">      <input id="login-email" class="form-control login-input" placeholder="邮箱">      <input type="password" class="form-control login-input" placeholder="密码">      <button class="btn btn-lg btn-primary btn-block">注册</button>    </form>   </div>  <div id="banner" style="background-image:url(<%= basePath %>static/images/banner-image.jpg);height:575px;width:100%;">   </div></body></html>

  11)静态文件  大多数开发都把静态文件放在公共文件中,方便维护、查找

<%@ page language="java" import="java.util.*" 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"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><link href="${basePath}static/bootstrap/css/bootstrap.min.css" rel="stylesheet"><script type="text/javascript" src="${basePath}static/js/jquery.min.js"></script><script type="text/javascript" src="${basePath}static/bootstrap/js/bootstrap.min.js"></script><script type="text/javascript">  var basePath = "${basePath}";</script></head>

  12)页面对应的js文件 个人习惯单写一个js,也有很多开发者把js写在对应的页面里

  这里js写的时候有点蒙,因为开发团队有很多人,对应写的页面不同,js可能相似,这样可以避免冲突(loginFunction=页面名称+function)

var loginFunction={    //登入    loginSubmit : function(){      var email = $("#login-email").val();//邮箱      var password = $("#login-password").val();//密码      if(email =="") {        alert("请输入邮箱");        return;      }      if(password =="") {        alert("请输入密码");        return;      }      //$("#login").attr("action",basePath+"index.htm");      //$("#login").submit();      $.ajax({        url:basePath+"101/loginCheck.htm",        type:"post",        data:{email : email,password:password},//密码得加密        dataType:"json",        success: function(data){          if(data.status == "success"){            window.location.href = basePath+"101/index.htm";          }else{            alert("用户名或密码错误");          }        },         error : function(data) {                  }      });          }};$(function(){});

  13)action-简单写了一个验证功能,正常情况密码加密、设置session等,这些后续开发

package com.springmvc.action;import java.util.HashMap;import java.util.List;import java.util.Map;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.ResponseBody;import com.springmvc.model.User;import com.springmvc.service.UserService;@Controller@RequestMapping(value = "/101")public class IndexAction {  @Autowired  private UserService userService;  /**   * 首页   *   * @return   */  @RequestMapping(value = "/index.htm")  public String index() {    return "index";  }  /**   * 登入页面   *   * @return   */  @RequestMapping(value = "/login.htm")  public String login() {    return "login";  }  /**   * 登入验证   *   * @return   */  @RequestMapping(value = "/loginCheck.htm", method = RequestMethod.POST)  @ResponseBody  public Map<String, Object> loginCheck(User user) {    List<User> list = userService.getUser(user);    Map<String, Object> map = new HashMap<String, Object>();    if (list != null && list.size() > 0) {      map.put("status", "success");      map.put("message", "验证成功");    }    return map;  }}

http://localhost:8080/springmvc/101/login.htm

个人笔记