JavaWeb_(Spring框架)在Struts+Hibernate框架中引入Spring框架
spring的功能:简单来说就是帮我们new对象,什么时候new对象好,什么时候销毁对象。
在MySQL中添加spring数据库,添加user表,并添加一条用户数据

使用struts + hibernate框架实现用户登陆功能:当用户在login.jsp中账号密码输入错误,重定向login.jsp,并提示用户输入账号、密码错误,如果用户在login.jsp中账号密码输入正确,跳转到index.html


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8"> <link rel="stylesheet" href="css/head.css" />
<link rel="stylesheet" type="text/css" href="css/login.css" />
</head> <body>
<div class="dvhead">
<div class="dvlogo">
<a href="index.html">你问我答</a>
</div>
<div class="dvsearch">10秒钟注册账号,找到你的同学</div>
<div class="dvreg">
已有账号,立即 <a href="login.html">登录</a>
</div>
</div>
<section class="sec">
<form action="${pageContext.request.contextPath }/UserAction_login" method="post">
<div class="register-box">
<label for="username" class="username_label"> 用 户 名 <input
maxlength="20" name="username" type="text" placeholder="您的用户名和登录名" />
</label>
<div class="tips"></div>
</div>
<div class="register-box">
<label for="username" class="other_label"> 密 码 <input
maxlength="20" type="password" name="password"
placeholder="建议至少使用两种字符组合" />
</label>
<div class="tips"></div>
</div>
<div class="arguement">
<input type="checkbox" id="xieyi" /> 阅读并同意 <a
href="javascript:void(0)">《你问我答用户注册协议》</a> <a href="register.html">没有账号,立即注册</a>
<div class="tips" style="color: red" > <s:property value="#error"/> </div>
</div>
<div class="submit_btn">
<button type="submit" id="submit_btn">立 即 登录</button>
</div>
</form>
</section>
<script src="js/index.js" type="text/javascript" charset="utf-8"></script>
</body>
login.jsp
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd"> <struts>
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant> <package name="spring" namespace="/" extends="struts-default">
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="UserAction_*" class="com.Gary.web.UserAction" method="{1}">
<result name="login">/login.jsp</result>
<result name="toIndex" type="redirect">/index.html</result>
</action>
</package>
</struts>
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///spring</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connecton.password">123456</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property>
<!-- 隔离级别 不可重复读 -->
<property name="hibernate.connection.isolation">4</property> <property name="hibernate.current_session_context_class">thread</property> <mapping resource="com/Gary/domain/User.hbm.xml"/> </session-factory>
</hibernate-configuration>
hibernate.cfg.xml
package com.Gary.web; import com.Gary.domain.User;
import com.Gary.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven; public class UserAction extends ActionSupport implements ModelDriven<User>{ public User user = new User(); public String login() throws Exception { UserService userService = new UserService();
boolean success = userService.findUser(user);
if(success)
{
return "toIndex";
}else {
ActionContext.getContext().put("error", "用户名或者密码错误!!");
return "login";
} } @Override
public User getModel() { return user;
} }
UserAction.java
package com.Gary.utils; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; public class HibernateUtils { private static SessionFactory sessionFactory = null; static {
Configuration config = new Configuration().configure();
sessionFactory = config.buildSessionFactory();
} public static Session getSession()
{
return sessionFactory.openSession();
} public static Session getCurrentSession()
{
return sessionFactory.getCurrentSession();
} }
HibernateUtils.java
package com.Gary.service; import org.hibernate.Transaction; import com.Gary.dao.UserDao;
import com.Gary.domain.User;
import com.Gary.utils.HibernateUtils; public class UserService { public boolean findUser(User user) {
UserDao userDao = new UserDao(); Transaction beginTransaction = HibernateUtils.getCurrentSession().beginTransaction();
User temp = null;
try { temp = userDao.findUser(user);
}catch(Exception e){
beginTransaction.rollback();
} beginTransaction.commit(); return temp==null?false:true; }
}
UserService.java
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.Gary.domain"> <class name="User" table="user">
<id name="id">
<generator class="uuid"></generator>
</id> <property name="username" column="username"></property>
<property name="password" column="password"></property> </class> </hibernate-mapping>
User.hbm.xml
package com.Gary.domain;
public class User {
private String id;
private String username;
private String password;
public String getId() {
return id;
}
public void setId(String 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;
}
}
User.java
package com.Gary.dao; import org.hibernate.Session;
import org.hibernate.query.NativeQuery; import com.Gary.domain.User;
import com.Gary.utils.HibernateUtils; public class UserDao { public User findUser(User user) {
Session session = HibernateUtils.getCurrentSession(); //sql操作数据库
String sql = "select * from user where username = ? and password = ?";
NativeQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.addEntity(User.class);
sqlQuery.setParameter(1, user.getUsername());
sqlQuery.setParameter(2, user.getPassword()); User result = (User) sqlQuery.uniqueResult(); return result;
} }
UserDao.java
Spring介入,启动Spring,在web.xml中进行配置
<!-- 让spring随着web项目的启动而启动 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- 配置spring配置文件的位置 -->
<context-param>
<param-name>contextConfiguration</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<?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>Spring</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <!-- 让spring随着web项目的启动而启动 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- 配置spring配置文件的位置 -->
<context-param>
<param-name>contextConfiguration</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param> <filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>
web.xml
修改UserService.java和UserDao,不用再UserAction中使用UserService userService = new UserService(),使用Spring框架帮我们new对象
package com.Gary.web; import com.Gary.domain.User;
import com.Gary.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven; public class UserAction extends ActionSupport implements ModelDriven<User>{ public User user = new User(); private UserService userService; public String login() throws Exception { boolean success = userService.findUser(user);
if(success)
{
return "toIndex";
}else {
ActionContext.getContext().put("error", "用户名或者密码错误!!");
return "login";
} } @Override
public User getModel() { return user;
} public UserService getUserService() {
return userService;
} public void setUserService(UserService userService) {
this.userService = userService;
} }
UserAction.java
package com.Gary.service; import org.hibernate.Transaction; import com.Gary.dao.UserDao;
import com.Gary.domain.User;
import com.Gary.utils.HibernateUtils; public class UserService { private UserDao userDao; public boolean findUser(User user) { Transaction beginTransaction = HibernateUtils.getCurrentSession().beginTransaction();
User temp = null;
try { temp = userDao.findUser(user);
}catch(Exception e){
beginTransaction.rollback();
} beginTransaction.commit(); return temp==null?false:true;
} public UserDao getUserDao() {
return userDao;
} public void setUserDao(UserDao userDao) {
this.userDao = userDao;
} }
UserService.java
applicationContext.xml中进行Action、Service的配置,Dao暂时不配置
<!-- 配置Action -->
<bean name = "userAction" class="com.Gary.web.UserAction" scope="prototype">
<property name="userService" ref="userService"></property>
</bean> <!-- 配置Service -->
<bean name="userService" class="com.Gary.service.UserService">
<property name="userDao" ref="userDao"></property>
</bean> <!-- 配置Dao -->
<bean name="userDao" class="com.Gary.dao.UserDao">
</bean>
<?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: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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 配置Action -->
<bean name = "userAction" class="com.Gary.web.UserAction" scope="prototype">
<property name="userService" ref="userService"></property>
</bean> <!-- 配置Service -->
<bean name="userService" class="com.Gary.service.UserService">
<property name="userDao" ref="userDao"></property>
</bean> <!-- 配置Dao -->
<bean name="userDao" class="com.Gary.dao.UserDao">
</bean> </beans>
applicationContext.xml
在struts.xml中告诉struts不用创建Action,sping来帮你创建Action
<!-- 告诉struts,你不用创建Action,sping来帮你创建Action -->
<constant name="struts.objectFactory" value="spring"></constant>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd"> <struts>
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant> <!-- 告诉struts,你不用创建Action,sping来帮你创建Action -->
<constant name="struts.objectFactory" value="spring"></constant> <package name="spring" namespace="/" extends="struts-default">
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="UserAction_*" class="com.Gary.web.UserAction" method="{1}">
<result name="login">/login.jsp</result>
<result name="toIndex" type="redirect">/index.html</result>
</action>
</package>
</struts>
struts.xml
引入Spring框架,添加applicationContext.xml

