Spring Framework: различия между версиями

Содержимое удалено Содержимое добавлено
Строка 450:
Создадим новый Web проект в NetBeans под именем OrganizationProject:
 
 
<source lang="java">
 
</source>
 
Создаем базу данных organization и соединение в NetBeans.
Строка 589 ⟶ 585 :
 
</beans>
 
</source>
 
Веб слой приложения.
 
Файл org.app.controller.UsersController:
 
<source lang="java">
package org.app.controller;
 
import org.app.config.UserSettings;
import org.app.service.IGroupsService;
import org.app.service.IUserService;
import org.app.service.PositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
@Controller
@RequestMapping(value="/user")
public class UsersController {
@Autowired
private PositionService positionService;
@Autowired
private IUserService userService;
@Autowired
private IGroupsService groupsService;
@Autowired
private UserSettings userSettings;
Logger log = LoggerFactory.getLogger(UsersController.class);
@RequestMapping(value="/index.htm", method=RequestMethod.GET)
public String index(Model model) {
model.addAttribute("groups", groupsService.getAll());
model.addAttribute("positions", positionService.getAll());
model.addAttribute("users", userService.getAll());
log.debug("xxx debug");
userSettings.loadSettings();
log.debug("user settings :{}, {}", userSettings.getCountry(), userSettings.getLanguage());
return "user/list";
}
@RequestMapping(value="addajax.htm",method=RequestMethod.POST)
public @ResponseBody String add(@RequestParam(value = "username", required = true) String username,
@RequestParam(value = "positionid", required = true) Integer positionid,
@RequestParam(value = "groupid", required = true) Integer groupid ){
String returnText;
if(!username.isEmpty()){
userService.addEntity(username, groupid, positionid);
returnText = "User has been added to the list. Total number of users are: " +username+";posid = "+positionid+";grid="+groupid;//+ userList.size();
}else{
returnText = "Sorry, an error has occur. User has not been added to list.";
}
return returnText;
}
@RequestMapping(value="/deleteajax.htm",method=RequestMethod.POST)
public @ResponseBody String delete(@RequestParam(value = "userid", required = true) Integer userid ){
String returnText;
if(userid.intValue() != 0){
userService.deleteEntity(userid);
returnText = "deleted: " +userid;
}else{
returnText = "Sorry, an error has occur. User has not been added to list.";
}
return returnText;
}
}
 
</source>
 
Файл org.app.controller.GroupController:
 
<source lang="java">
 
package org.app.controller;
 
import org.app.domain.entities.Groups;
import org.app.service.IGroupsService;
import org.app.utils.GroupValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
 
@Controller
public class GroupController {
@Autowired
private IGroupsService groupsService;
Logger log = LoggerFactory.getLogger(GroupController.class);
GroupValidator groupValidator = new GroupValidator();
@RequestMapping(value="/group/list.htm", method=RequestMethod.GET)
public String list(Model model){
model.addAttribute("groups", groupsService.getAll());
log.debug("group list");
return "group/list";
}
@RequestMapping(value="/group/add.htm",method=RequestMethod.GET)
public String add(@ModelAttribute("groupAttribute") Groups group){
return "group/add";
}
 
@RequestMapping(value = "/group/save.htm", method = RequestMethod.POST)
public String save(@ModelAttribute("groupAttribute") Groups group, BindingResult result) {
groupValidator.validate(group, result);
if (!result.hasErrors()) {
if (group.getId() == null) {
log.debug("group save");
this.groupsService.addEntity(group);
}
}
return "redirect:/group/list.htm";
}
}
 
</source>
 
Файл org.app.controller.Main для проверки работы:
 
<source lang="java">
package org.app.controller;
 
import java.util.Locale;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
 
public class Main {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext(new String[] {"/web/WEB-INF/dispatcher-servlet.xml", "/web/WEB-INF/applicationContext.xml"});
String message = context.getMessage("title.required", null, Locale.getDefault());
System.out.println("mess:"+message);
}
}
 
</source>
org.app.utils.GroupValidator
<source lang="java">
package org.app.utils;
 
import org.app.domain.entities.Groups;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
 
public class GroupValidator implements Validator{
 
@Override
public boolean supports(Class<?> type) {
return Groups.class.equals(type);
}
 
@Override
public void validate(Object o, Errors errors) {
Groups group = (Groups) o;
if(group.getTitle().trim().equals("")){
errors.rejectValue("title", "title.required");
}
}
}
 
</source>
 
Файл org.app.config.UserSettings для сохранения информации пользователя:
 
<source lang="java">
package org.app.config;
 
import java.util.Locale;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
@Component("userSettings")
public class UserSettings {
@Value("#{countryBean}") //inject bean
private Country country;
 
public UserSettings() {
}
public void loadSettings(){
country.loadSettings();
}
public String getLanguage(){
return country.getLanguage();
}
public String getCountry(){
return country.getCountry();
}
}
 
