JavaWeb流行框架(代码案例)

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("数据添加成功!!!");
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/528299.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Codeforces Round 938 (Div. 3) (A~E)

Codeforces Round 938 (Div. 3) (A~E) 目录&#xff1a;A B C D E A题&#xff1a;Yogurt Sale 标签: 数学&#xff08;math&#xff09; 题目大意 酸奶价格&#xff0c; a 元一份&#xff0c;b元两份n问&#xff1a;买n份最少多少钱 思路 a元一份&#xff0c;b元两份&#…

js获取上周本周下周的日期(附Demo)

目录 前言1. 基本知识2. Demo3. 彩蛋 前言 现在的时间点是&#xff1a;2024-04-08&#xff0c;对应的日期如下&#xff08;上周、这周、下周&#xff09; 1. 基本知识 讲述Demo之前&#xff0c;先补充一些基础知识 JavaScript 中的 Date 对象是用于处理日期和时间的对象。它…

【ensp】VLAN间通信的解决办法

VLAN间通信简介 VLAN间三层通信是指在VLAN网络中&#xff0c;不同VLAN之间进行通信的过程。 我们知道VLAN是虚拟局域网&#xff0c;在一个局域网内我们是通过Mac地址进行通信&#xff0c;在局域网与局域网之间通过IP地址来通信&#xff0c;大致过程如下&#xff1a; 主机在发…

【SERVERLESS】搭建ServerLess服务

目录 一、前言 二、什么是ServerLess? 三、ServerLess技术选型 四、ServerLess基础服务搭建 Mac安装示例&#xff1a; Windows安装说明&#xff1a; 五、生成ServerLess应用 六、ServerLess部署 验证并访问函数应用 七、ServerLess进阶演示 八、ServerLess最后总结 …

芒果YOLOv8改进组合157:动态标签分配ATSS+新颖高效AsDDet检测头组合改进,共同助力VisDrone涨点1.8%,小目标高效涨点

💡本篇内容:【芒果YOLOv8改进ATSS标签分配策略|第三集】芒果YOLOv8改进组合157:动态标签分配ATSS+新颖高效AsDDet检测头组合改进,共同助力VisDrone涨点1.8%,小目标高效涨点 💡🚀🚀🚀本博客 标签分配策略ATSS改进+ 新颖高效AsDDet检测头组合改进,适用于 YOLOv8 …

免费ai写作软件有哪些?分享10个给你 #媒体#学习#媒体

你是否因为写作困顿而感到沮丧&#xff1f;是不是希望能够找到一个能给你提供无限灵感和提高创作效率的利器&#xff1f;AI写作助手就是你的绝佳选择&#xff01;现在我向大家推荐几款好用的AI写作助手&#xff0c;它们将让你的创作之旅更加流畅、富有创意。 1.飞鸟写作 这是…

超详细解读Transformer框架

Transformer是由谷歌大脑2017年在论文《Attention is All You Need》中提出的一种序列到序列(Seq2Seq)模型。自提出伊始&#xff0c;该模型便在NLP和CV界大杀四方&#xff0c;多次达到SOTA效果。NLP领域中&#xff0c;我们所熟知的BERT和GPT就是从Transformer中衍生出来的预训练…

【云计算】云网络产品体系概述

云网络产品体系概述 在介绍云网络产品体系前&#xff0c;先介绍几个与云计算相关的基础概念。 阿里云在基础设施层面分为 地域 和 可用区 两层&#xff0c;关系如下图所示。在一个地域内有多个可用区&#xff0c;每个地域完全独立&#xff0c;每个可用区完全隔离&#xff0c;同…

咸鱼之王_手游_开服搭建架设_内购修复无bug运营版

视频演示 咸鱼之王_手游_开服 游戏管理后台界面 源码获取在文章末尾 源码获取在文章末尾 源码获取在文章末尾 或者直接下面 https://githubs.xyz/y28.html 1.安装宝塔 yum install -y wget && wget -O install.sh http://download.bt.cn/install/install_6.0.sh &…

Leetcode C语言习题

Leetcode习题27&#xff1a;移除元素 题目&#xff1a; 说明&#xff1a; 示例&#xff1a; 题解&#xff1a; 方法一&#xff1a;&#xff08;开辟额外的数组空间&#xff09; 我们可以创建一个新的数组&#xff0c;然后用循环来遍历原数组&#xff0c;将原数组中不为 val…

