程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> java springmvc mybatis mysql,springmvcmybatis

java springmvc mybatis mysql,springmvcmybatis

編輯:JAVA綜合教程

java springmvc mybatis mysql,springmvcmybatis


僅供參考

  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.xml  配置文件,spring 數據庫連接、事務等寫在一起了,可以分開

<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="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 映射器 XML 文件 --> <property name="mapperLocations" value="classpath*:com/springmvc/sqlmap/*.xml" /> </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; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public List<User> getUser(User user) { return userDao.getUser(user); } } service接口實現

  7)UserEntity.xml 寫sql語句文件-簡單寫一個查詢語句,select id 對應到方法名

<?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.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.xml配置-網上有很多這些配置,不理解的可以在網上查詢資料

   現在配置的訪問後綴:.htm

<?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_3_0.xsd" 
 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.xml</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.xml  dispatcher對應的配置文件servlet

<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="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+xml  
                html=text/html  
                json=application/json  
                *=*/*  
            </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" >
            <input type="checkbox" id="login-remember"> 記住我
            </label>
            <a class="pull-right" href="javascript:void(0);" >忘記密碼</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" > 
    </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

個人筆記

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved