SSH框架 注解的使用

标签: SSH

为什么要使用注解?

正常情况下没有注解的话会导致spring配置文件中多个实体配置需要注入多个Bean,每个实体每个框架中需要多个配置文件,十分繁琐。

导包过程:Spring需要面向切面,日志管理等,其他的三大框架内容由MyEclipse自动导入。


web.xml 不变 如果通过注解方式进行ssh配置,注解应该放在web-inf/content,(webinf中的文件不能通过地址栏进行访问,只能通过跳转显示)设置结果路径为根目录下

<constant name="struts.convention.result.path" value="/"/>

默认包路径包含action的所有包都会被struts作为含有Action类的路径来搜索

<constant name="struts.convention.default.parent.package" value="default-package" />

<constant name="struts.convention.package.loacltors" value="action"/>

<package dname="default-package' extends="json-default">

</package>

 


建立Spring配置文件

为Spring指定扫描注解bean组件的根包

<contant;component-scan base-package="com.it"/>

为Spring声明使用注解事务,并制定所依赖的事务管理器包

tx:annotation-driven transaction-manager="txManager"/>

 

<property name="annotatedClasses">

<list> 此处指定注解实体类</list>

</property>

配置事务管理器

<bean id="txManager"

class="org.springramework.orm.hibernate3.HibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory"/>

</bean>

Hibernate持久化类