29.WEB渗透测试-数据传输与加解密(3)

免责声明&#xff1a;内容仅供学习参考&#xff0c;请合法利用知识&#xff0c;禁止进行违法犯罪活动&#xff01; 内容参考于&#xff1a; 易锦网校会员专享课 上一个内容&#xff1a;28.WEB渗透测试-数据传输与加解密&#xff08;2&#xff09; md5解密网站&#xff1a;ht…

SpringMVC数据接收(全面/详细注释)

SpringMVC涉及组件&#xff1a; DispatcherServlet : SpringMVC提供&#xff0c;我们需要使用web.xml配置使其生效&#xff0c;它是整个流程处理的核心&#xff0c;所有请求都经过它的处理和分发&#xff01;[ CEO ]HandlerMapping : SpringMVC提供&#xff0c;我们需要进行…

高创新 | [24年新算法]NRBO-XGBoost回归+交叉验证基于牛顿拉夫逊优化算法-XGBoost多变量回归预测

高创新 | [24年新算法]NRBO-XGBoost回归交叉验证基于牛顿拉夫逊优化算法-XGBoost多变量回归预测 目录 高创新 | [24年新算法]NRBO-XGBoost回归交叉验证基于牛顿拉夫逊优化算法-XGBoost多变量回归预测预测效果基本介绍程序设计参考资料 预测效果 基本介绍 1.Matlab实现 [24年新算…

实现 jwt 鉴权- SpringBoot + 微服务

目录 项目结构 主要步骤 auth-service里&#xff1a; 1. 配置 pom.xml 依赖 2. 实现HandlerInterceptor 接口的 preHandle 函数 3. 实现 WebMvcConfigurer 的 addInterceptors 接口 4. 生成 token 和验证 token 5. 登录接口示例 user-service 里&#xff1a; 6. 实现拦…

Netty NioEventLoop详解

文章目录 前言类图主要功能NioEventLoop如何实现事件循环NioEventLoop如何处理多路复用Netty如何管理Channel和Selector管理Channel管理Selector注意事项 前言 Netty通过事件循环机制(EventLoop)处理IO事件和异步任务&#xff0c;简单来说&#xff0c;就是通过一个死循环&…

信息泄露漏洞的JS整改方案

引言 &#x1f6e1;️ 日常工作中&#xff0c;我们经常会面临线上环境被第三方安全厂商扫描出JS信息泄露漏洞的情况&#xff0c;这给我们的系统安全带来了潜在威胁。但幸运的是&#xff0c;对于这类漏洞的整改并不复杂。本文将介绍几种可行的整改方法&#xff0c;以及其中一种…

【C语言】:枚举和联合体

这里写自定义目录标题 1、枚举1.1 枚举类型的声明1.2 枚举类型的优点1.3 枚举类型的使用 2、联合体&#xff08;共用体&#xff09;2.1 联合体类型的声明2.2 联合体的特点2.3联合体大小的计算 1、枚举 1.1 枚举类型的声明 枚举顾名思义就是⼀⼀列举&#xff0c;把可能的取值⼀…

Tomcat以服务方式启动,无法访问网络共享目录问题

关于“Tomcat以服务方式启动&#xff0c;无法访问网络共享目录问题”解决方式如下&#xff1a; 1、通过doc命令【services.msc】打开本地服务找到&#xff0c;找到tomcat服务所在位置 2、右键打开Tomcat服务的属性 3、选择 登陆选项卡 4、选择“此账户”选项&#xff0c;并…

Nginx配置文件修改结合内网穿透实现公网访问多个本地web站点

文章目录 1. 下载windows版Nginx2. 配置Nginx3. 测试局域网访问4. cpolar内网穿透5. 测试公网访问6. 配置固定二级子域名7. 测试访问公网固定二级子域名 1. 下载windows版Nginx 进入官方网站(http://nginx.org/en/download.html)下载windows版的nginx 下载好后解压进入nginx目…

自动驾驶中的多目标跟踪_第二篇

自动驾驶中的多目标跟踪:第二篇 上一节介绍了多目标跟踪的定义、应用场景和类型以及面临的挑战&#xff1b;在这一节&#xff0c;我们回顾贝叶斯滤波&#xff0c;简单介绍运动模型和量测模型&#xff0c;卡尔曼滤波等。 附赠自动驾驶学习资料和量产经验&#xff1a;链接 贝叶…