SpringMVC+maven+mybatis+mysql配置web应用

来源:互联网 发布:极点五笔linux版 编辑:程序博客网 时间:2024/05/17 07:50

在spring中web配置项目时,确保自己的基础环境是没问题的,maven jdk tomcat 

一,建立数据库

<span style="font-size:12px;">CREATE DATABASE STUDENT_MANAGER;USE STUDENT_MANAGER;/***** 建立student表 *****/CREATE TABLE STUDENT_TBL(   STUDENT_ID         VARCHAR(255) PRIMARY KEY,   STUDENT_NAME       VARCHAR(10) NOT NULL,   STUDENT_SEX        VARCHAR(10),   STUDENT_BIRTHDAY   DATE,   CLASS_ID           VARCHAR(255));/*插入学生数据*/INSERT INTO STUDENT_TBL (STUDENT_ID,                         STUDENT_NAME,                         STUDENT_SEX,                         STUDENT_BIRTHDAY,                         CLASS_ID)  VALUES   (123456,            '威武',            '男',            '1980-08-01',            121546            )</span>

或者去mysql的客户端自己创建数据库和表结构。



二 ,配置maven

通过配置maven文件加载相关的jar包

配置pom.xml文件

<span style="font-size:12px;"><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.0</modelVersion>  <groupId>com.springmvc_mybatis_demo</groupId>  <artifactId>springmvc_mybatis_demo</artifactId>  <packaging>war</packaging>  <version>0.0.1-SNAPSHOT</version>  <name>springmvc_mybatis_demo Maven Webapp</name>  <url>http://maven.apache.org</url>  <!-- spring的版本号 -->  <properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><spring.version>3.2.3.RELEASE</spring.version><jackson.version>2.5.0</jackson.version></properties>  <dependencies>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>3.8.1</version>      <scope>test</scope>    </dependency>        <!-- spring的核心包 -->    <dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version><scope>test</scope></dependency><!-- mybatis的包 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.2.8</version></dependency><!-- mybatis spring的插件 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.2.2</version></dependency><!-- mysql数据库连接 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.34</version></dependency><!-- AOP会使用 --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.4</version></dependency><!-- 配置log4j --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><!-- 配置servlet和jsp --><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>3.0-alpha-1</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><!-- 配置json格式数据 --><dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.9.13</version></dependency><!-- <dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.3</version></dependency> --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>${jackson.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>${jackson.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>${jackson.version}</version></dependency> <!-- 文件上传 --><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.2.2</version></dependency><!-- mybatis --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.30</version></dependency><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.2.2</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.2.2</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.2.7</version></dependency>  </dependencies>      <build>    <finalName>springmvc_mybatis_demo</finalName>  <!-- 给项目配置插件 -->  <!-- 配置Junit单元测试插件 -->  <plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>2.4.2</version><configuration><skipTests>true</skipTests></configuration></plugin><!-- 配置maven的打包 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-war-plugin</artifactId><version>2.3</version><configuration><webXml>src/main/webapp/WEB-INF/web.xml</webXml></configuration></plugin><!-- 生成java的文档 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-javadoc-plugin</artifactId><version>2.9.1</version><configuration><javadocDirectory>target/javadoc</javadocDirectory><reportOutputDirectory>target/javadoc</reportOutputDirectory><charset>UTF-8</charset><encoding>UTF-8</encoding><docencoding>UTF-8</docencoding><show>private</show></configuration></plugin><!-- 部署至本机 --><plugin><groupId>org.codehaus.cargo</groupId><artifactId>cargo-maven2-plugin</artifactId><version>1.0</version><configuration><container><containerId>tomcat7x</containerId><home>D:\apache-tomcat-7.0.56</home></container><configuration><type>existing</type><home>D:\WebServer\apache-tomcat-7.0.56</home></configuration></configuration></plugin></plugins></build></project></span>





配置web.xml

web.xml文件主要配置spring的DispatcherServlet

<span style="font-size:12px;"><?xml version="1.0" encoding="ISO-8859-1"?><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/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"         id="WebApp_ID" version="2.5">    <display-name>springmvc_mybatis_demo</display-name>       <!--- Location of the XML file that defines the root application context.- Applied by ContextLoaderListener.-->    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>/WEB-INF/applicationContext.xml</param-value>    </context-param>    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>            <!--- Servlet that dispatches request to registered handlers (Controller implementations).-->    <servlet>        <servlet-name>web</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>/WEB-INF/mvc-config.xml</param-value>        </init-param>        <load-on-startup>2</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>web</servlet-name>        <url-pattern>*.do</url-pattern>    </servlet-mapping></web-app></span>





