Struts2基础
通过Struts2将请求转发到指定JSP页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>主页</title>
</head>
<body>4
<a href="first.jsp">请求 Struts2</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>第一个Struts程序</title>
</head>
<body>
第一个Struts程序
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>8.1</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- Struts2过滤器 -->
<filter>
<!-- 过滤器名称 -->
<filter-name>struts2</filter-name>
<!-- 过滤器类 -->
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<!-- Struts2过滤器映射 -->
<filter-mapping>
<!-- 过滤器名称 -->
<filter-name>struts2</filter-name>
<!-- 过滤器映射 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<!-- 声明包 -->
<package name="myPackage" extends="struts-default">
<!-- 定义action -->
<action name="first">
<!-- 添加成功的映射页面 -->
<result>/first.jsp</result>
</action>
</package>
</struts>
应用Struts2提供的动态Action,处理添加用户信息请求及更新用户信息请求
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<!-- 声明包 -->
<package name="myPackage" extends="struts-default">
<!-- 定义action -->
<action name="userAction" class="com.wgh.UserAction">
<!-- 添加成功的映射页面 -->
<result name="add">user_add.jsp</result>
<result name="update">user_update.jsp</result>
</action>
</package>
</struts>
package com.wgh;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport {
private static final long serialVersionUID=1L;
private String info;
public String add() throws Exception{
info="添加用户信息";
return "add";
}
public String update() throws Exception{
info="更新用户信息";
return "update";
}
public String getInfo(){
return info;
}
public void setInfo(String info){
this.info=info;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>主页</title>
</head>
<body>
<a href="user_add.jsp">添加用户</a>
<br>
<a href="user_update.jsps">更新用户</a>
</body>
</html>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>第一个Struts程序</title>
</head>
<body>
<front color="red">
<s:property value="info/"></s:property>
</front>
</body>
</html>
编写一个Action对象,处理对表单提交的数据,模拟实现对指定用户的问候
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>主页</title>
<style type="text/css">
*{font-size: 12px;}
</style>
</head>
<body>
<form action="GreetingAction.java" method="post">
请输入你的姓名:<label>
<input type="text" name="username">
</label>
<input type="submit" value="提交">
</form>
</body>
</html>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<!-- 声明包 -->
<package name="myPackage" extends="struts-default" >
<!-- 定义action -->
<action name="greeting" class="com.wgh.GreetingAction" >
<!-- 定义成功的映射页面 -->
<result name="success">success.jsp</result>
<!-- 定义失败的映射页面 -->
<result name="error">error.jsp</result>
</action>
</package>
</struts>
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping></web-app>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>错误</title>
</head>
<body>
<font color="red">错误:您没有输入姓名!</font>
</body>
</html>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>欢迎</title>
<style type="text/css">
*{font-size: 12px;}
</style>
</head>
<body>
<form color="red">
<s:property value="username"/>
</form>
,您好!
<br>
欢迎使用来到本站
</body>
</html>
package com.wgh;
import com.opensymphony.xwork2.ActionSupport;
public class GreetingAction extends ActionSupport {
private static final long serialVersionUID=1L;
private String username;
public String execute() throws Exception{
if (username==null||"".equals(username)){
return ERROR;
}else {
return SUCCESS;
}
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
通过ActionContext对象获取Map类型的request,session和application,分别为这3个对象设置一个info属性并赋值,然后在JSP页面获取3中作用域下的info属性信息
package com.wgh;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* @author Li Yongqiang
* Map类型的request、session、application
*/
public class TestAction extends ActionSupport {
private static final long serialVersionUID = 1L;
// Map类型的request
private Map<String, Object> request;
// Map类型的session
private Map<String, Object> session;
// Map类型的application
private Map<String, Object> application;
// 构造方法
@SuppressWarnings("unchecked")
public TestAction(){
// 获取ActionContext对象
ActionContext context = ActionContext.getContext();
// 获取Map类型的request
request = (Map<String, Object>) context.get("request");
// 获取Map类型的session
session = context.getSession();
// 获取Map类型的application
application = context.getApplication();
}
/**
* 请求处理方法
* @return String
*/
public String execute() throws Exception{
// 字符串信息
String info = "明日科技";
// 向request添加信息
request.put("info", info);
// 向session添加信息
session.put("info", info);
// 向application添加信息
application.put("info", info);
// 成功返回
return SUCCESS;
}
}
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<!-- 声明包 -->
<package name="myPackage" extends="struts-default" >
<!-- 定义action -->
<action name="testAction" class="com.wgh.TestAction" >
<!-- 定义成功的映射页面 -->
<result name="success">success.jsp</result>
</action>
</package>
</struts>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>欢迎</title>
<style type="text/css">
*{font-size: 12px;}
</style>
</head>
<body>
request范围内的info值:
<font color="red"><%=request.getAttribute("info")%></font>
<br>
session范围内的info值:
<font color="red"><%=session.getAttribute("info")%></font>
<br>
application范围内的info值:
<font color="red"><%=application.getAttribute("info")%></font>
<br>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>8.2</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><!-- Struts2过滤器 -->
<filter>
<!-- 过滤器名称 -->
<filter-name>struts2</filter-name>
<!-- 过滤器类 -->
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<!-- Struts2过滤器映射 -->
<filter-mapping>
<!-- 过滤器名称 -->
<filter-name>struts2</filter-name>
<!-- 过滤器映射 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>主页</title>
<style type="text/css">
*{font-size: 12px;}
</style>
</head>
<body>
<a href="testAction.action">Map类型的request、session、application</a>
<br>
</body>
</html>
struts2技术进阶
通过OGNL操作普通的属性与方法
package com.wgh;
public class Student {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String say(){
return "我是一个学生";
}
}
}
package com.wgh;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* @author Li Yongqiang
* Map类型的request、session、application
*/
public class OGNLAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String name;
private Student student;
Map<String,Object> request;
@SuppressWarnings("unchecked")
public OGNLAction(){
student=new Student();
student.setId(1);
student.setName("张三");
name="tom";
request=(Map<String,Object>) ActionContext.getContext().get("request");
}
/**
* 请求处理方法
* @return String
*/
public String execute() throws Exception{
request.put("info","request测试");
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Map<String, Object> getRequest() {
return request;
}
public void setRequest(Map<String, Object> request) {
this.request = request;
}
}
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>欢迎</title>
<style type="text/css">
*{font-size: 12px;}
</style>
</head>
<body>
<div>
<h1>操作普通属性</h1>
属性name的值:<s:property value="name"/>
<br><hr>
学号:<s:property value="student.id"/><br>
姓名:<s:property value="student.name"/><br>
<s:property value="student.say()"/>
<br><hr>
request中的info值:<s:property value="student.say()"/>
</div>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>主页</title>
<style type="text/css">
*{font-size: 12px;}
</style>
</head>
<body>
<a href="ognl.action">测试</a>
<br>
</body>
</html>
为Action对象配置输出执行时间的拦截器,查看执行Action所需要的时间
package com.wgh;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
private static final long serialVersionUID = 1L;
public String execute() throws Exception{
Thread.sleep(1000);
return SUCCESS;
}
}
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true"/>
<constant name="struts.confriguration.xml.reload" value="true"/>
<!-- 声明包 -->
<package name="myPackage" extends="struts-default" >
<!-- 定义action -->
<action name="testAction" class="com.wgh.TestAction" >
<interceptor-ref name="timer"/>
<result name="success">success.jsp</result>
</action>
</package>
</struts>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>成功</title>
</head>
<body>
测试成功,请查看控制台程序的用时
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>主页</title>
<style type="text/css">
*{font-size: 12px;}
</style>
</head>
<body>
<a href="testAction.action">ceshi</a>
<br>
</body>
</html>
通过Struts2框架提供的表单标签编写用户注册表单
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>主页</title>
<style type="text/css">
*{font-size: 12px;}
</style>
</head>
<body>
<h2>用户注册</h2>
<s:form action="TestAction!register" method="post">
<s:textfield name="name" label="用户名" required="true" requiredposition="left"></s:textfield>
<s:password name="password" label="密码" required="true" requiredposition="left"></s:password>
<s:select list="{'请选择省份','吉林','广东','山东','河南'}" name="province" label="省份"></s:select>
<s:checkboxlist list="{'足球','篮球','羽毛球','乒乓球'}" name="hobby" label="爱好"></s:checkboxlist>
<s:textarea name="description" cols="30" rows="5" label="描述"></s:textarea>
<s:submit value="注册"></s:submit>
<s:reset value="重置"></s:reset>
</s:form>
</body>
</html>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>成功</title>
</head>
<body>
<div>
<h2>用户注册信息</h2>
<ul>
<li>用户名:<s:property value="name" /></li>
<li>密码:<s:property value="password" /></li>
<li>省份:<s:property value="province" /></li>
<li>爱好: <s:property value="hobby" /></li>
<li>描述:<s:property value="description" /></li>
</ul>
</div>
</body>
</html>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true"/>
<!-- 声明包 -->
<package name="myPackage" extends="struts-default" >
<!-- 定义action -->
<action name="testAction" class="com.wgh.TestAction" >
<result>success.jsp</result>
</action>
</package>
</struts>
package com.wgh;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String name;
private String password;
private String description;
private int sex = 0;
private String province;
private String hobby;
public String execute() throws Exception {
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
}
使用验证框架对数据校验
package com.wgh;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private String username;// 用户名
private String password;// 密码
// 用户登录
@Override
public String execute() throws Exception {
return SUCCESS;
}
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;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.3//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd" >
<validators>
<!-- 验证用户名 -->
<field name="username">
<field-validator type="requiredstring">
<message>请输入用户名</message>
</field-validator>
</field>
<!-- 验证密码 -->
<field name="password">
<field-validator type="requiredstring">
<message>请输入密码</message>
</field-validator>
</field>
</validators>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<!-- 声明包 -->
<package name="myPackge" extends="struts-default">
<!-- 配置UserAction -->
<action name="userAction" class="com.wgh.UserAction">
<!-- 用户登录页面 -->
<result name="input">/login.jsp</result>
<!-- 注册成功页面 -->
<result>/success.jsp</result>
</action>
</package>
</struts>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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=UTF-8">
<title>用户登录</title>
</head>
<body>
<s:form action="userAction" method="post">
<s:textfield name="username" label="用户名" required="true"></s:textfield>
<s:password name="password" label="密码" required="true"></s:password>
<s:submit key="submit" value="登录"></s:submit>
</s:form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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=UTF-8">
<title>登录成功</title>
</head>
<body>
<h2>
<s:property value="username"/>,登录成功
</h2>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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=UTF-8">
<title>用户登录</title>
<style type="text/css">
*{font-size: 12px;}
</style>
</head>
<body>
<s:form action="userAction" method="post">
<s:textfield name="username" label="用户名" required="true"></s:textfield>
<s:password name="password" label="密码" required="true"></s:password>
<s:submit key="submit" value="登录"></s:submit>
</s:form>
</body>
</html>
HIbernate技术
向数据库中的产品信息表添加产品信息
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库驱动 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 数据库连接的URL -->
<property name="connection.url">jdbc:mysql://localhost:3306/db_database10</property>
<!-- 数据库连接用户名 -->
<property name="connection.username">root</property>
<!-- 数据库连接密码 -->
<property name="connection.password">986</property>
<!-- Hibernate方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 打印SQL语句 -->
<property name="show_sql">true</property>
<!-- 映射文件 -->
<mapping resource="com/mr/product/Product.hbm.xml"/>
</session-factory>
</hibernate-configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 产品信息字段配置信息 -->
<hibernate-mapping>
<class name="com.mr.product.Product" table="tab_product1">
<!-- id值 -->
<id name="id" column="id" type="int">
<generator class="native"/>
</id>
<!-- 产品名称 -->
<property name="name" type="string" length="45">
<column name="name"/>
</property>
<!-- 产品价格 -->
<property name="price" type="double">
<column name="price"/>
</property>
<!-- 生产厂商 -->
<property name="factory" type="string" length="45">
<column name="factory"/>
</property>
<!-- 备注 -->
<property name="remark" type="string" length="100">
<column name="remark"/>
</property>
</class>
</hibernate-mapping>
package com.mr.product;
/**
* 商品信息的持久化类
*/
public class Product {
private Integer id;//唯一性标识
private String name;//产品名称
private Double price;//产品价格
private String factory;//生产商
private String remark;//备注
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getFactory() {
return factory;
}
public void setFactory(String factory) {
this.factory = factory;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
package com.mr.main;
import org.hibernate.Session;
import com.mr.hibernate.HibernateInitialize;
import com.mr.product.Product;
public class AddProduct {
/**
* 添加商品
*/
public static void main(String[] args) {
Session session = null; //声明Session对象
Product product = new Product();//实例化持久化类
//为持久化类属性赋值
product.setName("Java Web编程宝典");//设置产品名称
product.setPrice(79.00);//设置产品价格
product.setFactory("明日科技1");//设置生产商
product.setRemark("无");//无
//Hibernate的持久化操作
try {
session = HibernateInitialize.getSession();//获取Session
session.beginTransaction();//开启事务
session.save(product);//执行数据库添加操作
session.getTransaction().commit();//事务提交
} catch (Exception e) {
session.getTransaction().rollback();//事务回滚
System.out.println("数据添加失败");
e.printStackTrace();
}finally{
HibernateInitialize.closeSession();//关闭Session对象
}
}
}
package com.mr.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* Hibernate初始化类
*
*/
public class HibernateInitialize {
private static ThreadLocal<Session> threadLocal = null;//ThreadLocal对象
private static SessionFactory sessionFactory = null;//SessionFactory对象
//静态块
static {
try {
// 加载Hibernate配置文件
Configuration cfg = new Configuration().configure();
threadLocal = new ThreadLocal<Session>();//ThreadLocal对象
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
System.err.println("创建会话工厂失败");
e.printStackTrace();
}
}
/**
* 获取Session
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession(): null;
threadLocal.set(session);
}
return session;
}
/**
* 重建会话工厂
*/
public static void rebuildSessionFactory() {
try {
// 加载Hibernate配置文件
Configuration cfg = new Configuration().configure();
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
System.err.println("创建会话工厂失败");
e.printStackTrace();
}
}
/**
* 获取SessionFactory对象
* @return SessionFactory对象
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* 关闭Session
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();//关闭Session
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>10.3</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>
</web-app>
利用get()方法加载Product对象
package com.mr.main;
import org.hibernate.Session;
import com.mr.hibernate.HibernateInitialize;
import com.mr.product.Product;
public class GetProduct {
//利用get()方法装载对象
public static void main(String[] args){
Session session = null; //声明Session对象
try {
//Hibernate的持久化操作
session = HibernateInitialize.getSession();//获取Session
Product product = (Product) session.get(Product.class, new Integer("1"));//装载对象
System.out.println("产品ID:"+product.getId());
System.out.println("产品名称:"+product.getName());
System.out.println("产品价格:"+product.getPrice()+"元");
System.out.println("生产厂商:"+product.getFactory());
System.out.println("产品备注:"+product.getRemark());
} catch (Exception e) {
System.out.println("对象装载失败");
e.printStackTrace();
} finally{
HibernateInitialize.closeSession();//关闭Session
}
}
}
利用delete()方法删除指定的产品信息
package com.mr.main;
import javax.transaction.Transactional;
import org.hibernate.Session;
import com.mr.hibernate.HibernateInitialize;
import com.mr.product.Product;
public class DeleteProduct {
//删除指定产品信息
public static void main(String[] args) {
Session session = null; //声明Session对象
try {
//Hibernate的持久化操作
session = HibernateInitialize.getSession();//获取Session
session.beginTransaction();
Product product = (Product) session.get(Product.class, new Integer("1"));//装载对象
session.delete(product);//删除持久化信息
session.flush();//强制刷新提交
} catch (Exception e) {
System.out.println("对象删除失败");
e.printStackTrace();
} finally{
HibernateInitialize.closeSession();//关闭Session
}
}
}
修改指定的产品信息
package com.mr.main;
import org.hibernate.Session;
import com.mr.hibernate.HibernateInitialize;
import com.mr.product.Product;
public class UpdateProduct {
//修改指定产品信息
public static void main(String[] args) {
Session session = null; //声明Session对象
try {
//Hibernate的持久化操作
session = HibernateInitialize.getSession();//获取Session
session.beginTransaction();
Product product = (Product) session.load(Product.class, new Integer("1"));//装载对象
product.setName("Java Web编程");//修改商品名称
product.setRemark("无1");//修改备注信息
session.update(product );
session.flush();
} catch (Exception e) {
System.out.println("对象修改失败");
e.printStackTrace();
} finally{
HibernateInitialize.closeSession();//关闭Session
}
}
}
Hibernate技术进阶
建立产品对象与生产商对象的多对一单向关联,并利用映射关系查询完整的图书信息
package com.mr.product;
import com.mr.factory.Factory;
import javax.persistence.Convert;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
/**
* 商品信息的持久化类
*/
public class Product {
private Integer id;//唯一性标识
private String name;//产品名称
private Double price;//产品价格
private Factory factory;//关联的生产商
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Convert
public Factory getFactory() {
return factory;
}
public void setFactory(Factory factory) {
this.factory = factory;
}
}
package com.mr.main;
import org.hibernate.Session;
import com.mr.factory.Factory;
import com.mr.hibernate.HibernateInitialize;
import com.mr.product.Product;
public class SelectProduct {
public static void main(String[] args) {
Session session = null; //声明第一个Session对象
try {
//Hibernate的持久化操作
session = HibernateInitialize.getSession();//获取Session
session.beginTransaction();//事务开启
Product product = (Product) session.get(Product.class, new Integer("1"));//装载对象
System.out.println("产品名称:"+product.getName());
System.out.println("产品价格:"+product.getPrice()+"元");
System.out.println("生产商:"+product.getFactory().getFactoryName());
session.getTransaction().commit();//事务提交
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();//事务回滚
} finally{
HibernateInitialize.closeSession();//关闭Session
}
}
}
建立公民对象与身份证对象的一对一主键关联
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 公民身份证字段信息配置信息 -->
<hibernate-mapping>
<class name="com.mr.idcard.IDcard" table="tab_idcard">
<!-- id值 -->
<id name="id" column="id" type="int">
<!-- 外键生成 -->
<generator class="foreign">
<param name="property">people</param>
</generator>
</id>
<!-- 公民身份证号 -->
<property name="idcard_code" type="string" length="45" not-null="true">
<column name="IDcard_code"/>
</property>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 公民信息字段配置信息 -->
<hibernate-mapping>
<class name="com.mr.people.People" table="tab_people">
<!-- id值 -->
<id name="id" column="id" type="int">
<generator class="native"/>
</id>
<!-- 公民姓名 -->
<property name="name" type="string" length="45">
<column name="name"/>
</property>
<!-- 公民性别 -->
<property name="sex" type="string" length="2">
<column name="sex"/>
</property>
<!-- 公民年龄 -->
<property name="age" type="int">
<column name="age"/>
</property>
<!-- 一对一映射 -->
<one-to-one name="idcard" class="com.mr.idcard.IDcard"
cascade="all"/>
</class>
</hibernate-mapping>
建立公民对象与身份证对象的一对一外键关联关系
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 公民信息字段配置信息 -->
<hibernate-mapping>
<class name="com.mr.people.People" table="tab_people">
<!-- id值 -->
<id name="id" column="id" type="int">
<generator class="native"/>
</id>
<!-- 公民姓名 -->
<property name="name" type="string" length="45">
<column name="name"/>
</property>
<!-- 公民性别 -->
<property name="sex" type="string" length="2">
<column name="sex"/>
</property>
<!-- 公民年龄 -->
<property name="age" type="int">
<column name="age"/>
</property>
<!-- 一对一映射 -->
<many-to-one name="idcard" unique="true">
<column name="card_id"/>
</many-to-one>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 公民身份证字段信息配置信息 -->
<hibernate-mapping>
<class name="com.mr.idcard.IDcard" table="tab_idcard">
<!-- id值 -->
<id name="id" column="id" type="int">
<generator class="native"/>
</id>
<!-- 公民身份证号 -->
<property name="idcard_code" type="string" length="45" not-null="true">
<column name="IDcard_code"/>
</property>
</class>
</hibernate-mapping>
建立用户对象与权限对象的多对多关联关系,查询用户admin所拥有的权限,以及权限“新闻管理员”被赋予了哪些用户
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Role实体对象 -->
<hibernate-mapping>
<class name="com.mr.role.Role" table="tab_role">
<!-- 主键id -->
<id name="id">
<generator class="native"/>
</id>
<!-- 权限名称 -->
<property name="roleName" not-null="true">
<column name="rolename"/>
</property>
<set name="users" table="tab_mapping">
<key column="role_id"></key>
<many-to-many class="com.mr.user.User" column="user_id"/>
</set>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- User实体对象 -->
<hibernate-mapping>
<class name="com.mr.user.User" table="tab_user">
<!-- 主键id -->
<id name="id">
<generator class="native"/>
</id>
<!-- 用户名称 -->
<property name="name" not-null="true" />
<set name="roles" table="tab_mapping">
<key column="user_id"></key>
<many-to-many class="com.mr.role.Role" column="role_id"/>
</set>
</class>
</hibernate-mapping>
package com.mr.main;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.Session;
import com.mr.hibernate.HibernateInitialize;
import com.mr.role.Role;
import com.mr.user.User;
public class Manger {
public static void main(String[] args) {
Session session = null; //声明一个Session对象
try {
//Hibernate的持久化操作
session = HibernateInitialize.getSession();//获取Session
session.beginTransaction();//事务开启
User user = (User)session.get(User.class, new Integer("1"));//装载用户对象
Set<Role> roles= user.getRoles();//获取权限名称集合
System.out.println(user.getName()+"用户所拥有的权限为:");
//通过迭代输出权限信息
for (Iterator<Role> it = roles.iterator(); it.hasNext();) {
Role roles2 = (Role) it.next();
System.out.print(roles2.getRoleName()+"||");
}
System.out.println();//换行
Role rol = (Role)session.get(Role.class, new Integer("2"));
Set<User> users = rol.getUsers();//获取用户名称集合
System.out.println(rol.getRoleName()+"权限被赋予用户:");
//通过迭代输出用户信息
for (Iterator<User> it = users.iterator(); it.hasNext();) {
User users2 = (User) it.next();
System.out.print(users2.getName()+"||");
}
session.getTransaction().commit();//事务提交
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();//事务回滚
} finally{
HibernateInitialize.closeSession();//关闭Session
}
}
}
利用级联操作删除公民表中的信息和其在身份证表中所关联的信息
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 公民信息字段配置信息 -->
<hibernate-mapping>
<class name="com.mr.people.People" table="tab_people">
<!-- id值 -->
<id name="id" column="id" type="int">
<generator class="native"/>
</id>
<!-- 公民姓名 -->
<property name="name" type="string" length="45">
<column name="name"/>
</property>
<!-- 公民性别 -->
<property name="sex" type="string" length="2">
<column name="sex"/>
</property>
<!-- 公民年龄 -->
<property name="age" type="int">
<column name="age"/>
</property>
<!-- 一对一映射 -->
<one-to-one name="idcard" class="com.mr.idcard.IDcard" cascade="delete"/>
</class>
</hibernate-mapping>
package com.mr.main;
import org.hibernate.Session;
import com.mr.hibernate.HibernateInitialize;
import com.mr.people.People;
public class Manger {
public static void main(String[] args) {
Session session = null;// 声明一个Session对象
try {
// Hibernate的持久化操作
session = HibernateInitialize.getSession();// 获取Session
session.beginTransaction();// 事务开启
People people = (People)session.load(People.class, new Integer("1"));//装载公民对象
session.delete(people);//删除装载的公民对象
session.getTransaction().commit();// 事务提交
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();// 事务回滚
} finally {
HibernateInitialize.closeSession();// 关闭Session
}
}
}
将类继承树映射成一张表,并向这个数据表中添加两个不同实体对象的信息
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 继承树的映射配置 -->
<hibernate-mapping package="com.mr.person">
<class name="Person" table="tab_person">
<id name="id">
<generator class="native"/>
</id>
<!-- 声明一个鉴别器 -->
<discriminator column="type" type="string"/>
<!-- 映射自有属性 -->
<property name="name" not-null="true"/>
<property name="age" type="int"/>
<property name="sex" type="string"/>
<!-- 声明子类Student -->
<subclass name="Student" discriminator-value="学生">
<property name="school"/>
</subclass>
<!-- 声明子类Staffer -->
<subclass name="Staffer" discriminator-value="职员">
<property name="company"/>
</subclass>
</class>
</hibernate-mapping>
package com.mr.main;
import org.hibernate.Session;
import com.mr.hibernate.HibernateInitialize;
import com.mr.person.Staffer;
import com.mr.person.Student;
public class AddPerson {
public static void main(String[] args) {
Session session = null;// 声明一个Session对象
HibernateInitialize hi = new HibernateInitialize();
try {
// Hibernate的持久化操作
session = hi.getSession();// 获取Session
session.beginTransaction();// 事务开启
Student student = new Student();//声明学生的实体对象
student.setName("小明");
student.setAge(12);
student.setSex("男");
student.setSchool("明日希望小学");
session.save(student);//保存学生信息
Staffer staffer = new Staffer();
staffer.setName("小红");
staffer.setAge(25);
staffer.setSex("女");
staffer.setCompany("明日科技");
session.save(staffer);//保存职员信息
session.getTransaction().commit();// 事务提交
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();// 事务回滚
} finally {
hi.closeSession();// 关闭Session
}
}
}
将继承Person对象的每个子类Student和Staffer映射成一张表,并向数据表中添加两个不同实体对象的信息
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 继承树的映射配置 -->
<hibernate-mapping package="com.mr.person">
<class name="Person" table="tab_person1">
<id name="id">
<generator class="native"/>
</id>
<!-- 映射自有属性 -->
<property name="name" not-null="true"/>
<property name="age" type="int"/>
<property name="sex" type="string"/>
<!-- 映射子类Student -->
<joined-subclass name="Student" table="tab_student">
<key column="id"/>
<property name="school"/>
</joined-subclass>
<!-- 映射子类Staffer -->
<joined-subclass name="Staffer" table="tab_staffer">
<key column="id" />
<property name="company"/>
</joined-subclass>
</class>
</hibernate-mapping>
将每个具体类Student和Staffer映射成一张表,并向每个数据表中添加两个不同的实体对象的信息
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 继承树的映射配置 -->
<hibernate-mapping package="com.mr.person">
<class name="Person" abstract="true">
<id name="id">
<!-- 主键生成策略为手动分配 -->
<generator class="assigned"/>
</id>
<!-- 映射自有属性 -->
<property name="name" not-null="true"/>
<property name="age" type="int"/>
<property name="sex" type="string"/>
<!-- 映射子类Student -->
<union-subclass name="Student" table="tab_student2">
<property name="school"/>
</union-subclass>
<!-- 映射子类Staffer -->
<union-subclass name="Staffer" table="tab_staffer2">
<property name="company"/>
</union-subclass>
</class>
</hibernate-mapping>
Spring核心之IOC
通过Spring的赋值为用户JavaBean的属性赋值
package com.mr.user;
public class User {
private String name;//用户姓名
private Integer age;//年龄
private String sex;//性别
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
package com.mr.main;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.mr.user.User;
public class Manger {
public static void main(String[] args) {
Resource resource = new ClassPathResource("applicationContext.xml"); //装载配置文件
BeanFactory factory = new XmlBeanFactory(resource);
User user = (User) factory.getBean("user"); //获取Bean
System.out.println("用户姓名——"+user.getName());//输出用户的姓名
System.out.println("用户年龄——"+user.getAge());//输出用户的年龄
System.out.println("用户性别——"+user.getSex());//输出用户的性别
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- User Bean -->
<bean name="user" class="com.mr.user.User">
<property name="name">
<value>小强</value>
</property>
<property name="age">
<value>26</value>
</property>
<property name="sex">
<value>男</value>
</property>
</bean>
</beans>
通过Spring的构造器注入为用户JavaBean的属性信息赋值
package com.mr.user;
public class User {
private String name;//用户姓名
private Integer age;//年龄
private String sex;//性别
//构造方法
public User(String name,Integer age,String sex){
this.name=name;
this.age=age;
this.sex=sex;
}
//输出JavaBean的属性值方法
public void printInfo(){
System.out.println("用户姓名——"+name);//输出用户的姓名
System.out.println("用户年龄——"+age);//输出用户的年龄
System.out.println("用户性别——"+sex);//输出用户的性别
}
}
package com.mr.main;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.mr.user.User;
public class Manger {
public static void main(String[] args) {
Resource resource = new ClassPathResource("applicationContext.xml"); //装载配置文件
BeanFactory factory = new XmlBeanFactory(resource);
User user = (User) factory.getBean("user"); //获取Bean
user.printInfo();//输出JavaBean的属性值
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- User Bean -->
<bean name="user" class="com.mr.user.User">
<constructor-arg>
<value>小强</value>
</constructor-arg>
<constructor-arg>
<value>26</value>
</constructor-arg>
<constructor-arg>
<value>男</value>
</constructor-arg>
</bean>
</beans>
将User对象注入Spring的控制器Manger中,并在控制器中执行User的printInfo()方法
package com.mr.main;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import com.mr.user.User;
public class Manger extends AbstractController {
public static void main(String[] args) {
}
private User user;//注入User对象
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
protected ModelAndView handleRequestInternal(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
user.printInfo();//执行User中的信息打印方法
return null;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- User Bean -->
<bean id="user" class="com.mr.user.User">
<property name="name">
<value>小强</value>
</property>
<property name="age">
<value>26</value>
</property>
<property name="sex">
<value>男</value>
</property>
</bean>
<!-- 注入JavaBean -->
<bean name="/main.do" class="com.mr.main.Manger">
<property name="user">
<ref bean="user"/>
</property>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>12.3</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!--设置自动加载配置文件-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
按bean名称自动装配User
package com.mr.user;
public class PrintInfo {
private User user;//注入User对象
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
//打印的User对象中的属性
public void PrintUser(){
System.out.println("PrintInfo打印的User属性");
System.out.println("----------------------");
System.out.println("用户姓名--"+user.getName());//输出用户的姓名
System.out.println("用户年龄--"+user.getAge());//输出用户的年龄
System.out.println("用户性别--"+user.getSex());//输出用户的性别
}
}
package com.mr.main;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.mr.user.PrintInfo;
public class Manger {
public static void main(String[] args) {
Resource resource = new ClassPathResource("applicationContext.xml"); //装载配置文件
BeanFactory factory = new XmlBeanFactory(resource);
PrintInfo printInfo = (PrintInfo) factory.getBean("printInfo"); //获取Bean
printInfo.PrintUser();//输出JavaBean的属性值
}
}
自定义MyDateEditor编辑器将String类型转换为Date类型
package com.mr.ms;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UserInfo {
private String name;//姓名
private char sex;//性别
private int age;//年龄
private Date date;//出生日期
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public void printInfo() {
System.out.println("姓名:" + name + "\n性别:" + sex + "\n年龄:" + age
+ "\n出生日期:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
}
}
package com.mr.ms;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDateEditor extends PropertyEditorSupport {
private String formate;
// 设置日期格式方法
public void setAsText(String text) throws IllegalArgumentException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = sdf.parse(text);
setValue(date);// 设置日期格式
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setFormate(String formate) {
this.formate = formate;
}
}
package com.mr.ms;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class PringUserInfo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");//装载配置文件
UserInfo ui = (UserInfo) context.getBean("user1");//获取bean
ui.printInfo();//执行bean的打印方法
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<!-- Spring配置文件 -->
<beans>
<bean id="user1" class="com.mr.ms.UserInfo">
<property name="name">
<value>小强</value>
</property>
<property name="sex">
<value>男</value>
</property>
<property name="age">
<value>26</value>
</property>
<property name="date">
<value>1985-02-08</value>
</property>
</bean>
<bean id="customEditorConfigurer"
class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date" value="com.mr.ms.MyDateEditor"/>
</map>
</property>
</bean>
</beans>
Spring核心之AOP
利用Spring AOP使日志输出与方法分离,让在调用目标方法之前执行日志输出
package com.mr.log;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class LoggerExecute implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
before();//执行前置通知
invocation.proceed();
return null;
}
//前置通知
private void before() {
System.out.println("程序开始执行!");
}
}
package com.mr.target;
public class Target {
//程序执行的方法
public void execute(String name){
System.out.println("执行execute()方法:" + name);//输出信息
}
}
package com.mr.main;
import org.springframework.aop.framework.ProxyFactory;
import com.mr.log.LoggerExecute;
import com.mr.target.Target;
public class Manger {
//创建代理
public static void main(String[] args) {
Target target = new Target(); //创建目标对象
ProxyFactory di=new ProxyFactory();
di.addAdvice(new LoggerExecute());
di.setTarget(target);
Target proxy=(Target)di.getProxy();
proxy.execute("AOP的简单实现"); //代理执行execute()方法
}
}
在Spring中利用DAO模式向tb_user表中添加数据
package com.mr.user;
public class User {
private Integer id;//唯一性标识
private String name;//姓名
private Integer age;//年龄
private String sex;//性别
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
package com.mr.dao;
import com.mr.user.User;
public interface UserDAOImpl {
public void inserUser(User user);//添加用户信息的方法
}
package com.mr.dao;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mr.user.User;
public class UserDAO implements UserDAOImpl {
private DataSource dataSource;//注入DataSource
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
//向数据表tb_user中添加数据
public void inserUser(User user) {
String name = user.getName();//获取姓名
Integer age = user.getAge();//获取年龄
String sex = user.getSex();//获取性别
Connection conn = null;//定义Connection
Statement stmt = null;//定义Statement
try {
conn = dataSource.getConnection();//获取数据库连接
stmt = conn.createStatement();
stmt.execute("INSERT INTO tb_user (name,age,sex) "
+ "VALUES('"+name+"','" + age + "','" + sex + "')");//添加数据的SQL语句
} catch (SQLException e) {
e.printStackTrace();
}
finally {
if(stmt != null) {
try {
stmt.close();//关闭Statement对象
}
catch(SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();//关闭数据库连接
}
catch(SQLException e) {
e.printStackTrace();
}
}
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- 配置数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/db_database10
</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>986</value>
</property>
</bean>
<!-- 为UserDAO注入数据源 -->
<bean id="userDAO" class="com.mr.dao.UserDAO">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
</beans>
package com.mr.main;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.mr.dao.UserDAO;
import com.mr.user.User;
public class Manger {
public static void main(String[] args) {
Resource resource = new ClassPathResource("applicationContext.xml"); //装载配置文件
BeanFactory factory = new XmlBeanFactory(resource);
User user = new User();//实例化User对象
user.setName("张三");//设置姓名
user.setAge(new Integer(30));//设置年龄
user.setSex("男");//设置性别
UserDAO userDAO = (UserDAO) factory.getBean("userDAO");//获取UserDAO
userDAO.inserUser(user);//执行添加方法
System.out.println("数据添加成功!!!");
}
}