СоХабр закрыт.
С 13.05.2019 изменения постов больше не отслеживаются, и новые посты не сохраняются.
Привет, Хабр!
При устройстве на работу java программистом меня попросили написать тестовое web приложение «Телефонный справочник». Хочу поделиться с вами этим «шедевром».
Ext.application({
name: 'PhonesDir',
appFolder: 'app',
launch: function () {
Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: {
xtype: 'panel',
html: '<h2>Телефонный справочник</h2>'
}
});
}
});
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Справочник</title>
<link rel="stylesheet" type="text/css" href="resources/css/ext-all.css"/>
<script type="text/javascript" src="resources/ext-all.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
</body>
</html>
Ext.define('PhonesDir.view.SearchPhones', {
extend: 'Ext.form.Panel',
alias: 'widget.searchPhones',
bodyPadding: 10,
items: [
{
xtype: 'textfield',
name: 'search',
fieldLabel: 'Введите имя',
maxLength: 200
}
]
});
Ext.define('PhonesDir.view.PhonesGrid', {
extend: 'Ext.grid.Panel',
alias: 'widget.phonesGrid',
width: 400,
height: 300,
frame: true,
iconCls: 'icon-user',
columns: [
{
text: 'Имя',
flex: 1,
sortable: true,
dataIndex: 'name'
},
{
flex: 2,
text: 'Телефон',
sortable: true,
dataIndex: 'phone'
}
],
dockedItems: [
{
xtype: 'toolbar',
items: [
{
text: 'Добавить',
action: 'add',
iconCls: 'icon-add'
},
'-',
{
action: 'delete',
text: 'Удалить',
iconCls: 'icon-delete',
disabled: true
}
]
}
]
});
Ext.define('PhonesDir.view.AddWindowForm', {
extend: 'Ext.window.Window',
alias: 'widget.addWindowForm',
autoShow: true,
layout: 'fit',
modal: true,
items: [
{
bodyPadding: 10,
xtype: 'form',
items: [
{
xtype: 'textfield',
name: 'name',
fieldLabel: 'Имя',
regex: /^[А-Я-Ё][а-я-ё]{1,}$/,
regexText: 'Имя должно состоять из двух и более букв и начинаться с заглавной буквы',
allowBlank: false,
blankText: 'Это поле должно быть заполнено'
},
{
xtype: 'textfield',
name: 'phone',
fieldLabel: 'Телефон',
regex: /^([+][0-9]{11,12})*$/,
regexText: 'Телефон должно соответсвовать шаблону "+XXXXXXXXXXX" или "+XXXXXXXXXXXX", где X - цифры. ',
allowBlank: false,
blankText: 'Это поле должно быть заполнено'
}
]
}
],
buttons: [
{
text: 'Сохранить',
action: 'save',
disabled: true
},
{
text: 'Отменить',
handler: function () {
this.up('window').close();
}
}
]
});
Ext.define('PhonesDir.view.PhonesDirectory', {
extend: 'Ext.panel.Panel',
width: 500,
height: 360,
padding: 10,
alias: 'widget.phonesDirectory',
layout: 'border',
items: [
{
xtype: 'phonesGrid',
region: 'center'
},
{
xtype: 'panel',
html: '<div style="font: normal 18px cursive"><center><font size = "10">Телефонный справочник</font></center></div>',
region: 'north',
height: 80
},
{
xtype: 'searchPhones',
title: 'Поиск',
region: 'west',
width: 300,
collapsible: true,
collapsed: false
}
],
renderTo: Ext.getBody()
});
items: {
xtype: 'phonesDirectory'
}
Ext.define('PhonesDir.controller.PhonesDirectoryController', {
extend: 'Ext.app.Controller',
views: [
'AddWindowForm',
'PhonesDirectory',
'PhonesGrid',
'SearchPhones'
],
init: function () {
this.control({
});
}
Ext.application({
name: 'PhonesDir',
appFolder: 'app',
controllers: [
'PhonesDirectoryController'
],
launch: function () {
Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: {
xtype: 'phonesDirectory'
}
});
}
});
Ext.define('PhonesDir.model.PhonesDirectoryModel', {
extend: 'Ext.data.Model',
fields: ['name', 'phone'],
proxy: {
pageParam: 'search',
type: 'rest',
api: {
create: 'phone',
read: 'phone',
destroy: 'phone'
},
reader: {
type: 'json',
root: 'data',
successProperty: 'success'
},
writer: {
type: 'json',
writeAllFields: true
}
}
});
Ext.define('PhonesDir.store.PhonesDirectoryStore', {
extend: 'Ext.data.Store',
model: 'PhonesDir.model.PhonesDirectoryModel',
autoLoad: true,
autoSync: true,
proxy: {
type: 'rest',
api: {
create: 'phone',
read: 'phone',
destroy: 'phone'
},
reader: {
type: 'json',
root: 'data',
successProperty: 'success'
},
writer: {
type: 'json',
writeAllFields: true
}
}
});
@Entity
@Table(name = "phones")
public class Phone implements Serializable {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Pattern(regexp = "^[А-Я-Ё][а-я-ё]{1,}$")
@Column(name = "name")
private String name;
@Pattern(regexp = "^([+][0-9]{11,12})([,][+][0-9]{11,12})*$")
@Column(name = "phone")
private String phone;
public Phone() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
public interface PhoneDao {
void add(Phone entity);
void delete(Phone entity);
Collection<Phone> getPhones(String search);
public List findByPhone(String name, String phone);
}
public class PhoneDaoImpl implements PhoneDao {
@PersistenceContext
private EntityManager emf;
@Override
public void add(Phone phone) {
emf.persist(phone);
}
@Override
public void delete(Phone phone) {
emf.remove(emf.getReference(Phone.class, phone.getId()));
}
@Override
public Collection<Phone> getPhones(String search) {
if (null == search || search.trim().isEmpty()) {
return emf.createQuery(
"select c from Phone c")
.getResultList();
}
return emf.createQuery(
"select c from Phone c where c.name like :search")
.setParameter("search", search.trim() + "%")
.getResultList();
}
public List<Phone> findByPhone(String name, String phone) {
return emf.createQuery(
"select c from Phone c where c.name = :name and c.phone = :phone")
.setParameter("name", name)
.setParameter("phone", phone)
.getResultList();
}
}
public interface PhoneService {
Boolean add(Phone phone);
Collection<Phone> getPhones(String search);
void delete(Phone phone);
}
public class PhoneServiceImpl implements PhoneService {
private PhoneDao phoneDao;
public PhoneDao getPhoneDao() {
return phoneDao;
}
public void setPhoneDao(PhoneDao phonePhoneDao) {
this.phoneDao = phonePhoneDao;
}
@Transactional
@Override
public Boolean add(Phone entity) {
List<Phone> duplicate = phoneDao.findByPhone(entity.getName(), entity.getPhone());
if (duplicate.isEmpty()) {
phoneDao.add(entity);
return true;
}
return false;
}
@Transactional
@Override
public Collection<Phone> getPhones(String search) {
return phoneDao.getPhones(search);
}
@Transactional
@Override
public void delete(Phone entity) {
phoneDao.delete(entity);
}
}
@Controller
@RequestMapping("/phone")
public class PhoneController {
@Autowired
private PhoneService phoneService;
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public Collection<Phone> getPhone(String search) {
return phoneService.getPhones(search);
}
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public ExtResult setPhone(@RequestBody Phone phone) {
return new ExtResult(phoneService.add(phone), phone);
}
@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
@ResponseBody
public String delPhone(@RequestBody Phone phone) {
phoneService.delete(phone);
return "del";
}
}
public class ExtResult {
private boolean success;
private Phone data;
public ExtResult(boolean success, Phone data) {
this.success = success;
this.data = data;
}
public ExtResult() {
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public Phone getData() {
return data;
}
public void setData(Phone data) {
this.data = data;
}
}
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"
p:packagesToScan="model"
p:jpaProperties-ref="jpaProperties"
p:persistenceProvider-ref="persistenceProvider"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"
depends-on="entityManagerFactory"/>
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close"
p:driverClass="com.mysql.jdbc.Driver"
p:jdbcUrl="jdbc:mysql://localhost:3306/phonedir?characterEncoding=UTF-8"
p:username="root"
p:password="1234"
p:idleConnectionTestPeriodInMinutes="1"
p:idleMaxAgeInSeconds="240"
p:minConnectionsPerPartition="2"
p:maxConnectionsPerPartition="5"
p:partitionCount="2"
p:acquireIncrement="1"
p:statementsCacheSize="100"
p:releaseHelperThreads="2"
p:statisticsEnabled="false"/>
<bean id="persistenceProvider" class="org.hibernate.ejb.HibernatePersistence"/>
<bean id="jpaProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="connection.pool_size">1</prop>
<prop key="current_session_context_class">thread</prop>
<prop key="show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean name="phoneDao" class="model.dao.impl.PhoneDaoImpl">
</bean>
<bean name="PhoneService" class="service.impl.PhoneServiceImpl">
<property name="phoneDao" ref="phoneDao">
</property>
</bean>
</beans>
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="controllers"/>
<mvc:view-controller path="/" view-name="/index.jsp"/>
<mvc:resources mapping="/**" location="/"/>
<mvc:annotation-driven/>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/my-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
Ext.define('PhonesDir.controller.PhonesDirectoryController', {
extend: 'Ext.app.Controller',
views: [
'AddWindowForm',
'PhonesDirectory',
'PhonesGrid',
'SearchPhones'
],
stores: ['PhonesDirectoryStore'],
models: ['PhonesDirectoryModel'],
refs: [
{selector: 'phonesGrid',
ref: 'phonesGrid'},
{selector: 'phonesGrid button[action="add"]',
ref: 'phonesGridAdd'},
{selector: 'phonesGrid button[action="delete"]',
ref: 'phonesGridDelete'},
{selector: 'searchPhones button[action="search"]',
ref: 'searchPhones'},
{selector: 'addWindowForm',
ref: 'addWindowForm'},
{selector: 'phonesDirectory',
ref: 'phonesDirectory'},
{selector: 'addWindowForm textfield[name=name] ',
ref: 'addWindowFormName'},
{selector: 'addWindowForm textfield[name=phone]',
ref: 'addWindowFormPhone'},
{selector: 'addWindowForm button[action=save]',
ref: 'addWindowFormPhoneSave'}
],
init: function () {
this.control({
'phonesGrid button[action=add]': {
click: this.onAddPhone
},
'phonesGrid button[action=delete]': {
click: this.onDelPhone
},
'searchPhones textfield[name="search"]': {
change: this.onChangeText
},
'phonesGrid': {
cellclick: this.onLineGrid
},
'addWindowForm button[action=save]': {
click: this.onSavePhone
},
'addWindowForm textfield[name=name]': {
change: this.onValidation
},
'addWindowForm textfield[name=phone]': {
change: this.onValidation
}
});
},
onSavePhone: function (button) {
var me = this;
var phoneModel = Ext.create('PhonesDir.model.PhonesDirectoryModel');
phoneModel.set(this.getAddWindowForm().down('form').getValues());
phoneModel.save({
success: function (operation, response) {
var objAjax = operation.data;
me.getPhonesDirectoryStoreStore().add(objAjax);
me.getAddWindowForm().close();
},
failure: function (dummy, result) {
Ext.MessageBox.show({
title: 'Дубликат!',
msg: 'Такое имя и телефон уже существуют',
buttons: Ext.Msg.OK,
icon: Ext.Msg.ERROR
});
}
});
},
onAddPhone: function () {
Ext.widget('addWindowForm');
},
onDelPhone: function () {
var sm = this.getPhonesGrid().getSelectionModel();
var rs = sm.getSelection();
this.getPhonesGrid().store.remove(rs[0]);
this.getPhonesGrid().store.commitChanges();
this.getPhonesGridDelete().disable();
},
onChangeText: function () {
this.getPhonesDirectoryStoreStore().load({
params: {
search: this.getPhonesDirectory().down('searchPhones').getValues()
}
});
},
onLineGrid: function () {
this.getPhonesGridDelete().enable();
},
onValidation: function () {
if (this.getAddWindowFormName().validate() && this.getAddWindowFormPhone().validate()) {
this.getAddWindowFormPhoneSave().enable();
} else {
this.getAddWindowFormPhoneSave().disable();
}
}
});
<%@page contentType="text/html" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Справочник</title>
<link rel="stylesheet" type="text/css" href="resources/resources/css/ext-all.css"/>
<style type="text/css">
.icon-delete {
background-image: url(resources/resources/delete.png) !important;
}
.icon-add {
background-image: url(resources/resources/add.png) !important;
}
</style>
<script type="text/javascript" src="resources/ext-all.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
</body>
</html>
комментарии (9)