配置mvc-config.xml文件

mvc-config文件在web.xml文件中有引用,主要配置jsp的访问路径。这里设置的jsp路径是/WEB-INF/view/jsp/ 必须建立相关的目录

<span style="font-size:12px;"><?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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">    <!-- Uncomment and your base-package here:         <context:component-scan            base-package="org.springframework.samples.web"/>  --><context:component-scan base-package="com" />    <!-- <mvc:annotation-driven /> --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->        <property name="prefix" value="/WEB-INF/view/jsp/"/>        <property name="suffix" value=".jsp"/></bean></beans></span>



配置applicationContext.xml

在这个文件中加载mybatis与spring整合,配置sqlsessionFactory和mapper。mapper扫描dao层的sql文件即     StudentMapper.xml文件

<span style="font-size:12px;"><?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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"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/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"><!-- 配置多个dao,在配置文件中定义JDBCTemplate并注入到每个dao中,扫描包以注册注解申明的Bean --><context:component-scan base-package="com"></context:component-scan><!-- 配置mybatis,导入属性配置文件 --><context:property-placeholder location="classpath:mysql.properties"/><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"><!-- 数据源驱动 --><property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property><!-- 数据源连接 --><property name="url"><value>jdbc:mysql://localhost:3306/student_manager</value></property><!-- 登录用户 --><property name="username"><value>root</value></property><!-- 登录密码 --><property name="password"><value>123456</value></property><!--initialSize: 初始化连接 --><property name="initialSize" value="5" /><!--maxIdle: 最大空闲连接 --><property name="maxIdle" value="10" /><!--minIdle: 最小空闲连接 --><property name="minIdle" value="5" /><!--maxActive: 最大连接数量 --><property name="maxActive" value="15" /><!--removeAbandoned: 是否自动回收超时连接 --><property name="removeAbandoned" value="true" /><!--removeAbandonedTimeout: 超时时间(以秒数为单位) --><property name="removeAbandonedTimeout" value="180" /><!--maxWait: 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 --><property name="maxWait" value="3000" /><property name="logAbandoned" value="true" /><property name="validationQuery"><value>SELECT 1</value></property></bean><!-- 配置spring的jdbc的数据源 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!-- 配置SQLSessionFactory为mybatis核心--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><property name="typeAliasesPackage" value="com.domain"></property><property name="mapperLocations" value="classpath*:com.dao/**/*.xml"></property></bean> <!-- 扫描mapper配置 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">      <property name="sqlSessionFactory" ref="sqlSessionFactory"/>      <property name="basePackage" value="com.dao"/>  </bean>  </beans>       </span>

上面的xml文件的路径在springmvc_mybatis_demo\src\main\webapp\WEB-INF


三,配置mybatis

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><typeAliases><typeAlias alias="StudentEntity" type="com.domain.StudentEntity"/></typeAliases><mappers><mapper resource="com.dao.StudentMapper.xml"/></mappers></configuration>   

四,配置jdbc

#Mysqljdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc\:mysql\://localhost\:3306/sampledbjdbc.username=rootjdbc.password=123456



配置StudentMapper.xml文件

需要

这个文件的主要作用是通过实体类映射sql语句

<span style="font-size:12px;"><?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.dao.StudentMapper"><resultMap type="com.domain.StudentEntity" id="studentResultMap"><id property="studentID" column="STUDENT_ID"/><result property="studentName" column="STUDENT_NAME"/><result property="studentSex" column="STUDENT_SEX"/><result property="studentbirthday" column="STUDENT_BIRTHDAY"/></resultMap><!-- 查询学生,根据id --><select id="getStudent" parameterType="String" resultType="com.domain.StudentEntity" resultMap="studentResultMap"><![CDATA[SELECT * from student_tbl ST WHERE ST.STUDENT_ID]]></select><!-- 查询学生列表 --><select id="getStudentAll" resultType="com.domain.StudentEntity" resultMap="studentResultMap"><![CDATA[SELECT * from student_tbl;]]></select></mapper></span>


三,编写相关的java代码


根据spring的mvc的分层思想,可以把包按功能分成如下几个 

domian包:主要是实体类和实体类接口,这里定义的java对象对应数据库表的字段。ClassEntity.java  StudentEntity.java

dao包:主要实现数据库增删改查的接口文件,以及数据库的sql文件。  StudentMapper.xml StudentMapper.java

