搭建Spring4+Spring4MVC+SpringData+JPA+Hibernate4项目

第一步,准备spring4、springdata、jpa、hibernate、c3p0、mysql、log4j的jar包

第二步,新建dynamic web project,将jar包放入lib目录,并build path

第三步,配置web.xml


<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">



    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext.xmlparam-value>
    context-param>

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

  

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

    
    <servlet-mapping>
        <servlet-name>springDispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

 
    <filter>
        <filter-name>characterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>characterEncodingFilterfilter-name>
        <url-pattern>/url-pattern>
    filter-mapping>
web-app>

第四步,配置数据库配置文件db.properties

user=root
password=
jdbcUrl=jdbc:mysql:///ssshj
driverClass=com.mysql.jdbc.Driver

第五步,新建package

> com.dobeyue.dao 
> com.dobeyue.entities 
> com.dobeyue.service
> com.dobeyue.serviceImpl
> com.dobeyue.handler

第六步,配置log4j.properties(debug时使用,正式使用关闭debug)

log4j.rootLogger=debug,stdout,logfile

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

log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=jbit.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n

log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

第七步,配置applicationContext.xml


<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:context="http://www.springframework.org/schema/context"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p"
    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.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
    
    <context:property-placeholder location="classpath:db.properties"/>
    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        p:user="${user}" p:password="${password}"
        p:driverClass="${driverClass}" p:jdbcUrl="${jdbcUrl}" />
    
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource">property>
        <property name="packagesToScan" value="com.dobeyue">property>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">bean>
        property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.show_sql">trueprop>
                <prop key="hibernate.format_sql">trueprop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialectprop>
                <prop key="hibernate.hbm2ddl.auto">updateprop>
            props>
        property>
    bean> 
    
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    bean>
    
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
    
    <jpa:repositories base-package="com.dobeyue" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>
    
    <context:component-scan base-package="com.dobeyue">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>
    <aop:aspectj-autoproxy/>
beans>

第八步,配置WEB-INF/springDispatcherServlet-servlet.xml文件


<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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        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.1.xsd">
    <context:component-scan base-package="com.dobeyue">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
beans>

第九步,新建User.java文件

package com.dobeyue.entities;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.springframework.stereotype.Component;

@Table(name="my_users")
@Entity
@Component
public class User {
    private Long id;
    private String username;
    private String password;
    @GeneratedValue
    @Id
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public User() {
        // TODO Auto-generated constructor stub
    }
    public User(String username, String password) {
        super();
        this.username = username;
        this.password = password;
    }
}

新建UserDao.java文件

package com.dobeyue.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import com.dobeyue.entities.User;

public interface UserDao extends JpaRepository{
    @Modifying@Transactional
    @Query(value="UPDATE my_users SET  password=?,username=?  WHERE id = 1",nativeQuery=true)
    public void update(String password,String username);
}

新建UserService.java文件

package com.dobeyue.service;

public interface UserService {
    public void update(String password,String username);
}

新建UserServiceImpl.java文件

package com.dobeyue.serviceImpl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dobeyue.dao.UserDao;
import com.dobeyue.service.UserService;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    @Transactional
    public void update(String password, String username) {
//      userDao.save(new User(password, username));
        userDao.update(password, username);
    }

}

新建UserHandler.java文件

package com.dobeyue.handler;

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 com.dobeyue.service.UserService;

@Controller
public class UserHandler {
    @Autowired
    private UserService userService;
    @RequestMapping(value="update",method=RequestMethod.POST)
    public String update(String username,String password){
        userService.update(password, username);
        return "index.jsp";
    }
}

新建index.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
    <form action="update" method="post">
        <input type="text" name="username"/>
        <input type="password" name="password"/>
        <button type="submit">submitbutton>
    form>
body>
html>

最后启动程序即可。

你可能感兴趣的:(javaweb)