搭建环境:
-Win10专业版
-JetBrains IDEA 2017.1.5
-JDK1.8
-MySQL5.7
-Tomcat9
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driverproperty>
<property name="connection.url">jdbc:mysql://localhost:3306/j2eetestproperty>
<property name="dialect">org.hibernate.dialect.MySQL57Dialectproperty>
<property name="show_sql">trueproperty>
<property name="format_sql">trueproperty>
<property name="hbm2ddl.auto">validateproperty>
<mapping class="cn.hust.entity.User"/>
<mapping resource="cn/hust/entity/User.hbm.xml"/>
session-factory>
hibernate-configuration>
选择IDEA界面左下侧边的“Persistence”:
右键项目名,如下图选择:
点击之后出现界面:
在“Choose Data Source”上配置数据库:
可以点击“Test Connection”测试一下是否可以连接上该数据库。
之后,选择刚才创建的数据库连接,在Package选择保存的包,将“entity suffix”删除,勾选上需要持久化的表,点击OK即可。
此时entity包下多出了两个文件:
原来的hibernate.cfg.xml也加入了相关映射:
6. spring相关配置文件
在conf目录下创建配置文件db.properties:
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/j2eetest
db.username=root
db.password=yourpassword
在conf目录下创建Spring配置文件applicationContext.xml:
上图中上方的提示一定要点,再次强调。
applicationContext.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:tx="http://www.springframework.org/schema/tx"
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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="cn.hust"/>
<context:property-placeholder location="classpath:/conf/db.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${db.driverClassName}"/>
<property name="jdbcUrl" value="${db.url}"/>
<property name="user" value="${db.username}"/>
<property name="password" value="${db.password}"/>
<property name="initialPoolSize" value="2"/>
<property name="minPoolSize" value="1"/>
<property name="maxPoolSize" value="10"/>
bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:/conf/hibernate.cfg.xml" />
<property name="dataSource" ref="dataSource" />
bean>
<bean id="ht" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
bean>
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
bean>
<tx:annotation-driven transaction-manager="txManager"/>
beans>
以下采取程序注解的方式进行spring注入,而非采取配置文件中配置的方式。
简要说明一下用的注解:
dao层代码如下:
BaseDAO接口类:
package cn.hust.dao;/*Created by LCJ on 2017.7.15.*/
import java.util.List;
public interface BaseDAO {
boolean add(Object o);
boolean delete(Object o);
boolean update(Object o);
List find(Object o);
}
BaseDAOImpl.java实现类:
package cn.hust.dao.Impl;/*Created by LCJ on 2017.7.15.*/
import cn.hust.dao.BaseDAO;
import org.hibernate.FlushMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Repository
@Transactional
@Scope("prototype")
public class BaseDAOImpl implements BaseDAO {
private HibernateTemplate ht;
@Autowired
public void setHt(HibernateTemplate ht) {
this.ht = ht;
}
private HibernateTemplate getHt() {
ht.setCacheQueries(true);
ht.getSessionFactory().getCurrentSession().setHibernateFlushMode(FlushMode.AUTO);
return ht;
}
@Override
public boolean add(Object o) {
try {
this.getHt().save(o);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public boolean delete(Object o) {
try {
this.getHt().delete(o);
return true;
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public boolean update(Object o) {
try {
this.getHt().update(o);
return true;
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public List find(Object o) {
return this.getHt().findByExample(o);
}
}
service层代码:
UserService接口类:
package cn.hust.service;/*Created by LCJ on 2017.7.15.*/
import cn.hust.entity.User;
public interface UserService {
User checkLogin(String name, String pass);
boolean register(String name, String pass);
}
UserServiceImpl.java实现类:
package cn.hust.service.Impl;/*Created by LCJ on 2017.7.15.*/
import cn.hust.dao.BaseDAO;
import cn.hust.entity.User;
import cn.hust.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@Scope("prototype")
public class UserServiceImpl implements UserService {
@Autowired
private BaseDAO baseDAO;
@Override
public User checkLogin(String name, String pass) {
User u = new User();
u.setUsername(name);
u.setPassword(pass);
List users = baseDAO.find(u);
if (users.size() != 0) return (User)users.get(0);
return null;
}
@Override
public boolean register(String name, String pass) {
User u = new User();
u.setUsername(name);
u.setPassword(pass);
List users = baseDAO.find(u);
return users.size() == 0 && baseDAO.add(u);
}
}
action层代码:
UserAction.java
package cn.hust.action;/*Created by LCJ on 2017.7.15.*/
import cn.hust.entity.User;
import cn.hust.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
@Controller
@Scope("prototype")
public class UserAction extends ActionSupport {
@Autowired
private UserService userService;
private String username;
private String password;
public String login() {
User user = userService.checkLogin(username, password);
if (user != null) return SUCCESS;
return ERROR;
}
public String register() {
if (userService.register(username, password)) return SUCCESS;
return ERROR;
}
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;
}
}
配置struts.xml如下:
<struts>
<constant name="struts.devMode" value="false"/>
<constant name="struts.objectFactory" value="spring"/>
<package name="user" namespace="/" extends="struts-default">
<action name="login" class="cn.hust.action.UserAction" method="login">
<result name="success">/success.jspresult>
<result name="error">/index.jspresult>
action>
<action name="register" class="cn.hust.action.UserAction" method="register">
<result name="success">/index.jspresult>
<result name="error">/register.jspresult>
action>
package>
struts>
web.xml如下:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>MyDemodisplay-name>
<welcome-file-list>
<welcome-file>index.htmlwelcome-file>
<welcome-file>index.htmwelcome-file>
<welcome-file>index.jspwelcome-file>
<welcome-file>default.htmlwelcome-file>
<welcome-file>default.htmwelcome-file>
<welcome-file>default.jspwelcome-file>
welcome-file-list>
<filter>
<filter-name>struts2filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
filter>
<filter-mapping>
<filter-name>struts2filter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:/conf/applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
web-app>
index.jsp:
<%--
Created by IntelliJ IDEA.
User: LCJ
Date: 2017.7.14
Time: 01:02
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录title>
head>
<body>
<form action="login.action" method="post">
<input type="text" name="username" placeholder="输入用户名" />
<br/>
<input type="password" name="password" placeholder="输入密码" />
<br />
<input type="submit" value="登录">
<input type="reset" value="重置">
<div>
<a href="register.jsp">还没有账号?点此注册a>
div>
form>
body>
html>
register.jsp:
<%--
Created by IntelliJ IDEA.
User: LCJ
Date: 2017.7.14
Time: 11:40
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Registertitle>
head>
<body>
<form action="register.action" method="post">
<input type="text" name="username" placeholder="输入用户名" />
<br/>
<input type="password" name="password" placeholder="输入密码" />
<br />
<input type="submit" value="注册">
<input type="reset" value="重置">
form>
body>
html>
success.jsp:
<%--
Created by IntelliJ IDEA.
User: LCJ
Date: 2017.7.13
Time: 11:21
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Successtitle>
head>
<body>
<p>Success!p>
body>
html>
最后配置一下tomcat,运行即可实现用户登录注册功能啦!