service包:只要是业务层的逻辑处理,实现数据库增删该查的接口。和进行负载的业务处理。   接口StudentService.java StudentServiceImpl.java

action包:主要进行页面展示的路径映射,指定相关的前端页面显示。TestController.java

目录结构如图所示:




domain包文件如下:  StudentEntity.java   ClassEntuty.java

StudentEntity.java

package com.domain;import java.io.Serializable;import java.util.Date;public class StudentEntity implements Serializable {/** *  */private static final long serialVersionUID = 5559181761184101398L;private ClassEntity classEntity;private Date studentbirthday;private String studentID;private String studentName;private String studentSex;public ClassEntity getClassEntity() {return classEntity;}public void setClassEntity(ClassEntity classEntity) {this.classEntity = classEntity;}public Date getStudentbirthday() {return studentbirthday;}public void setStudentbirthday(Date studentbirthday) {this.studentbirthday = studentbirthday;}public String getStudentID() {return studentID;}public void setStudentID(String studentID) {this.studentID = studentID;}public String getStudentName() {return studentName;}public void setStudentName(String studentName) {this.studentName = studentName;}public String getStudentSex() {return studentSex;}public void setStudentSex(String studentSex) {this.studentSex = studentSex;}@Overridepublic String toString() {return "StudentEntity [classEntity=" + classEntity+ ", studentbirthday=" + studentbirthday + ", studentID="+ studentID + ", studentName=" + studentName + ", studentSex="+ studentSex + "]";}}


ClassEntuty.java

package com.domain;


public interface ClassEntity {


}
dao包文件如下:StudentMapper.xml StudentMapper.java   这里的xml文件在上面已经配置过。路径需要存放在dao层的目录下面

StudentMapper.java

package com.dao;import java.util.List;import com.domain.StudentEntity;//创建数据访问接口    给studentEntity创建接口public interface StudentMapper {public StudentEntity getStudent(String studentID);public StudentEntity getStudentAndClass(String studentID);public List<StudentEntity> getStudentAll();public void insertStudent(StudentEntity entity);public void deleteStudent(StudentEntity entity);public void updateStudent(StudentEntity entity);}<strong></strong>

service包文件如下:IStudentService.java      StudentServiceImpl.java

IStudentService.java

package com.service;import java.util.List;import org.springframework.transaction.annotation.Transactional;import com.domain.StudentEntity;@Transactionalpublic interface IStudentService {public StudentEntity getStudent(String studentID);public StudentEntity getStudentAndClass(String studentID);public List<StudentEntity> getStudentAll();public void insertStudent(StudentEntity entity);public void deleteStudent(StudentEntity entity);public void updateStudent(StudentEntity entity);}


StudentServiceImpl.java

package com.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.dao.StudentMapper;import com.domain.StudentEntity;import com.service.IStudentService;@Servicepublic class StudentServiceImpl implements IStudentService {@Autowiredprivate StudentMapper studentMapper;public StudentEntity getStudent(String studentID) {return studentMapper.getStudent(studentID);}public StudentEntity getStudentAndClass(String studentID) {return null;}public List<StudentEntity> getStudentAll() {return null;}public void insertStudent(StudentEntity entity) {// TODO Auto-generated method stub}public void deleteStudent(StudentEntity entity) {// TODO Auto-generated method stub}public void updateStudent(StudentEntity entity) {// TODO Auto-generated method stub}}<strong></strong>


action包:TestController.java   这里指向了login.jsp文件

package com.action;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import com.domain.StudentEntity;import com.service.IStudentService;@Controllerpublic class TestController {@Autowiredprivate IStudentService studentService;@RequestMapping("/index")public String index(Model model){StudentEntity student = studentService.getStudent("123456");System.out.println(student.toString());model.addAttribute("st", student);return "login";}}


最后就是页面的显示:

login.jsp文件


<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%><!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=ISO-8859-1"><title>上海微客来运维管理系统</title></head><body><c:if test="${!empty error}"><font color="red"><c:out value="${error}" /></font></c:if><form action="<c:url value='loginCheck.html'/>" method="post">用户名:<input type="text" name="userName"><br>密码:<input type="password" name="password"> <br><input type="submit" value="登陆"/><input type="reset" value="重置"/></form><br/>${st.studentName},${st.studentSex},${st.studentID},</body></html>
至此基于springMVC+ maven+mysql+mybatis框架的web应用就搭建成功了

这是页面:访问路径:这是从数据库获取的信息





0 0
原创粉丝点击