spring hibernate struts 整合开发(6) - 额外功能

一.springhibernatestruts整合开发(1)-搭建环境

二.springhibernatestruts整合开发(2)-Spring集成的Hibernate编码和测试

三.springhibernatestruts整合开发(3)-Struts集成Spring

四.springhibernatestruts整合开发(4)-Struts与Spring集成2

五.springhibernatestruts整合开发(5)-Hibernate二级缓存

六.springhibernatestruts整合开发(6)-额外功能

Spring提供的CharacterEncoding和OpenSessionInView功能。

这里通过一个表单页面,提交数据,由struts封装数据,并由action调用业务层持久化数据,来引出乱码问题。

1.创建index.jsp页面

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html:form action="/person/dispose">
	<html:text property="name" />
	<html:hidden property="method" value="add" />
	<html:submit value="Submit" />
</html:form>

2.配置struts-config.xml

添加action和form-bean:

<form-beans>
		<form-bean name="personForm" type="com.john.web.formbean.PersonForm" />
	</form-beans>
	<action-mappings>
		<!-- Let the action be managed by spring, thus type property is eliminated -->
		<action path="/person/dispose" name="personForm" scope="request" parameter="method" validate="false">
			<forward name="message" path="/WEB-INF/pages/message.jsp"/>
		</action>
	</action-mappings>

Note:这里的action和form-bean都是用type来表示类的全限定名的,不是className。

3.配置beans.xml

添加actionbean:

<bean name="/person/dispose" class="com.john.web.action.PersonDisposeAction"/>

4.创建PersonForm和PersonDispatchAction类

public class PersonForm extends ActionForm {
   private Integer id;
   private String name;
   // getters and setters are omitted
}
// Utilize DispatchAction to execute specified method
public class PersonDisposeAction extends DispatchAction{
	// Since this action is managed by spring, we could
	// inject the business bean
	@Resource PersonService personService;
	
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		PersonForm personForm = (PersonForm)form;
		personService.save(new Person(personForm.getName()));
		request.setAttribute("result", "Saved successfully!");
		return mapping.findForward("message");
	}
}

5.创建结果显示页面message.jsp

<body>
${result}
</body>

开启服务,打开index.jsp页面,输入名称,提交。

6.使用spring解决struts1.3乱码问题

如果输入的名称是中文,保存到数据库后是乱码,可以使用spring提供的方法:

在web.xml加入:

<filter>
  	<filter-name>encoding</filter-name>
  	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  	<init-param>
  		<param-name>encoding</param-name>
  		<param-value>UTF-8</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>encoding</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

7.使用spring解决hibernate因session关闭导致的延迟加载例外问题

在web.xml加入:

<filter>
  	<filter-name>OpenSessionInViewFilter</filter-name>
  	<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>OpenSessionInViewFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

整理自:传智播客spring教程

相关推荐