@Component("countryBean")
class Country {
 
@Value("RU") //inject string directly
private String country;
@Value("ru")
private String language;
public Country() {
}
 
public String getCountry() {
return country;
}
 
public String getLanguage() {
return language;
}
void loadSettings(){
this.country = Locale.getDefault().getCountry();
this.language = Locale.getDefault().getLanguage();
}
}
</source>
 
Слой представления.
 
Файл include.jsp:
<source lang="xml">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
</source>
 
Файл user/list.jsp:
 
<source lang="xml">
<%@ include file="../include.jsp" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.7.2.min.js" />"></script>
<script type="text/javascript">
function addUser() {
var name = $('#name').val();
var positionid = $("#positions option:selected").val();
var groupid = $("#groups option:selected").val();
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/user/addajax.htm",
data: "username=" + name+"&positionid="+positionid+"&groupid="+groupid,
success: function(response){
$('#info').html(response);
$('#name').val('');
},
error: function(e){
alert('Error: ' + e);
}
});
}
function deleteUser(id){
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/user/deleteajax.htm",
data: "userid=" + id,
success: function(response){
$('#info').html(response);
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
</head>
<body>
<a href="${pageContext.request.contextPath}/group/list.htm">groups</a><br/>
<h1>List users</h1>
<ul>
<c:forEach items="${users}" var="user">
<li>Name : <c:out value="${user.username}" />;<input type="button" value="Delete" onclick="deleteUser(${user.id})">
</c:forEach>
</ul>
<table>
<tr><td>Enter your name : </td><td> <input type="text" id="name"></td><td>
<select id="positions">
<c:forEach items="${positions}" var="pos">
<option value="${pos.id}"><c:out value="${pos.title}" /></option>
</c:forEach>
</select>
</td><td>
<select id="groups">
<c:forEach items="${groups}" var="group">
<option value="${group.id}"><c:out value="${group.title}" /></option>
</c:forEach>
</select>
</td></tr>
<tr><td colspan="2"><input type="button" value="Add Users" onclick="addUser()"><br/></td></tr>
<tr><td colspan="2"><div id="info" style="color: green;"></div></td></tr>
</table>
</body>
</html>
 
</source>
 
Файл group/add.jsp:
 
<source lang="xml">
<%@ include file="../include.jsp" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<style>
 
.error {
 
color: #ff0000;
 
font-style: italic;
 
}
</style>
</head>
<body>
<h1>Add group</h1>
<c:url var="indexUrl" value="/user/index.htm" />
<c:url var="saveUrl" value="/group/save.htm" />
<form:form modelAttribute="groupAttribute" method="POST" action="${saveUrl}">
Title:
<form:input path="title"></form:input><form:errors path="title" cssClass="error" />
<input type="submit" value="Save" />
</form:form>
<p>Return to <a href="${indexUrl}">Index Page</a></p>
</body>
</html>
 
</source>
 
Файл group/list.jsp:
 
<source lang="xml">
<%@ include file="../include.jsp" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>List groups</h1>
<c:url var="indexUrl" value="/user/index.htm" />
<a href="add.htm">create</a><br/>
<c:if test="${empty groups}">
List is empty.<br/>
</c:if>
<ul>
<c:forEach items="${groups}" var="group">
<li>Title : <c:out value="${group.title}" />;
</c:forEach>
</ul>
<p>Return to <a href="${indexUrl}">Index Page</a></p>
</body>
</html>
 
</source>
 
Файл logback.xml:
 
<source lang="xml">
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %5p | %-55logger{55} | %m %n</pattern>
</encoder>
</appender>
 
<logger name="org.app.service">
<level value="DEBUG" />
</logger>
 
<logger name="org.springframework">
<level value="DEBUG" />
</logger>
 
<root>
<level value="DEBUG" />
<appender-ref ref="CONSOLE" />
</root>
</configuration>
</source>
 
Файл messages.properties:
 
<source lang="text">
title.required = Title is required
</source>
 
Доменный слой.
 
HibernateUtil:
 
<source lang="java">
package org.utils;
 
import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
 
public class HibernateUtil {
 
private static final SessionFactory sessionFactory;
private static final Session session;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
session = sessionFactory.openSession();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session getSession(){
return session;
}
}
 
</source>
 
Файл org.app.service.IUserService:
 
<source lang="java">
package org.app.service;
 
import java.util.List;
import org.app.domain.entities.Users;
 
public interface IUserService {
List<Users> getAll();
void addEntity(String username, Integer groupid, Integer positionid);
void deleteEntity(Integer id);
}
</source>
 
Файл org.app.service.IGroupsService:
 
<source lang="java">
 
package org.app.service;
 
import java.util.List;
import org.app.domain.entities.Groups;
 
public interface IGroupsService {
List<Groups> getAll();
void addEntity(Groups group);
void deleteEntity(Integer id);
}
 
</source>
 
Файл org.app.service.IPositionService:
 
<source lang="java">
 
package org.app.service;
 
import java.util.List;
import org.app.domain.entities.Positions;
 
public interface IPositionService {
List<Positions> getAll();
}
 
</source>
 
Файл org.app.service.UsersService:
 
<source lang="java">
 
package org.app.service;
 
import java.util.ArrayList;
import java.util.List;
import org.app.domain.entities.Users;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
 
import org.springframework.stereotype.Service;
import org.utils.HibernateUtil;
 
@Service
public class UsersService implements IUserService{
Session session;
public UsersService() {
this.session = HibernateUtil.getSession();
}
@Override
public List<Users> getAll(){
List <Users>resultList = new ArrayList<Users>();
String hql = "from Users u";
session.beginTransaction();
Query q = session.createQuery(hql);
resultList.addAll(q.list());
session.getTransaction().commit();
return resultList;
}
public static void main(String[] args) {
try {
String hql = "from Users u where id = 1";
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query q = session.createQuery(hql);
List <Users>resultList = q.list();
for(Users u : resultList){
System.out.println("user:"+u.getUsername());
}
System.out.println("size:" + resultList.toString());
session.getTransaction().commit();
SQLQuery sq = session.createSQLQuery("select u.* from users as u, languages as l, language_user as lu where l.id = lu.language_id and u.id = lu.user_id and l.title = ? and u.position_id = ?");
sq.setParameter(0, "c#");
sq.setParameter(1, 3);
List founded = sq.list();
System.out.println("res:"+founded.size());
} catch (HibernateException he) {
he.printStackTrace();
}
}
 
@Override
public void addEntity(String username, Integer groupid, Integer positionid) {
session.beginTransaction();
//Query q = session.createQuery(hql);
Users u = new Users(username, positionid, groupid);
session.save(u);
session.getTransaction().commit();
}
 
@Override
public void deleteEntity(Integer id) {
Users user = (Users) session.get(Users.class, id);
if(user != null) {
session.beginTransaction();
session.delete(user);
session.getTransaction().commit();
}
}
}
 
</source>
 
Файл org.app.service.GroupsService:
 
<source lang="java">
 
package org.app.service;
 
import java.util.ArrayList;
import java.util.List;
import org.app.domain.entities.Groups;
import org.hibernate.Query;
import org.hibernate.Session;
 
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.utils.HibernateUtil;
 
@Service
@Transactional
public class GroupsService implements IGroupsService{
Session session;
public GroupsService() {
this.session = HibernateUtil.getSession();
}
@Override
public List<Groups> getAll(){
List <Groups>resultList = new ArrayList<Groups>();
String hql = "from Groups g";
Query q = session.createQuery(hql);
resultList.addAll(q.list());
return resultList;
}
 
@Override
public void addEntity(Groups group) {
session.save(group);
}
 
@Override
public void deleteEntity(Integer id) {
Groups g = (Groups) session.get(Groups.class, id);
if(g != null) {
session.delete(g);
}
}
}
 
</source>
 
Файл org.app.service.PositionService:
 
<source lang="java">
 
package org.app.service;
 
import java.util.ArrayList;
import java.util.List;
import org.app.domain.entities.Positions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;
import org.utils.HibernateUtil;
 
@Service
public class PositionService implements IPositionService{
 
Session session;
public PositionService() {
this.session = HibernateUtil.getSession();
}
 
@Override
public List<Positions> getAll() {
List <Positions>resultList = new ArrayList<Positions>();
String hql = "from Positions u";
session.beginTransaction();
Query q = session.createQuery(hql);
resultList.addAll(q.list());
session.getTransaction().commit();
return resultList;
}
}
 
</source>
Файл org.app.domain.entities.Users:
<source lang="java">
package org.app.domain.entities;
 
public class Users implements java.io.Serializable {
 
private Integer id;
private String username;
private Integer positionId;
private Integer groupId;
 
public Users() {
}
 
public Users(String username, Integer positionId, Integer groupId) {
this.username = username;
this.positionId = positionId;
this.groupId = groupId;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getPositionId() {
return this.positionId;
}
public void setPositionId(Integer positionId) {
this.positionId = positionId;
}
public Integer getGroupId() {
return this.groupId;
}
public void setGroupId(Integer groupId) {
this.groupId = groupId;
}
}
</source>
 
Файл org.app.domain.entities.Groups:
 
<source lang="java">
package org.app.domain.entities;
 
public class Groups implements java.io.Serializable {
 
private Integer id;
private String title;
 
public Groups() {
}
 
public Groups(String title) {
this.title = title;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
}
</source>
 
И файлы настроек Hibernate:
 
Файл hibernate.cfg.xml:
 
<source lang="xml">
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/organization</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<mapping resource="org/app/domain/entities/Positions.hbm.xml"/>
<mapping resource="org/app/domain/entities/Languages.hbm.xml"/>
<mapping resource="org/app/domain/entities/Groups.hbm.xml"/>
<mapping resource="org/app/domain/entities/Users.hbm.xml"/>
</session-factory>
</hibernate-configuration>
 
</source>
 
Файл hibernate.reveng.xml:
 
<source lang="xml">
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
<schema-selection match-catalog="organization"/>
<table-filter match-name="languages"/>
<table-filter match-name="positions"/>
<table-filter match-name="groups"/>
<table-filter match-name="users"/>
</hibernate-reverse-engineering>
 
</source>