@[email protected](name="student')

public class Student{

}

@SequenceGenerator(name="generator",sequenceName="se_per",alloctionSize=1)//表示每次主键值增加的大小,例如设置成1,则表示每次创建新纪录后自动加1,默认为50

@Id

@GeneratedValue(strategy=SEQUENCE,generator="generator")

@Column(name="stuId",unique=true,nullable=false,percision=5,scale=0)


ServiceImpl.java

@Transactional声明该类的方法都是事务性

@Service("studentService")//声明该类是Spring管理的业务bean,其id为studentService



private SessionFactory sessionFacotry;

@Autowired//声明从spring容器中自动注入sessionFacotry

写在set方法上


开发Sturts2的Action

@Controller

@Scope("prototype")//单例

@ParentPackage(value="default-package")

@Namespace("/")

@Results({

@Result(name="success",location="success.jsp",type="dispatch"),//默认类型请求转发

@Result(name="input',location="register.jsp"),

@Result(name="returnjson",type="json"),

})

其中sturts.xml还有用,指定default package的值。


全部的三大框架均由MyEclipse软件生成注入,cfg配置文件和hbm.xml文件均写入applicationContext.xml中和注释中。

注意:先添加Spring框架,再加入Hibernate框架,最后注入Sturts2。

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"

    xmlns:p="http://www.springframework.org/schema/p"

     xmlns:context="http://www.springframework.org/schema/context"

    

    xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-4.1.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx.xsd"

    xmlns:tx="http://www.springframework.org/schema/tx">

    <bean id="dataSource"

        class="org.apache.commons.dbcp.BasicDataSource">

         <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>

           <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>

         <property name="username" value="system"></property>

         <property name="password" value="Yuquan980730"></property>

    </bean>

    <context:annotation-config/>

    <context:component-scan base-package="com.it.ssh"></context:component-scan>

    <bean id="sessionFactory"

        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

         <property name="dataSource">

             <ref bean="dataSource" />

         </property>

         <property name="hibernateProperties">

             <props>

                 <prop key="hibernate.dialect">

                     org.hibernate.dialect.Oracle9Dialect

                 </prop>

             </props>

         </property>

         <property name="annotatedClasses">

             <list>

                 <value>com.it.ssh.entity.Person</value></list>

         </property></bean>

    <bean id="transactionManager"

        class="org.springframework.orm.hibernate4.HibernateTransactionManager">

         <property name="sessionFactory" ref="sessionFactory" />

    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" /></beans>

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>

  <constant name="struts.convention.result.path" value="/"></constant>

</struts>   

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

  <display-name>8_6SSH</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>

  <listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  </listener>



  <context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>classpath:applicationContext.xml</param-value>

  </context-param>

  <filter>

    <filter-name>struts2</filter-name>

    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

  </filter>

  <filter-mapping>

    <filter-name>struts2</filter-name>

    <url-pattern>/*</url-pattern>

  </filter-mapping>

</web-app>

Person实体类

package com.it.ssh.entity;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import static javax.persistence.GenerationType.SEQUENCE;

import javax.persistence.Id;

import javax.persistence.SequenceGenerator;

import javax.persistence.Table;
/**
* Person entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "PERSON", schema = "SYSTEM")
public class Person implements java.io.Serializable {
    // Fields
    private Integer pid;
    private String pname;
    private String pwd;
    // Constructors
    /** default constructor *
    public Person() {
    }
    /** full constructor */
    public Person(String pname, String pwd) {
        this.pname = pname;
        this.pwd = pwd;
    }
    // Property accessors
    @SequenceGenerator(name = "generator",sequenceName="seq_newsId",allocationSize=1)
    @Id
    @GeneratedValue(strategy = SEQUENCE, generator = "generator")
    @Column(name = "PID", unique = true, nullable = false, precision = 5, scale = 0)
    public Integer getPid() {//
        return this.pid;
    }
    public void setPid(Integer pid) {
        this.pid = pid;
    }
    @Column(name = "PNAME", length = 20)
    public String getPname() {
        return this.pname;
    }
    public void setPname(String pname) {
        this.pname = pname;
    }
    @Column(name = "PWD", length = 20)

    public String getPwd() {

        return this.pwd;
    }

    public void setPwd(String pwd) {

        this.pwd = pwd;

    }

}

PersonDao.java

package com.it.ssh.dao;

import com.it.ssh.entity.Person;

public interface personDao {

    public boolean login(Person person);

}

PersonDaoImpl.java

package com.it.ssh.Impl;



import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;



import com.it.ssh.dao.personDao;

import com.it.ssh.entity.Person;

@Repository

public class PersonDaoImpl implements personDao {

    private SessionFactory sessionFactory;

    @Autowired

    public void setSessionFactory(SessionFactory sessionFactory) {

        this.sessionFactory = sessionFactory;

    }



    @Override

    public boolean login(Person person) {

        // TODO Auto-generated method stub

        String hql="from Person where pid=? and pwd=?";

        Session session=sessionFactory.getCurrentSession();

        Query q=session.createQuery(hql);

        q.setInteger(0, person.getPid());

        q.setString(1, person.getPwd());

        boolean flag=false;

        Object obj=q.uniqueResult();

        if(obj!=null){

            flag=true;    

        }

        return flag;

    }



}

personService.java

package com.it.ssh.dao;

import com.it.ssh.entity.Person;

public interface personService {

    public boolean login(Person person);

}

personServiceImpl.java

package com.it.ssh.Impl;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;



import com.it.ssh.dao.personDao;

import com.it.ssh.dao.personService;

import com.it.ssh.entity.Person;

@Service("personService")

@Transactional

public class personSerivceImpl implements personService {

    private personDao personDao;   

    @Autowired

    public void setPersonDao(personDao personDao) {

        this.personDao = personDao;
    }

    @Override

    public boolean login(Person person) {

        // TODO Auto-generated method stub

        return personDao.login(person);

    }



}

PersonAction.java

package com.it.ssh.action;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Result;

import org.apache.struts2.convention.annotation.Results;

import org.springframework.stereotype.Controller;

import com.it.ssh.dao.personService;

import com.it.ssh.entity.Person;

import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

@Controller

@Results({@Result(name="success",location="show.jsp"),@Result(name="input",location="index.jsp",type="redirect")})

public class personAction extends ActionSupport implements ModelDriven<Person>{

    /**

     *

     */

    private static final long serialVersionUID = 1L;

    Person person =new Person();

    private personService personService;

    @Resource(name="personService")

    public void setPersonService(personService personService) {

        this.personService = personService;

    }

    @Override

    public Person getModel() {

        // TODO Auto-generated method stub

        return person;

    }

    public  String login() throws Exception {

        boolean flag=false;

        flag=personService.login(person);

        String path=INPUT;

        if(flag){

            path=SUCCESS;

        }

        return path;
     

    }



}

index.jsp

<%@ 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 'index.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>

    <s:form action="person!login" method="post">

    <s:textfield name="pid" label="账号"></s:textfield>

    <s:password name="pwd" label="密码"></s:password>

    <tr>

    <td colspan="2">

    <s:submit value="提交"  theme="simple"></s:submit>

    </td>

    </tr>

    </s:form>

  </body>

</html>

show.jsp

<%@ 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 'show.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>

<s:property value="pid"/>

  </body>

</html>

 

版权声明:本文为YuQuanZhang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/YuQuanZhang/article/details/81474939