eclipse+springmvc+mybatis+mysql搭建web工程

        本人在使用eclipse+springMVC+mybatis+mysql搭建web工程时,总结了一些经验和方法,供大家学习交流。之所以采用这些工具和技术搭建工程,是因为它们的应用比较广泛且是开源的,有很多的资料可供参考,在较长的时间内不会被淘汰,废话少说直接上干货。

说明:eclipse中的maven工程和基础的数据库安装、环境搭建大家可在网上搜索,比较多,不再赘述。

1、工程目录结构

1)后台java文件

eclipse+springmvc+mybatis+mysql搭建web工程_第1张图片

   2)配置文件

eclipse+springmvc+mybatis+mysql搭建web工程_第2张图片

   3)前端jsp页面(如果创建工程中没有WEB-INF目录可在eclipse中配置生成;views是自己添加的)

eclipse+springmvc+mybatis+mysql搭建web工程_第3张图片

2、具体文件内容及说明

1)UserController.java(控制层文件,主要负责客户端的请求拦截,调用业务层进行处理,并将处理结果返回到前端的jsp页面)

package com.bj58.stp.controller;

import javax.servlet.http.HttpServletRequest;

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

import org.springframework.context.annotation.Scope;

import org.springframework.stereotype.Controller;

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

import com.bj58.stp.entity.User;

import com.bj58.stp.service.UserService;

 

//@Controller注解用于标示本类为web层控制组件

@Controller

 //@RequestMapping("/user")用于标定访问时对url位置

   @RequestMapping("/user")

 //在默认情况下springmvc的实例都是单例模式,所以使用scope域将其注解为每次都创建一个新的实例

   @Scope("prototype")

   public class UserController{

       @Autowired

        UserService userService;

       @RequestMapping("/login")

       public String login(User user,HttpServletRequest request){

            //调用login方法来验证是否是注册用户

            boolean loginType = userService.login(user.getUsername(),user.getPassword());

            if(loginType){

                //如果验证通过,则将用户信息传到前台

                request.setAttribute("user",user);

                //并跳转到success.jsp页面

                return "success";

            }else{

                //若不对,则将错误信息显示到错误页面

                request.setAttribute("message","用户名密码错误");

                return "fail";

            }

        }

   }

 

2)IUserDao.java(持久层文件,主要封装了数据访问对象,便于对数据库进行访问操作)

package com.bj58.stp.dao;

import com.bj58.stp.entity.User;

public interface IUserDao {

    public User selectById(int id);

    public User selectByName(String username);

 

}

   3User(实体层文件,对应数据库中具体的表;变量对应表中的字段)

package com.bj58.stp.entity;

public class User {

    private int id;

    private String username;

    private String password;

   

    public String getPassword() {

        return password;

    }

    public void setPassword(String password) {

        this.password=password;

    }

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id=id;

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username=username;

    }

}

 

4)UserServiceImpl.java(实现层文件,这是业务层负责业务逻辑的处理,实现的是UserService接口)

package com.bj58.stp.impl;

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

import org.springframework.stereotype.Service;

import com.bj58.stp.dao.IUserDao;

import com.bj58.stp.entity.User;

import com.bj58.stp.service.UserService;

 

//@Service("UserService") 注解用于标示此类为业务层组件,在使用时会被注解的类会自动由

//spring进行注入,无需我们创建实例

@Service("UserService")

public class UserServiceImpl implements UserService{

    //自动注入iuserdao 用于访问数据库

    @Autowired

    IUserDao Mapper;

    //登录方法的实现,从jsp页面获取username与password

    public boolean login(String username,String password) {

        //对输入账号进行查询,取出数据库中保存对信息

        User user=Mapper.selectByName(username);

        if(user!=null) {

            if(user.getUsername().equals(username)&&user.getPassword().equals(password))

                return true;

        }

        return false;

    }

}

 

5)UserService.xml(mybatis配置文件,映射面向对象和关系型数据库的关系)

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.bj58.stp.dao.IUserDao">

     

      <select id="selectByName" parameterType="string" resultType="User">

          select * from user  where username=#{username}

      select>

      <select id="selectById" parameterType="int" resultType="User">

          select * from user  where id=#{id}

      select>

 mapper>

 

6)UserService(接口文件,定义业务操作具体实现在子类中)

package com.bj58.stp.service;

public interface UserService {

    public boolean login(String username,String password);

}

 

