Simple SSH saving based on Annotations

Source: Internet
Author: User

Simple SSH saving based on Annotations

Requirement: Build an SSH framework environment, use annotations for related injection (entity annotation, AOP annotation, DI injection), and save user information

Effect:

1. import dependency packages

Ii. project directory structure

Iii. web. xml configuration

<? Xml version = "1.0" encoding = "UTF-8"?>
<Web-app xmlns = "http://xmlns.jcp.org/xml/ns/javaee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
Version = "3.1">

<! -- Lazy loading filter to solve the problem of lazy loading -->
<Filter>
<Filter-name> openSession </filter-name>
<Filter-class> org. springframework. orm. hibernate5.support. OpenSessionInViewFilter </filter-class>
</Filter>
<Filter-mapping>
<Filter-name> openSession </filter-name>
<Url-pattern> *. action </url-pattern>
</Filter-mapping>

<! -- Struts2 front-end Controller -->
<Filter>
<Filter-name> struts </filter-name>
<Filter-class> org. apache. struts2.dispatcher. ng. filter. StrutsPrepareAndExecuteFilter </filter-class>
</Filter>
<Filter-mapping>
<Filter-name> struts </filter-name>
<Url-pattern>/* </url-pattern>
</Filter-mapping>

<! -- Spring creates a listener -->
<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>

</Web-app>

Iv. applicationContext. xml configuration

<? 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: tx = "http://www.springframework.org/schema/tx"
Xmlns: contex = "http://www.springframework.org/schema/context"
Xsi: schemaLocation = "http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans.xsd
Http://www.springframework.org/schema/tx
Http://www.springframework.org/schema/tx/spring-tx.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context.xsd>

<! -- Enable annotation scanning -->
<Contex: component-scan base-package = "com. pri"/>

<! -- The following is the hibernate configuration -->
<Bean id = "dataSource" class = "com. mchange. v2.c3p0. ComboPooledDataSource">
<Property name = "driverClass" value = "com. mysql. jdbc. Driver"/>
<Property name = "jdbcUrl" value = "jdbc: mysql: // ssh_demo1? UseSSL = false "/>
<Property name = "user" value = "root"/>
<Property name = "password" value = ""/>
</Bean>

<Bean id = "sessionFactory" class = "org. springframework. orm. hibernate5.LocalSessionFactoryBean">
<! -- 1. Core configuration -->
<Property name = "dataSource" ref = "dataSource"/>

<! -- 2. optional configuration -->
<Property name = "hibernateProperties">
<Props>
<Prop key = "hibernate. dialect"> org. hibernate. dialect. MySQL5Dialect </prop>
<Prop key = "hibernate. show_ SQL"> true </prop>
<Prop key = "hibernate. format_ SQL"> true </prop>
<Prop key = "hibernate. hbm2ddl. auto"> update </prop>
</Props>
</Property>
<! -- 3. Scan the ing file -->
<Property name = "packagesToScan" value = "com. pri. domain"> </property>
</Bean>

<! -- Enable transaction control -->
<Bean id = "transactionManager" class = "org. springframework. orm. hibernate5.HibernateTransactionManager">
<Property name = "sessionFactory" ref = "sessionFactory"> </property>
</Bean>
<Tx: annotation-driven transaction-manager = "transactionManager"/>
</Beans>

5. log4j. properties configuration

# How to Set logging to the console
Log4j. appender. std = org. apache. log4j. leleappender
# Output in black and err in red
Log4j. appender. std. Target = System. err
Log4j. appender. std. layout = org. apache. log4j. PatternLayout
Log4j. appender. std. layout. ConversionPattern = % d {yyyy-MM-dd HH: mm: ss} % 5 p % c {1}: % L-% m % n
# How to Set logging to a file
Log4j. appender. file = org. apache. log4j. FileAppender
# Log file path file name
Log4j. appender. file. File = mylog. log
# Log output format
Log4j. appender. file. layout = org. apache. log4j. PatternLayout
Log4j. appender. file. layout. ConversionPattern = % d {ABSOLUTE} % 5 p % c {1}: % L-% m % n
# Log output level and configuration record solution. Level: error> warn> info> debug> trace
Log4j. rootLogger = info, std, file

6. Page code

Index. jsp

<% @ Page contentType = "text/html; charset = UTF-8" language = "java" %>
<Html>
<Head>
<Title> $ Title $ </title>
</Head>
<Body>
<H3> Add a customer <Form action = "$ {pageContext. request. contextPath}/customerAction_save" method = "post">
Name: <input type = "text" name = "name"/> <br/>
Age: <input type = "text" name = "age"/> <br/>
<Input type = "submit" value = "submit"/> <br/>
</Form>
</Body>
</Html>

Success. jsp

<% @ Page contentType = "text/html; charset = UTF-8" language = "java" %>
<Html>
<Head>
<Title> homepage </title>
</Head>
<Body>
<H1> saved successfully! </H1>
</Body>
</Html>

VII. entity-Layer Code

Package com. pri. domain;

Import javax. persistence .*;


@ Entity
@ Table (name = "customer ")
Public class Customer {
@ Id
@ Column (name = "userId ")
@ GeneratedValue (strategy = GenerationType. IDENTITY)
Private Integer userId;

@ Column (name = "name ")
Private String name;
@ Column (name = "age ")
Private Integer age;

Public Integer getUserId () {return userId ;}

Public void setUserId (Integer userId) {this. userId = userId ;}

Public String getName () {return name ;}

Public void setName (String name) {this. name = name ;}

Public Integer getAge () {return age ;}

Public void setAge (Integer age) {this. age = age ;}
}

8. action-Layer Code

Package com. pri. action;

Import com. pri. domain. Customer;
Import com. pri. service. CustomerService;
Import com. opensymphony. xwork2.ActionSupport;
Import com. opensymphony. xwork2.ModelDriven;
Import org. apache. struts2.convention. annotation. Action;
Import org. apache. struts2.convention. annotation. Namespace;
Import org. apache. struts2.convention. annotation. ParentPackage;
Import org. apache. struts2.convention. annotation. Result;
Import org. springframework. context. annotation. Scope;
Import org. springframework. stereotype. Controller;
Import javax. annotation. Resource;


@ Controller ("customerAction ")
@ ParentPackage (value = "struts-default ")
@ Scope ("prototype ")
@ Namespace (value = "/")
Public class CustomerAction extends ActionSupport implements ModelDriven <Customer> {

Private Customer customer;

@ Resource (name = "customerService ")
Private CustomerService customerService;

@ Override
Public Customer getModel (){
If (customer = null ){
Customer = new Customer ();
}
Return customer;
}

@ Action (value = "customerAction_save ",
Results = {@ Result (name = SUCCESS, type = "redirect", location = "/success. jsp ")})
Public String save (){
CustomerService. save (customer );
Return SUCCESS;
}
}

9. service-Layer Code

Package com. pri. service;

Import com. pri. domain. Customer;

Public interface CustomerService {
Void save (Customer user );
}
// ================================================ =
Package com. pri. service. impl;

Import com. pri. domain. Customer;
Import com. pri. dao. CustomerDao;
Import com. pri. service. CustomerService;
Import org. springframework. stereotype. Service;
Import org. springframework. transaction. annotation. Transactional;

Import javax. annotation. Resource;

@ Service ("customerService ")
@ Transactional
Public class CustomerServiceImpl implements CustomerService {

@ Resource (name = "customerDao ")
Private CustomerDao customerDao;

@ Override
Public void save (Customer customer ){
CustomerDao. save (customer );
}
}

10. dao Layer Code

Package com. pri. dao;

Import com. pri. domain. Customer;

Public interface CustomerDao {
Void save (Customer customer );
}

// ================================================ ======================================
Package com. pri. dao. impl;

Import org. hibernate. SessionFactory;
Import org. springframework. orm. hibernate5.support. HibernateDaoSupport;
Import org. springframework. stereotype. Component;
Import javax. annotation. Resource;

@ Component ("myHibernateDaoSupport ")
Public class MyHibernateDaoSupport extends HibernateDaoSupport {

@ Resource (name = "sessionFactory ")
Public void setSuperSessionFactory (SessionFactory sessionFactory ){
Super. setSessionFactory (sessionFactory );
}
}
// ================================================ ==============
Package com. pri. dao. impl;

Import com. pri. dao. CustomerDao;
Import com. pri. domain. Customer;
Import org. springframework. stereotype. Repository;

@ Repository ("customerDao ")
Public class CustomerDaoImpl extends MyHibernateDaoSupport implements CustomerDao {

@ Override
Public void save (Customer customer ){
GetHibernateTemplate (). save (customer );
}
}

11. Spring Beans Dependencies

 

This article permanently updates link: https://www.bkjia.com/Linux/2018-02/151099.htm

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.