(引入Spring框架后修改过的一些东西)
<?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>Spring</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <!-- 让spring随着web项目的启动而启动 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- 配置spring配置文件的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param> <filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>
web.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: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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 配置Action -->
<bean name = "userAction" class="com.Gary.web.UserAction" scope="prototype">
<property name="userService" ref="userService"></property>
</bean> <!-- 配置Service -->
<bean name="userService" class="com.Gary.service.UserService">
<property name="userDao" ref="userDao"></property>
</bean> <!-- 配置Dao -->
<bean name="userDao" class="com.Gary.dao.UserDao">
</bean> </beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///spring</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connecton.password">123456</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property>
<!-- 隔离级别 不可重复读 -->
<property name="hibernate.connection.isolation">4</property> <property name="hibernate.current_session_context_class">thread</property> <mapping resource="com/Gary/domain/User.hbm.xml"/> </session-factory>
</hibernate-configuration>
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd"> <struts>
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant> <!-- 告诉struts,你不用创建Action,sping来帮你创建Action -->
<constant name="struts.objectFactory" value="spring"></constant> <package name="spring" namespace="/" extends="struts-default">
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="UserAction_*" class="com.Gary.web.UserAction" method="{1}">
<result name="login">/login.jsp</result>
<result name="toIndex" type="redirect">/index.html</result>
</action>
</package>
</struts>
struts.xml
package com.Gary.web; import com.Gary.domain.User;
import com.Gary.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven; public class UserAction extends ActionSupport implements ModelDriven<User>{ public User user = new User(); private UserService userService; public String login() throws Exception { boolean success = userService.findUser(user);
if(success)
{
return "toIndex";
}else {
ActionContext.getContext().put("error", "用户名或者密码错误!!");
return "login";
} } @Override
public User getModel() { return user;
} public UserService getUserService() {
return userService;
} public void setUserService(UserService userService) {
this.userService = userService;
} }
UserAction.java
package com.Gary.service; import org.hibernate.Transaction; import com.Gary.dao.UserDao;
import com.Gary.domain.User;
import com.Gary.utils.HibernateUtils; public class UserService { private UserDao userDao; public boolean findUser(User user) { Transaction beginTransaction = HibernateUtils.getCurrentSession().beginTransaction();
User temp = null;
try { temp = userDao.findUser(user);
}catch(Exception e){
beginTransaction.rollback();
} beginTransaction.commit(); return temp==null?false:true;
} public UserDao getUserDao() {
return userDao;
} public void setUserDao(UserDao userDao) {
this.userDao = userDao;
} }
UserService.java
JavaWeb_(Spring框架)在Struts+Hibernate框架中引入Spring框架的更多相关文章
- 三大框架:Struts+Hibernate+Spring
三大框架:Struts+Hibernate+Spring Java三大框架主要用来做WEN应用. Struts主要负责表示层的显示 Spring利用它的IOC和AOP来处理控制业务(负责对数据库的操作 ...
- Java项目在jsp页面中引入jquery框架的步骤
环境:在Java web项目中引入juqery框架 工具:MyEclipse8.5 [步骤如下] A:新建一个Java web项目TestJquery,在WebRoot目录下创建一个jquery文件 ...
- go微服务框架Kratos笔记(三)引入GORM框架
介绍 GORM是一个使用Go语言编写的ORM框架.中文文档齐全,对开发者友好,支持主流数据库. GORM官方文档 安装 go get -u github.com/jinzhu/gorm 在kratos ...
- 2018.11.11 Java的 三大框架:Struts+Hibernate+Spring
·定义:Java三大框架主要用来做WEN应用.Struts主要负责表示层的显示: Spring利用它的IOC和AOP来处理控制业务(负责对数据库的操作): Hibernate主要是数据持久化到数据库. ...
- JavaWeb_(SSH)三大框架整合struts+hibernate+spring_Demo
三大框架整合 一.SSH导包 二.书写Spring 三.书写Struts 四.整合Spring与Struts 五.书写(与整合)Hibernate.引入c3p0连接池并使用hibernate模板 六. ...
- JavaWeb项目中引入spring框架
主要步骤有以下3步: 1:下载spring的jar包2:在项目中web.xml中添加spring配置3:bean配置文件-applicationContext.xml 1:引入包,这个就不说了,官网下 ...
- 【IDEA】项目中引入Spring MVC
一.原文说明: IntelliJ idea创建Spring MVC的Maven项目 - winner_0715 - 博客园 https://images2015.cnblogs.com/blog/82 ...
- 基于Struts+Hibernate开发过程中遇到的错误
1.import javax.servlet.http.HttpServletRequest 导入包出错 导入包出错,通常是包未引入,HttpServletRequest包是浏览器通过http发出的 ...
- vue项目中引入第三方框架
element-ui npm install element-ui -- save; main.js中 import Element from 'element-ui'; import 'elemen ...
随机推荐
- centos中拉取postgre
新搭建好的linux服务器环境,docker也配置好了. 第一步,下载postgre docker pull postgres:11 这里的版本号自己按照自己的需要来获取. 然而实际上没那么顺利,直接 ...
- Java Thread(线程)案例详解sleep和wait的区别
上次对Java Thread有了总体的概述与总结,当然大多都是理论上的,这次我将详解Thread中两个常用且容易疑惑的方法.并通过实例代码进行解疑... F区别 sleep()方法 sleep()使当 ...
- 初学java2 认识面向对象 以及运算符 输入输出
面向对象 面向对象是一种程序设计思路,在设计一个程序时不需要考虑内部如何实现,只需要想他要实现什么功能 就像在餐馆点菜一样,你不需要知道他应该怎么做,你只需要决定你要吃什么 面向对象三大特征 继承 封 ...
- 关于微信小程序返回页面时刷新页面的实现
在小程序开发中,我们通常会遇到这样的需求:提交某个表单成功后跳转该表单详情页面,但是返回时需要跳转回到首页(注意:我这里的首页是提交表单页的前一个页面),而不能再返回提交表单的页面,并且要在首页中刷新 ...
- Django 之form简单应用
form组件 参考链接:https://www.cnblogs.com/maple-shaw/articles/9537309.html form组件的作用: 1.自动生成input框 2.可以对数据 ...
- Vmvare 虚拟机固定IP
首先我们打开虚拟机的虚拟网络编辑器,打开vmvare菜单栏的编辑,选择虚拟网络编辑器. 在打开的网络虚拟器中,会看到相关信息,虚拟机网络类型采用的NAT模式,子网地址是192.168.89.0,虚 ...
- 《数据结构与算法之美》 <01>复杂度分析(上):如何分析、统计算法的执行效率和资源消耗?
我们都知道,数据结构和算法本身解决的是“快”和“省”的问题,即如何让代码运行得更快,如何让代码更省存储空间.所以,执行效率是算法一个非常重要的考量指标. 那如何来衡量你编写的算法代码的执行效率呢?这里 ...
- E - GCD HDU - 2588
The greatest common divisor GCD(a,b) of two positive integers a and b,sometimes written (a,b),is the ...
- 使用Tarjan进行缩点无向图
int From[maxn],Laxt[maxn],To[maxn<<2],Next[maxn<<2],cnt; int low[maxn],dfn[maxn],times,q ...
- hexo不蒜子网站访问量统计失效
问题 hexo博客的不蒜子网站访问量统计最近失效了. 解决 原因 不蒜子域名更改了,所以需要修改博客的配置文件. 方法 进入博客目录下\themes\next\layout\_third-party\ ...