7applicationContext.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:p="http://www.springframework.org/schema/p"

    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

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

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

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

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

        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">

 

   

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

   

    <bean id="jdbcDataSource"

        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="${jdbc.driver}" />

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

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

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

    bean>

   

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

       

        <property name="dataSource" ref="jdbcDataSource" />

       

        <property name="typeAliasesPackage" value="com.bj58.stp.entity">property>

       

        <property name="mapperLocations"

            value="classpath*:com/bj58/stp/mapper/*.xml">property>  

    bean>

   

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

       

        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>

       

        <property name="basePackage" value="com.bj58.stp.dao">property>

    bean>

     

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">

        <constructor-arg index="0" ref="sqlSessionFactory" />

    bean>

     

    <context:component-scan base-package="com.bj58.stp">

        <context:exclude-filter type="aspectj" expression="com.bj58.stp.dao.*"/>

       

    context:component-scan>

    <aop:aspectj-autoproxy proxy-target-class="true">aop:aspectj-autoproxy>

beans>

 

8db.properties

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://10.252.61.65:3306/ftp?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull

jdbc.username=root

jdbc.password=root

 

9log4j.properties

################ FATAL, ERROR, WARN, INFO, DEBUG

log4j.rootLogger=WARN

### stdout  ,stdout,D,E ###

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.Target=System.out

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern= %d{ABSOLUTE} %5p %c{1}:%L - %m%n

### logFile ###

### save error to another file ###

log4j.appender.D=org.apache.log4j.DailyRollingFileAppender

log4j.appender.D.File=D:/logs/test-error.log

log4j.appender.D.Append=true

#error only in this file

log4j.appender.D.Threshold =WARN

log4j.appender.D.layout=org.apache.log4j.PatternLayout

log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%t:%r] - [%p]  %m%n

 

10springmvc-servlet.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.xsd

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

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

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

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

 

   

    <context:component-scan base-package="com.bj58.stp.controller" />

   

    <mvc:default-servlet-handler />

   

    <mvc:annotation-driven />

   

    <bean

        class="org.springframework.web.servlet.view.InternalResourceViewResolver"

        id="internalResourceViewResolver">

       

        <property name="prefix" value="/WEB-INF/views/" />

       

        <property name="suffix" value=".jsp" />

    bean>

   

beans>

 

另外需要两个最终要的配置文件web.xmlpom.xml,具体配置如下:

Web.xml

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

  <display-name>stpdisplay-name>

  <welcome-file-list>

    <welcome-file>index.jspwelcome-file>

  welcome-file-list>

 

  <listener>

      <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>

  listener>

 

  <context-param>

      <param-name>contextConfigLocationparam-name>

      <param-value>classpath:applicationContext.xmlparam-value>

  context-param>

 

  <servlet>

      <servlet-name>springmvcservlet-name>

      <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>

      <init-param>

          <param-name>contextConfigLocationparam-name>

          <param-value>classpath:springmvc-servlet.xmlparam-value>

      init-param>

      <load-on-startup>1load-on-startup>

  servlet>

  <servlet-mapping>

      <servlet-name>springmvcservlet-name>

      <url-pattern>*.dourl-pattern>

  servlet-mapping>

 

  <filter>

      <filter-name>encodingFilterfilter-name>

      <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>

      <init-param>

        <param-name>encodingparam-name>

        <param-value>UTF-8param-value>

    init-param>

  filter>

  <filter-mapping>

      <filter-name>encodingFilterfilter-name>

      <url-pattern>/*url-pattern>

  filter-mapping>

web-app>

 

pom.xml

<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.0modelVersion>

  <groupId>com.bj58.stpgroupId>

  <artifactId>com.bj58.stpartifactId>

  <version>0.0.1-SNAPSHOTversion>

  <packaging>warpackaging>

 

  <repositories>

    <repository>

      <id>maven repoid>

      <url>http://repo1.maven.org/maven2/url>

    repository>

  repositories>

 

  <properties> 

        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>

         

        <spring.version>4.2.0.RELEASEspring.version> 

         

        <slf4j.version>1.6.6slf4j.version> 

        <log4j.version>1.2.12log4j.version> 

         

        <junit.version>4.10junit.version> 

         

        <mybatis.version>3.4.1mybatis.version> 

    properties> 

   

    <dependencies> 

         

        <dependency> 

            <groupId>org.springframeworkgroupId> 

            <artifactId>spring-coreartifactId> 

            <version>${spring.version}version> 

        dependency> 

        <dependency> 

            <groupId>org.springframeworkgroupId> 

            <artifactId>spring-webmvcartifactId> 

            <version>${spring.version}version> 

        dependency> 

        <dependency> 

            <groupId>org.springframeworkgroupId> 

            <artifactId>spring-contextartifactId> 

            <version>${spring.version}version> 

        dependency> 

        <dependency> 

            <groupId>org.springframeworkgroupId> 

            <artifactId>spring-context-supportartifactId> 

            <version>${spring.version}version> 

        dependency> 

        <dependency> 

            <groupId>org.springframeworkgroupId> 

            <artifactId>spring-aopartifactId> 

            <version>${spring.version}version> 

        dependency> 

        <dependency> 

            <groupId>org.springframeworkgroupId> 

            <artifactId>spring-aspectsartifactId> 

            <version>${spring.version}version> 

        dependency> 

        <dependency> 

            <groupId>org.springframeworkgroupId> 

            <artifactId>spring-txartifactId> 

            <version>${spring.version}version> 

        dependency> 

        <dependency> 

            <groupId>org.springframeworkgroupId> 

            <artifactId>spring-jdbcartifactId> 

            <version>${spring.version}version> 

        dependency> 

        <dependency> 

            <groupId>org.springframeworkgroupId> 

            <artifactId>spring-webartifactId> 

            <version>${spring.version}version> 

        dependency> 

 

         

        <dependency> 

            <groupId>junitgroupId> 

            <artifactId>junitartifactId> 

            <version>${junit.version}version> 

            <scope>testscope> 

        dependency> 

 

         

         

        <dependency> 

            <groupId>log4jgroupId> 

            <artifactId>log4jartifactId> 

            <version>${log4j.version}version> 

        dependency> 

        <dependency> 

            <groupId>org.slf4jgroupId> 

            <artifactId>slf4j-apiartifactId> 

            <version>${slf4j.version}version> 

        dependency> 

        <dependency> 

            <groupId>org.slf4jgroupId> 

            <artifactId>slf4j-log4j12artifactId> 

            <version>${slf4j.version}version> 

        dependency> 

         

 

         

        <dependency> 

            <groupId>org.springframeworkgroupId> 

            <artifactId>spring-testartifactId> 

            <version>${spring.version}version> 

            <scope>testscope> 

        dependency> 

 

         

        <dependency> 

            <groupId>org.mybatisgroupId> 

            <artifactId>mybatisartifactId> 

            <version>${mybatis.version}version> 

        dependency> 

 

         

        <dependency> 

            <groupId>org.mybatisgroupId> 

            <artifactId>mybatis-springartifactId> 

            <version>1.3.1version> 

        dependency> 

 

         

        <dependency> 

            <groupId>mysqlgroupId> 

            <artifactId>mysql-connector-javaartifactId> 

            <version>5.1.29version> 

        dependency> 

 

       

        <dependency>

            <groupId>org.codehaus.jacksongroupId>

            <artifactId>jackson-mapper-aslartifactId>

            <version>1.9.13version>

        dependency>

       

        <dependency>

            <groupId>javax.servletgroupId>

            <artifactId>javax.servlet-apiartifactId>

            <version>3.1.0version>

        dependency>

       

       

        <dependency>

            <groupId>javax.servletgroupId>

            <artifactId>servlet-apiartifactId>

            <version>3.0-alpha-1version>

            <scope>providedscope>

        dependency>

        <dependency>

            <groupId>javax.servletgroupId>

            <artifactId>jstlartifactId>

            <version>1.2version>

        dependency>

       

        <dependency>

            <groupId>org.aspectjgroupId>

            <artifactId>aspectjweaverartifactId>

            <version>1.8.5version>

        dependency>

       

        <dependency>

            <groupId>com.fasterxml.jackson.coregroupId>

            <artifactId>jackson-coreartifactId>

            <version>2.5.2version>

        dependency>

        <dependency>

            <groupId>com.fasterxml.jackson.coregroupId>

            <artifactId>jackson-databindartifactId>

            <version>2.5.2version>

        dependency>

    dependencies>

    <build>

    <plugins> 

         

        <plugin> 

            <groupId>org.apache.maven.pluginsgroupId> 

            <artifactId>maven-compiler-pluginartifactId> 

            <version>2.3.2version> 

            <configuration> 

                <source>1.8source>

                <target>1.8target>

                <encoding>UTF-8encoding>

            configuration> 

        plugin> 

       

       

  <plugin>

   <groupId>org.apache.maven.pluginsgroupId>

   <artifactId>maven-surefire-pluginartifactId>

   <version>2.16version>

   <configuration>

      <skip>trueskip>

      <argLine>-Dfile.encoding=UTF-8argLine>

   configuration>

  plugin>    

    plugins> 

  build>

 

project>

 

3、运行工程,访问页面如下:

  1)通过jetty启动服务,在浏览器访问地址:http://localhost:8080/login.jsp

eclipse+springmvc+mybatis+mysql搭建web工程_第4张图片

2)用户名和密码进行登录

eclipse+springmvc+mybatis+mysql搭建web工程_第5张图片

至此demo搭建成功,可以在此基础上进行扩展,从零到一慢慢积累

 

4、踩过的坑

     1、如果启动工程出现文件查找不到,建议查看配置文件中名称和路径是否配置正确

     2、如果服务启动正常访问页面出现404,建议查看jsp或者html前端页面存放路径和返回url是否一致

     3、使用过程中请按照上面给定pom中配置的版本,否则出现版本不兼容服务启动失败(你自己找到合适的其他版本组合也可以)

你可能感兴趣的:(web开发)