SSH study notes (b)

Second, the small practice project

Project description: a user's last name, first name, age and additions and deletions to change search, use ssh + apache framework of dbcp connection pool.

 

1, it was confirmed commons-dbcp.jar has been introduced (according to the operation on the articles will be introduced)

2, using mysql database, establish a database called mytest to create table users

create table users ( id int not null, firstname varchar(50) not null, lastname varchar(50) not null, age int not null, primary key (id) ) ENGIN = InnoDB ROW_FORMAT = DEFAULT;

3, doorway pages index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!-- 增加页面的structs支持 --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'index.jsp' starting page</title> </head> <body> <h1><font color="red">Operation List</font> </h1> <s:a href="save.jsp">Save User</s:a><br><br><br> <!-- structs提供的标签 --> <s:a href="listUser.action"> List User</s:a> <!-- 通过调用服务器端的资源来显示所有用户 --> </body> </html>

4, New save.jsp, save the user page

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>save user</title> </head> <body> <h1><font color="red">Save User</font> </h1> <s:form action="saveUser"> <s:textfield name="user.firstname" label="firstname"></s:textfield> <s:textfield name="user.lastname" label="lastname"></s:textfield> <s:textfield name="user.age" label="age"></s:textfield> <s:submit></s:submit> </s:form> </body> </html>


5, the new packet com.test.bean, in which the new User.java

package com.test.bean; public class User { private Integer id; private String firstname; private String lastname; private int age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }

This javabean just fine. Then generates the corresponding profile hibernate thereto. In the same bag New User.hbm.xml

<?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.test.bean.User" table="users">

 <id name="id" type="java.lang.Integer" column="id"> <generator class="increment"/><!-- 主键生成策略为increment --> </id>

 <property column="firstname" name="firstname" type="string" length="50"> </property>  <property column="lastname" name="lastname" type="string"  length="50">  </property>   <property column="age" name="age" type="java.lang.Integer"> </property>  </class>

</hibernate-mapping>

6, a new packet com.test.action.user, the new package in SaveUserAction.java

package com.test.action.user; import com.opensymphony.xwork2.ActionSupport; import com.test.bean.User; import com.test.service.UserService; public class SaveUserAction extends ActionSupport { /** * */ private static final long serialVersionUID = 1L; private User user; private UserService service; public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String execute() throws Exception { // TODO Auto-generated method stub //不自己实现保存用户,而是调用业务逻辑层来实现 this.service.save(this.user); return this.SUCCESS; } public UserService getService() { return service; } public void setService(UserService service) { this.service = service; } }

7, adding support for the internationalization of the page. New File struts.properties, wrote in the document under src directory

struts.custom.i18n.resources=globalMessages

New globalMessages_en.properties in the src directory, write in a file

firstname=firstname lastname=lastname age=age

New in the src directory globalMessages_zh.properties, add correspondence, write in a file (here with a graphical user better)

firstname=\u59D3 lastname=\u540D age=\u5E74\u9F84

That firstname corresponds to the "name", lastname corresponds to the "name", age corresponds to "age."

After modifying save.jsp, the label attribute change it, modify the

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>save user</title> </head> <body> <h1><font color="red">Save User</font> </h1> <s:form action="saveUser"> <s:textfield name="user.firstname" label="%{getText('firstname')}"></s:textfield> <s:textfield name="user.lastname" label="%{getText('lastname')}"></s:textfield> <s:textfield name="user.age" label="%{getText('age')}"></s:textfield> <s:submit></s:submit> </s:form> </body> </html>

In this way, we save.jsp have the support of the international.

8, the new package com.test.dao, the new package in UserDAO.java

package com.test.dao; import java.util.List; import com.test.bean.User; public interface UserDAO { public void saveUser(User user); public void removeUser(User user); public User findUserById(Integer id); public List<User> findAllUsers(); public void updateUser(User user); }

9, a new bag com.test.dao.impl, the new package in UserDAOImpl.java

package com.test.dao.impl; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.test.bean.User; import com.test.dao.UserDAO; public class UserDAOImpl extends HibernateDaoSupport implements UserDAO { @SuppressWarnings("unchecked") public List<User> findAllUsers() { // 根据hql查询 //@SuppressWarnings("unchecked") String hql = "from User user order by user.id desc"; return (List<User>)this.getHibernateTemplate().find(hql); } public User findUserById(Integer id) { // TODO Auto-generated method stub User user = (User)this.getHibernateTemplate().get(User.class, id); return user; } public void removeUser(User user) { // TODO Auto-generated method stub this.getHibernateTemplate().delete(user); } public void saveUser(User user) { // TODO Auto-generated method stub this.getHibernateTemplate().save(user); } public void updateUser(User user) { // TODO Auto-generated method stub this.getHibernateTemplate().update(user); } }

10, the new packet com.test.service, the new package in UserService.java

package com.test.service; import java.util.List; import com.test.bean.User; public interface UserService { public List<User> findAll(); public void save(User user); public void delete(User user); public User findById(Integer id); public void update(User user); }

11, the new packet com.test.service.impl, the new package in UserServiceImpl.java

package com.test.service.impl; import java.util.List; import com.test.bean.User; import com.test.dao.UserDAO; import com.test.service.UserService; public class UserServiceImpl implements UserService { private UserDAO userDao; public void delete(User user) { // TODO Auto-generated method stub this.userDao.removeUser(user); } public List<User> findAll() { // TODO Auto-generated method stub return this.userDao.findAllUsers(); } public User findById(Integer id) { // TODO Auto-generated method stub return this.userDao.findUserById(id); } public void save(User user) { // TODO Auto-generated method stub this.userDao.saveUser(user); } public void update(User user) { // TODO Auto-generated method stub this.userDao.updateUser(user); } public UserDAO getUserDao() { return userDao; } public void setUserDao(UserDAO userDao) { this.userDao = userDao; } }

12, edited structs.xml, add information to the action

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="user" extends="struts-default"> <action name="saveUser" class="saveUserAction"> <result name="success" type="redirect">listUser.action</result> <!-- 输入正确的话跳转到另一个action --> <result name="input">/saveUser.jsp</result> <!-- 输入错误的话跳就在saveUser.jsp页面继续输入 --> </action> </package> </struts>

13, then if you open the tomcat, will complain, Action class [saveUserAction] not found, this time because the configuration of our structs.xml which is an alias, this alias is for us to be provided by Spring, but this Spring configuration we have not write file.

14, the mysql-connector-java-5.0.3-bin.jar connector into the lib project directory edit /WebRoot/WEB-INF/applicationContext.xml

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org / 2001 / XMLSchema-instance "xsi: schemaLocation =" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd "> <! - the entire file is injected layer by layer, from the data source to sessionFactory injection, and then injected into the sessionFactory dao -> <bean id = "dataSource" class = "org.apache.commons.dbcp.BasicDataSource"> <! - database connection pool configuration -> <property name = "driverClassName" value = "com.mysql.jdbc.Driver"> </ property> <property name = "url" value = "jdbc: mysql: // localhost: 3306 / mytest "> </ property> <property name =" username "value =" root "> </ property> <property name="password" value="moiyer"></property> <property name="maxActive" value="100"></property> <property name="maxIdle" value="30"></property> <property name="maxWait" value="500"></property> <property name="defaultAutoCommit" value="true"></property> <!-- 本项目中的操作不需要事务,都是原子性的 --> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="mappingResources"> <list> <value>com/test/bean/User.hbm.xml</value><!-- 即包com.test.bean下的User.hbm.xml --> </list> </property> </bean> <bean id="userDao" class="com.test.dao.impl.UserDAOImpl" scope="singleton"> <!-- 这个singleton与设计模式里的singleton模式不同 --> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <bean id="userService" class="com.test.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"></property> </bean> <bean id="saveUserAction" class="com.test.action.user.SaveUserAction"> <property name="service" ref="userService"></property> </bean> </beans>

Then open the tomcat, will complain, Error creating bean with name 'sessionFactory' defined in ... this is because myeclipse causing packet collisions as we automatically import the package, remove asm-2.2.3.jar That lib directory resolves.

15, up to now, ssh framework of the project has been fully integrated up. Open the tomcat, visit HTTP: // localhost: 8080 / mytest / index.jsp , saving the user, whether in English can be saved (and the character set to utf-8 in the database is better: the page pagecoding set to utf-8 the structs arranged utf-8 (the default is true), the mysql arranged utf-8). Then save the page will jump to the user submits a page can not be accessed, it is because we have not written this page, but you can see the success from the database.

16, a new package in the ListUserAction.java com.test.action.user

package com.test.action.user; import java.util.Map; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.test.service.UserService; public class ListUserAction extends ActionSupport { @Override public String execute() throws Exception { // TODO Auto-generated method stub Map request = (Map) ActionContext.getContext().get("request"); request.put("list", service.findAll()); return SUCCESS; } private UserService service; public UserService getService() { return service; } public void setService(UserService service) { this.service = service; } }

Plus action listuser in the structs.xml

<action name="listUser" class="listUserAction"> <result>/list.jsp</result> <!-- 直接跳到list.jsp --> </action>

Plus listuser of bean in the applicationContext.xml

<bean id="listUserAction" class="com.test.action.user.ListUserAction"> <property name="service" ref="userService"></property> </bean>


17, the new list.jsp in WebRoot

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!-- 增加页面的structs支持 --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>list page</title> </head> <body> <h1><font color="red">User List</font> </h1> <table border="1" align="center"><!-- 删除和更新操作以后再实现 --> <tr> <td>id </td> <td>姓 </td> <td>名 </td> <td>年龄 </td> <td>删除 </td> <td>更新 </td> </tr> <s:iterator value="#request.list" id="us"> <tr> <td><s:property value="#us.id"/> </td> <td><s:property value="#us.firstname"/> </td> <td><s:property value="#us.lastname"/> </td> <td><s:property value="#us.age"/> </td> <td><s:a href="deleteUser.action?user.id=%{#us.id}">delete</s:a> <td><s:a href="updatePUser.action?user.id=%{#us.id}">update</s:a> </td> </tr> </s:iterator> </table> </body> </html>

18, re-open the tomcat, insert user operation, the operation was successful. Since then, this small project is almost complete.

19, add an input verification information. There are two methods: (1), using the input verification information in a validate method of action. (2), to check use of model-driven, based structs2 validation framework. The first method is easier to understand, be achieved using the second method below. There are two kinds of parity, 1) write check File: New SaveUserAction-validation.xml (note the name of the package com.test.action.user package must for this)

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators> <field name="user.firstname"> <field-validator type="requiredstring"> <message>required first name</message> </field-validator> </field> <field name="user.lastname"> <field-validator type="requiredstring"> <message>required last name</message> </field-validator> </field> <field name="user.age"> <field-validator type="required"> <message>required age</message> </field-validator> <field-validator type="int"> <param name="min">1</param> <param name="max">150</param> <message>age should be between ${min} and ${max}</message> </field-validator> </field> </validators>

Method 2) a new packet in a packet com.test.action.user SaveUserAction-validation.xml (note that this is a certain name)

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
	<field name="user">
		<field-validator type="visitor">        <!-- visitor类型表示通过另外一个配置文件对user的属性进行校验 -->
			<param name="context">user</param>   <!-- 与实际校验文件的名字有关,“类名-user-validation” -->
			<param name="appendPrefix">true</param>  <!-- 几个提示信息的前缀相同,都为user's -->
			<message>user's </message>
		</field-validator>
	</field>
</validators>
 
  
 
  

The new verification document in the User-user-validation.xml package com.test.bean

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators> <field name="firstname"> <field-validator type="requiredstring"> <message>required first name</message> </field-validator> </field> <field name="lastname"> <field-validator type="requiredstring"> <message>required last name</message> </field-validator> </field> <field name="age"> <field-validator type="required"> <message>required age</message> </field-validator> <field-validator type="int"> <param name="min">1</param> <param name="max">150</param> <message>age should be between ${min} and ${max}</message> </field-validator> </field> </validators>

20, well, check the frame is complete. But if the first data input errors, point to submit after being given the wrong information submitted reloading, but an error message will be superimposed on the output, which is obviously wrong. For use structs2.0 project management, after the request came, actionservelet will create an action, this error does not occur. But our project is managed by the spring, action by the bean factory to create the default is a single case, that is created using an action to handle all user requests, so the above error will occur. The solution is to modify the action stated applicationContext.xml

<Bean id = "saveUserAction" class = "com.test.action.user.SaveUserAction" scope = "prototype"> <-! Scope to ensure that for each new request, will create a new action to deal with -> <property name = "service" ref = "userService"> </ property> </ bean> <bean id = "listUserAction" class = "com.test.action.user.ListUserAction" scope = "prototype"> <property name = "service" ref = "userService"> </ property> </ bean>

21, delete user functions. In the package com.test.action.user new RemoveUserAction.java

package com.test.action.user; import com.opensymphony.xwork2.ActionSupport; import com.test.bean.User; import com.test.service.UserService; public class RemoveUserAction extends ActionSupport { private User user; private UserService service; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public UserService getService() { return service; } public void setService(UserService service) { this.service = service; } @Override public String execute() throws Exception { this.service.delete(user); return SUCCESS; } }


Add action statements in the structs.xml

<action name="deleteUser" class="removeUserAction"> <result name="success" type="redirect">listUser.action</result> </action>

Add action statements in the applicationContext.xml

<bean id="removeUserAction" class="com.test.action.user.RemoveUserAction" scope="prototype"> <property name="service" ref="userService"></property> </bean>

Well, the delete function of the project has been completed.
22, to complete the update function. This action updates the new UpdatePUserAction.java pretreated in the package com.test.action.user

package com.test.action.user; import com.opensymphony.xwork2.ActionSupport; import com.test.bean.User; import com.test.service.UserService; public class UpdatePUserAction extends ActionSupport { private User user; private UserService service; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public UserService getService() { return service; } public void setService(UserService service) { this.service = service; } @Override public String execute() throws Exception { user = this.service.findById(user.getId()); //两个user不是一样的 return SUCCESS; } }

Add action statements in the structs.xml 

<action name="updatePUser" class="updatePUserAction"> <result name="success">/update.jsp</result> </action>

Add action statements in the applicationContext.xml

<bean id="updatePUserAction" class="com.test.action.user.UpdatePUserAction" scope="prototype"> <property name="service" ref="userService"></property> </bean>

New update.jsp in WebRoot

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'update.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1><font color="red">Update User</font></h1> <s:form action="updateUser"> <table> <tr> <td> <s:hidden name="user.id" value="%{user.id}"></s:hidden> <!-- 将id设为不显示,但是还是会提交 --> </td> </tr> <tr> <td> <s:textfield name="user.firstname" value="%{user.firstname}" label="%{getText('firstname')}"></s:textfield> </td> </tr> <tr> <td> <s:textfield name="user.lastname" value="%{user.lastname}" label="%{getText('lastname')}"></s:textfield> </td> </tr> <tr> <td> <s:textfield name="user.age" value="%{user.age}" label="%{getText('age')}"></s:textfield> </td> </tr> <tr> <td> <s:submit></s:submit> </td> </tr> </table> </s:form> </body> </html>

New UpdateUserAction.java this action is updated in real package in com.test.action.user 

package com.test.action.user; import com.opensymphony.xwork2.ActionSupport; import com.test.bean.User; import com.test.service.UserService; public class UpdateUserAction extends ActionSupport { private User user; private UserService service; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public UserService getService() { return service; } public void setService(UserService service) { this.service = service; } @Override public String execute() throws Exception { this.service.update(user); return SUCCESS; } }

Add action statements in the structs.xml

<action name="updateUser" class="updateUserAction"> <result name="success" type="redirect">listUser.action</result> <result name="input">/update.jsp</result> </action>

Add action statements in the applicationContext.xml

<bean id="updateUserAction" class="com.test.action.user.UpdateUserAction" scope="prototype"> <property name="service" ref="userService"></property> </bean>

Input validation, the new package in UpdateUserAction-validation.xml com.test.user.action, the contents SaveUserAction-validation.xml same.

This update function has been completed.

 

 
  
 
 

Reproduced in: https: //www.cnblogs.com/moiyer/archive/2011/08/15/2316166.html

Guess you like

Origin blog.csdn.net/weixin_33832340/article/details/94693168