Rebuild SSH framework integration Basics

Source: Internet
Author: User

The overall framework of the Project is good (although quite dissatisfied with this framework, because there are still shadows in servlet)

Re-build this framework today and get familiar with it again to see if it is successful. (Class code mainly depends on copying)

1. Create a Main Page

/Admin/user/user_ooxx.jsp

/Index/ooxx. jsp

Login. jsp

2. Add the Struts framework,

Yourcompany ---> change to the corresponding company name, and the project name will be OK. (Other options should also be understood)

3. Configure the Struts-config file, which can be configured manually or in a graphical interface.

This is a basic framework for page Jump.

4. Write formbean, write the parameters passed by the page in formbean, and get set method. For example:

private String name;private String password;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;}

Both loginform and userform can be written (struts2 is directly in action, and formbean is not split)

In this step, the parameters passed over the page are received, and the result is that the page is returned.

V. Start of business logic

1. (abstract) business logic layer com. Jake. OA. Service. iuserservice. Java

2. (Implementation) business logic layer com. Jake. OA. Service. userserviceimpl. Java

Vi. integration between the view layer and the control layer

Struts is a control layer framework, mainly responsible for the connection between the view layer and the control layer,

At this time, you can write some methods in the action to achieve the jump of the view and control layer. (For example, using formbean in action to obtain data, Judge data, and redirect data)

For example:

public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {LoginForm loginForm = (LoginForm) form;// TODO Auto-generated method stubHashtable<String, Object> temp = new Hashtable<String, Object>();temp = this.login(request, response, temp, loginForm);if(temp != null){return mapping.findForward(temp.get("url").toString().trim());}return null;}public Hashtable<String, Object> login(HttpServletRequest request,HttpServletResponse response, Hashtable<String, Object> temp,LoginForm loginForm){    String name = loginForm.getName() == null ? ""     : loginForm.getName().trim();    String password = loginForm.getPassword() == null ? ""    : loginForm.getPassword().trim();     if("admin".equals(name) && "123".equals(password)){    temp.put("loginName", name);    request.getSession().setAttribute("temp", temp);    temp.put("url", "success");    }else{    temp.put("massage", "");    temp.put("url", "error");    }return temp;}

Of course, pay attention to the Red Section, here need to be paired with the Struts-config.xml file ing, in order to correctly jump to the desired page.

VII. Integration of other pages and business logic

(At this time, you can do other page content) Note that basically all connection jumps pass. DoIn the form of, basically through the processing of the business (such as login authentication ).

VIII. Combination of Spring IoC

First, add the Spring framework.

Note: The jar packages added by MySQL 2.5 are different in different versions, additional 6.6 check spring2.5web libraries and select jar library installation as copy checked library contents to project folder (TLDs always copied) directory as/webroot/WEB-INF/lib, I tried to put applicationcontext in the same directory as SRC. The result failed and was successfully moved to Lib.

Select next>

Select enable AOP as needed. This project is not used, so it is not checked.

Select New -----> finished for bean configuration type.

9. Perform IOC to the end (for what is IOC and Di, please refer to my previous diary)

At present, I have learned the understanding level of spring. Spring IoC has brought me two benefits. Saves time on Initialization objects and supports interface-oriented programming.

There are many things to pay attention to in IOC. For example, Spring provides three injection methods. However, normal people only use one method (although hibernatetemple seems to have been implemented in all three methods ), we only use one method, Set Value injection, that is, get and set method injection.

Here, my thoughts are divided into two parts:

I. Logic (CODE)

Ii. Spring or struts configuration section.

IOC requires us to know the class to be initialized in advance,

First, let's take a look at two sections of configuration, which is configured in struts, so that spring can manage a configuration information of struts classes.

  <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">  <set-property value="/WEB-INF/applicationContext.xml" property="contextConfigLocation"/>    </plug-in>

In struts1 (the SSH version of struts2 is expected to be implemented in May), submit the action to the configuration of delegatingactionproxy managed by spring.

<action      name="userForm"      path="/user"      scope="request"      type="org.springframework.web.struts.DelegatingActionProxy"      validate="false">      <forward name="success" path="/admin/user/usersuccess.jsp" />      ...    </action>

In this way, the user's useraction is handed over to the Spring IoC container for management. (Similar actions can be handed over to spring Management)

Next, let's look at the spring configuration.

<Bean name = "/user" class = "com. SMS. Struts. Action. useraction"> <! -- If property exists, it must be dependent. --> <property name = "iuserservice"> <! -- Specify the Bean class whose ID is iuserservice. This Bean class must also be defined in this applicationcontext. XML --> <ref bean = "iuserservice"/> </property> </bean> <bean id = "iuserservice" class = "com. SMS. service. ipml. userserviceimpl "> <property name =" idaotoolservice "> <ref bean =" idaotoolservice "/> </property> </bean> <! -- After Hibernate is loaded --> <bean id = "idaotoolservice" class = "com. SMS. idao. impl. daotoolserviceimpl"> <! -- The property name must be the same as that of ref ???? --> <Property name = "sessionfactory"> <ref bean = "sessionfactory"/> </property> </bean> ......

As a result, complete the above part of spring Configuration

Check the database operation interface of idaotoolservice.

import java.util.List;import org.hibernate.HibernateException;public interface IDaoToolService {public List quesr(String hql) throws HibernateException;public void save(Object obj) throws HibernateException;public void update(Object obj) throws HibernateException;public void saveOrUpdate(Object obj) throws HibernateException;public void delete(Object obj) throws HibernateException;}

Then, in the Code section, the get set method assigns the spring injection class to a class. First look at useraction

public class UserAction extends Action {/* * Generated Methods */private IUserService iuserService;public IUserService getIuserService() {return iuserService;}public void setIuserService(IUserService iuserService) {this.iuserService = iuserService;}/** * Method execute *  * @param mapping * @param form * @param request * @param response * @return ActionForward */public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {        。。。。。。 

Let's look at the database operation interface implementation class. (No get set here? Refer to the previous blog posts on inheriting the injection of hibernatedaosupport)

Public class daotoolserviceimpl extends hibernatedaosupport implementsidaotoolservice {/***** query database information * @ Param string hql * @ return list */public list quesr (string hql) throws hibernateexception {return this. gethibernatetemplate (). find (hql);}/*** Delete object * @ Param object * @ return void */Public void Delete (Object OBJ) throws hibernateexception {This. gethibernatetemplate (). delete (OBJ);}/*** save object * @ Param object * @ return **/Public void save (Object OBJ) throws hibernateexception {This. gethibernatetemplate (). save (OBJ);}/*** save or update the object * @ Param object * @ return **/Public void saveorupdate (Object OBJ) throws hibernateexception {This. gethibernatetemplate (). saveorupdate (OBJ);}/*** update object * @ Param object * @ return void ***/Public void Update (Object OBJ) throws hibernateexception {This. gethibernatetemplate (). update (OBJ );}}

In fact, when useraction is completed, or after writing the business logic that does not deal with the database, you can start to import hibernate.

Hibernate for myeclipse can be loaded manually or using myeclipse. The following shows how to load myeclipse,

I. Configure the data source

And then finish it.

Ii. Load jar packages and configurations

In fact, you can select either or not. Only some instance-specific hibernate classes are generated.

During this period, an error may be reported.

However

Import the corresponding package.

Then configure the ing.

The remaining next (you can choose hibernate style next) Next next finish (there are not so many next ~.~ )

In this way, the three frameworks are basically integrated. Let's take a look at the details.

A configuration file about Hibernate is added to applicationcontext. xml.

<bean id="bean" class="org.apache.commons.dbcp.BasicDataSource"><property name="driverClassName"value="com.mysql.jdbc.Driver"></property><property name="url" value="jdbc:mysql://localhost:3306/sms"></property><property name="username" value="root"></property><property name="password" value="123"></property></bean><bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="dataSource"><ref bean="bean" /></property><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop></props></property></bean>

Under the package browsing view, we can see that the model and its corresponding ing files are added. (Don't forget that hibernate supports multiple ing methods. Here we only introduce XML ing)

These are all automatically generated. You do not need to write it manually. (Of course, you must recognize what it means and what it means. Make changes .)

At this time, you can call the interface method of idaotoolservice to access its implementation class (inherited from hibernatedaosupport)

Public class daotoolserviceimpl extends hibernatedaosupport implementsidaotoolservice {/***** query database information * @ Param string hql * @ return list */public list quesr (string hql) throws hibernateexception {// todo auto-generated method stub // cool ~~~~~~~~ That is, hibernatetemplate. This is also recommended for instructor Ma... Return this. gethibernatetemplate (). find (hql);}/*** Delete object * @ Param object * @ return void */Public void Delete (Object OBJ) throws hibernateexception {This. gethibernatetemplate (). delete (OBJ);}/*** save object * @ Param object * @ return **/Public void save (Object OBJ) throws hibernateexception {This. gethibernatetemplate (). save (OBJ);}/*** save or update the object * @ Param object * @ return **/Public void saveorupdate (Object OBJ) throws hibernateexception {This. gethibernatetemplate (). saveorupdate (OBJ);}/*** update object * @ Param object * @ return void ***/Public void Update (Object OBJ) throws hibernateexception {This. gethibernatetemplate (). update (OBJ );}}

public final void setSessionFactory(SessionFactory sessionFactory) {        if (this.hibernateTemplate == null || sessionFactory != this.hibernateTemplate.getSessionFactory()) {            this.hibernateTemplate = createHibernateTemplate(sessionFactory);        }  } public final HibernateTemplate getHibernateTemplate() {        return this.hibernateTemplate;  }  

At this time, the. gethibernatetemplate (). Update (OBJ) or anything can be used.

This is where the framework integrates many interpolation operations,

The rest is about business logic or something.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.