📄 struts+hibernate模板开发笔记.txt
字号:
/**
* 设数据模型
* @param dataModule
*/
public void setDataModule(DataModule dataModule){
this.dataModule=dataModule;
this.sessionFactory=dataModule.getSessionFactory();
}
/**
* 建立DEMO
* @param demo
* @throws HibernateException
* @throws java.lang.Exception
*/
public void createDemo(Demo demo) throws HibernateException,Exception {
Transaction transaction = null;
Session session=sessionFactory.openSession();
try{
transaction = session.beginTransaction();
session.save(demo);
transaction.commit();
}catch(HibernateException he){
if ( transaction!=null ){
transaction.rollback();
}
throw he;
}finally{
session.close();
}
}
}
九、设计模式:MVC
1.表示层(应用了template)
JSP文件(template/Basictemplate.jsp)
<%@ page contentType="text/html; charset=gb2312" %>
<%@ taglib uri='/WEB-INF/struts-template.tld' prefix='template' %>
<html>
<head>
<title><template:get name='title'/></title>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=gb2312">
<META HTTP-EQUIV="Content-Language" CONTENT="zh-CN">
<META name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
<META name="keywords" content="extreme programming, extreme projects, design pattern, J2EE, forum, chinese">
<LINK href="default.css" type="text/css" rel="stylesheet">
</head>
<body topmargin='0'>
<table width="95%" border="0" align="center">
<tr>
<td width="17%" rowspan="3">
<!-- START OF NAVBAR -->
<template:get name='navbar'/>
<!-- END OF NAVBAR -->
</td>
<td width="83%" valign="top">
<!-- START OF HEADER -->
<template:get name='header'/>
<!-- END OF HEADER -->
</td>
</tr>
<tr>
<td valign="top">
<!-- START OF CONTENT -->
<template:get name='content'/>
<!--END OF CONTENT -->
</td>
</tr>
<tr>
<td valign="top">
<!-- START OF FOOTER -->
<template:get name='footer'/>
<!-- END OF FOOTER -->
</td>
</tr>
</table>
</body></html>
JSP文件(addDemo.jsp)
<%
/**
* <p>Title: Struts开发测试1.0</p>
* <p>Description:项目说明 </p>
* <p>Copyright: Copyright (c) 2003-2008 </p>
* <p>Company:优势科技 </p>
* @author 段洪杰
* @version 1.0
* @time [2003年10月22日 14时50分]
**/
%>
<%@page contentType="text/html; charset=gb2312" %>
<%@taglib uri='/WEB-INF/struts-template.tld' prefix='template' %>
<template:insert template='/template/basicTemplate.jsp'>
<template:put name='title' content='Struts开发测试1.0' direct='true'/>
<template:put name='navbar' content='/content/navbar.jsp' />
<template:put name='header' content='/content/header.jsp' />
<template:put name='content' content='/content/addDemo.jsp'/>
<template:put name='footer' content='/content/footer.jsp' />
</template:insert>
JSP文件(content/addDemo.jsp)
<%
/**
* <p>Title: Struts开发测试1.0</p>
* <p>Description:项目说明 </p>
* <p>Copyright: Copyright (c) 2003-2008 </p>
* <p>Company:优势科技 </p>
* @author 段洪杰
* @version 1.0
* @time [2003年10月22日 14时50分]
**/
%>
<%@page contentType = "text/html; charset=GB2312" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@taglib uri="/WEB-INF/ImageTag.tld" prefix="image" %>
<%@taglib uri="/WEB-INF/DateTag.tld" prefix="date" %>
<jsp:useBean id="sessionBean" scope="session" class="com.company.demo.web.SessionBean" />
<html:errors/>
<FORM METHOD="post" ACTION="addDemoAction.do" >
<p>名字(name) :
<input name="name" type="text">
</p>
<p>日期(date) :
<date:inputButton type="date" name="userDate"/>
</p>
<p>日期(date) :
<date:inputButton type="datetime" name="userDateTime"/>
</p>
<p>
<image:uploadButton savePath="saveimagepath"/>
</p>
<p>
<input type="submit" name="Submit" value="提交">
<input type="reset" name="Submit2" value="重置">
</p>
</FORM>
控制层(struts-config.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.0//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">
<struts-config>
<form-beans>
<form-bean name="demoActionForm" type="com.company.demo.web.DemoActionForm" />
<form-bean name="imageUploadActionForm" type="com.company.demo.web.ImageUploadActionForm" />
</form-beans>
<global-forwards>
<forward name="unknown-error" path="/error.jsp" />
<forward name="success" path="/success.jsp" />
</global-forwards>
<action-mappings>
<action name="demoActionForm" type="com.company.demo.web.AddDemoAction" input="/addDemo.jsp" scope="request" path="/addDemoAction" />
<action name="imageUploadActionForm" type="com.company.demo.web.ImageUploadAction" input="/content/imageUpload.jsp" scope="request" path="/imageUploadAction" />
</action-mappings>
</struts-config>
文件(DemoActionForm.java)
package com.company.demo.web;
import org.apache.struts.action.*;
import javax.servlet.http.*;
public class DemoActionForm extends ActionForm {
private String name;
private String userDate;
private String userDateTime;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserDate() {
return userDate;
}
public void setUserDate(String userDate) {
this.userDate = userDate;
}
public String getUserDateTime() {
return userDateTime;
}
public void setUserDateTime(String userDateTime) {
this.userDateTime = userDateTime;
}
public ActionErrors validate(ActionMapping actionMapping, HttpServletRequest httpServletRequest) {
/**@todo: finish this method, this is just the skeleton.*/
return null;
}
public void reset(ActionMapping actionMapping, HttpServletRequest httpServletRequest) {
}
}
应用逻辑层(AddDemoAction.java)
package com.company.demo.web;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import com.company.demo.jdo.Demo;
import com.company.demo.dao.DemoDAO;
import com.company.demo.dao.DemoDAOFactory;
import com.company.demo.dao.DemoDAOImpl;
public class AddDemoAction extends Action {
public ActionForward perform(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
/**@todo: complete the business logic here, this is just a skeleton.*/
DemoActionForm demoActionForm = (DemoActionForm) actionForm;
SessionBean sessionBean = (SessionBean) httpServletRequest.getSession().getAttribute("sessionBean");
if (sessionBean == null) {
httpServletRequest.setAttribute("message", "系统超时,请重新登录!!!");
return actionMapping.findForward("unknown-error");
}
else {
try {
Demo demo = new Demo();
demo.setName(demoActionForm.getName());
DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd hh:ss:mm");
Date userDateTime = dateTimeFormat.parse(demoActionForm.getUserDateTime());
demo.setSystemDate(userDateTime);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date userDate = dateFormat.parse(demoActionForm.getUserDate());
demo.setUserDate(userDate);
DemoDAO demoDAO = DemoDAOFactory.getDemoDAO();
demoDAO.setDataModule(sessionBean.getDataModule());
demoDAO.createDemo(demo);
}
catch (Exception ex) {
httpServletRequest.setAttribute("message",ex.toString());
return (actionMapping.findForward("unknown-error"));
}
httpServletRequest.setAttribute("message", "成功!");
return (actionMapping.findForward("success"));
}
}
}
十、自定义标签
1.自定义标签库(DateTag.tld)
<?xml version="1.0" encoding="GB2312" ?> <!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.2</jspversion>
<shortname>Date Tag Library</shortname>
<info>日期录入标签库</info>
<tag>
<name>inputButton</name>
<tagclass>com.company.demo.tags.DateTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>type</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
2.Tag类(DateTag.java)
package com.company.demo.tags; import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import javax.servlet.*;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>
* @author 段洪杰
* @version 1.0
* 生成日期录框
*/
public class DateTag extends TagSupport{
String type,name; //类型和参数名
public void setType(String type)throws JspException {
this.type=type;
}
public void setName(String name)throws JspException {
this.name=name;
}
public int doStartTag() throws JspException {
String string,dialogHeight,dialogWidth,size;
if(type=="date") {
dialogHeight="290";
dialogWidth="240";
size="10";
}
else if(type=="datetime") {
dialogHeight="315";
dialogWidth="240";
size="18";
}
else {
throw new JspTagException("类型参数错误,只能选择date或datetime!");
}
string="<SCRIPT language=javascript>"+
"function selectDate"+name+"(oSource){"+
"window.showModalDialog('content/dtpicker.jsp?rn='+Math.random(),oSource,'dialogHeight:"+dialogHeight+"px; dialogWidth: "+dialogWidth+"px;center: Yes; help: No; resizable: No;scroll:No;status: No;')"+
"}"+
"</script>"+
"<INPUT readOnly size="+size+" name="+name+
" DataType=\"date\" comparer=\"compareToLastUsedOn\" dateTimeType="+type+">"+
"<IMG src=\"images/select.gif\" width=\"23\" height=\"23\" align=absMiddle"+
" onclick=selectDate"+name+"(document.all(this.sourceIndex-1))> ";
try{
JspWriter out=pageContext.getOut();
out.println(string);
}
catch(Exception ex)
{
throw new JspTagException("程序调用标签时出错: "+ex.getMessage());
}
return SKIP_BODY;
}
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
}
十一、解决汉字编码问题
1.修改web.xml文件,在<web-app>标签后增加如下内容.
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>com.company.demo.util.SetEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
2.创建类文件(SetEncodingFilter.java)
package com.company.demo.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.UnavailableException;
/**
* Set All HttpRequest Encoding
*/
public class SetEncodingFilter
implements Filter {
/**
* The default character encoding to set for requests that pass through
* this filter.
*/
protected String encoding = null;
/**
* The filter configuration object we are associated with. If this value
* is null, this filter instance is not currently configured.
*/
protected FilterConfig filterConfig = null;
/**
* Should a character encoding specified by the client be ignored?
*/
protected boolean ignore = true;
/**
* Take this filter out of service.
*/
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
/**
* Select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*
* @param request The servlet request we are processing
* @param result The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (ignore || (request.getCharacterEncoding() == null)) {
request.setCharacterEncoding(selectEncoding(request));
}
chain.doFilter(request, response);
}
/**
* Place this filter into service.
* @param filterConfig The filter configuration object
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
}
/**
* Select an appropriate character encoding to be used, based on the
* characteristics of the current request and/or filter initialization
* parameters. If no character encoding should be set, return
* <code>null</code>.
* <p>
* The default implementation unconditionally returns the value configured
* by the <strong>encoding</strong> initialization parameter for this
* filter.
*
* @param request The servlet request we are processing
*/
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
/**
* Returns the filterConfig.
* @return FilterConfig
*/
public FilterConfig getFilterConfig() {
return filterConfig;
}
/**
* Sets the filterConfig.
* @param filterConfig The filterConfig to set
*/
public void setFilterConfig(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -