'JAVA'에 해당되는 글 9건

  1. 2023.01.30 파일업로드 구현 1
  2. 2023.01.23 DispatcherServlet
  3. 2023.01.18 Dao JDBC #3
  4. 2023.01.18 DAO JDBC #2
  5. 2023.01.18 DAO jdbc
  6. 2023.01.01 Servletでいまの時間を表示する
  7. 2023.01.01 IntellijでTomcat8.5を連携するときに不具合発生
  8. 2022.12.31 tomcat 8.0.x 설치
  9. 2022.12.31 openjdk 1.8.X 설치
2023. 1. 30. 00:53

먼저

apache commons fileupload와 commons io 라이브러리를 클래스패스에 연결

 

 

dto

RequestUtil

컨틀롤러 적용

ProductDao dao = new ProductDao();
if (ServletFileUpload.isMultipartContent(request)) {
    ParamDto dto = RequestUtil.parseParam(request);

    String product_name = dto.getParamMap().get("product_name");
    String description = dto.getParamMap().get("description");
    int price = Integer.parseInt(dto.getParamMap().get("price").toString());

    FileItem item = dto.getFileMap().get("img");
    String filename = item.getName();
    String path = request.getSession().getServletContext().getRealPath("/images/");
    item.write(new File(path + filename));

    Product product = new Product();
    product.setProduct_name(product_name);
    product.setDescription(description);
    product.setPrice(new BigDecimal(price));
    product.setFilename(filename);

    dao.insert(product);
}

return "redirect:/product.do";

 

package com.sora.webapptest.util;

import com.sora.webapptest.dto.ParamDto;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class RequestUtil {
    public static ParamDto parseParam(HttpServletRequest request) {
        ParamDto result = new ParamDto();

        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

        upload.setHeaderEncoding("UTF-8");

        try {
            List<FileItem> fileItemList = upload.parseRequest(request);

            for (FileItem fileItem :fileItemList) {
                if (fileItem.isFormField()) {
                    result.getParamMap().put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
                } else {
                    result.getFileMap().put(fileItem.getFieldName(), fileItem);
                }
            }
        } catch (FileUploadException | UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        return result;
    }
}

 

package com.sora.webapptest.dto;

import org.apache.commons.fileupload.FileItem;

import java.util.HashMap;
import java.util.Map;

public class ParamDto {
    private Map<String, String> paramMap;
    private Map<String, FileItem> fileMap;

    public ParamDto() {
        paramMap = new HashMap<>();
        fileMap = new HashMap<>();
    }

    public Map<String, String> getParamMap() {
        return paramMap;
    }

    public void setParamMap(Map<String, String> paramMap) {
        this.paramMap = paramMap;
    }

    public Map<String, FileItem> getFileMap() {
        return fileMap;
    }

    public void setFileMap(Map<String, FileItem> fileMap) {
        this.fileMap = fileMap;
    }
}

'JAVA' 카테고리의 다른 글

DispatcherServlet  (0) 2023.01.23
Dao JDBC #3  (0) 2023.01.18
DAO JDBC #2  (0) 2023.01.18
DAO jdbc  (0) 2023.01.18
Servletでいまの時間を表示する  (0) 2023.01.01
Posted by 다만사
2023. 1. 23. 10:39

출처: MVC基础框架项目的实现_孤狼灬笑的博客-CSDN博客

 

MVC基础框架项目的实现_孤狼灬笑的博客-CSDN博客

项目实现思路: 过滤器1(设置编码)--->过滤器2(事务管理)-->DispacherServlet-中央控制器(用于参数处理  invoke 视图处理)-->控制器:*Controller(*业务名字)-->IOC <beans>配置变量-->FruitServic-->FruitDAO调用BaseDAO-->B

blog.csdn.net

약간 수정했음.

 

ioc 부분

 

구현 클래스

 

applicationContext.xml

 

기본 HelloController.java

 

응용 CountriesController.java

 

java 8 이상에서 되는 -parameters 컴파일러 옵션 필수 (이렇게 하지 않으면, 메소드 파라미터의 이름을 가져올 수 없음)

참조: 

Maven, Gradle이면 소스코드에 삽입가능

 

intellij 에선

확인 후 빌드 -> 프로젝트 다시 빌드 

package com.sora.webapptest.controllers;

import com.sora.webapptest.dao.CountryDao;
import com.sora.webapptest.dto.Country;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

public class CountriesController {

    private String index(HttpServletRequest request) {
        CountryDao countryDao = new CountryDao();
        request.setAttribute("countryList", countryDao.getCountryList());
        return "country/index";
    }

    private String add() {
        return "country/add";
    }

    private String add_ok(String country_id, String country_name, Integer region_id) {
        Country country = new Country();
        country.setCountry_id(country_id);
        country.setCountry_name(country_name);
        country.setRegion_id(new BigDecimal(region_id));
        CountryDao countryDao = new CountryDao();

        countryDao.addCountry(country);

        return "redirect:countries.do";
    }

    private String edit(String cid, HttpServletRequest request) {
        if (cid != null) {
            CountryDao countryDao = new CountryDao();
            Country country = countryDao.getCountryByCid(cid);
            request.setAttribute("country", country);
            return "country/edit";
        }

        return "error";
    }

    private String update(String country_id, String country_name, Integer region_id) {
        Country country = new Country();
        country.setCountry_id(country_id);
        country.setCountry_name(country_name);
        country.setRegion_id(new BigDecimal(region_id));
        CountryDao countryDao = new CountryDao();
        countryDao.updateCountry(country);

        return "redirect:countries.do";

    }

    private String del(String cid) {
        if (cid != null) {
            CountryDao countryDao = new CountryDao();
            int result = countryDao.deleteCountry(cid);
            if (result == 1) {
                return "redirect:countries.do";
            }
        }
        return "error";
    }
}

 

package com.sora.webapptest.controllers;

public class HelloController {

    private String index() {
        return "index";
    }
}
<?xml version="1.0" encoding="UTF-8" ?>

<beans>
    <bean id="hello" class="com.sora.webapptest.controllers.HelloController" />
    <bean id="countries" class="com.sora.webapptest.controllers.CountriesController" />
</beans>
package com.sora.webapptest.ioc;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class ClassPathXmlApplicationContext implements BeanFactory {

    private Map<String, Object> beanMap = new HashMap<>();
    private String path = "applicationContext.xml";

    public ClassPathXmlApplicationContext() {
        this("applicationContext.xml");
    }

    public ClassPathXmlApplicationContext(String path) {
        if (path == null || path.equals("")) {
            throw new RuntimeException("path가 비어있습니다.");
        }
        try {
            InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path);
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(inputStream);


            NodeList beanNodeList = document.getElementsByTagName("bean");
            for (int i=0; i<beanNodeList.getLength(); i++) {
                Node beanNode = beanNodeList.item(i);
                if (beanNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element beanElement = (Element) beanNode;
                    String beanId = beanElement.getAttribute("id");
                    String className = beanElement.getAttribute("class");
                    Class beanClass = Class.forName(className);
                    Object beanObj = beanClass.newInstance();
                    beanMap.put(beanId, beanObj);


                }
            }


        } catch (ParserConfigurationException | IOException | SAXException | ClassNotFoundException |
                 InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object getBean(String id) {
        return beanMap.get(id);
    }
}

 

package com.sora.webapptest.ioc;

public interface BeanFactory {
    Object getBean(String id);
}
package com.sora.webapptest;



import com.sora.webapptest.ioc.BeanFactory;
import com.sora.webapptest.ioc.ClassPathXmlApplicationContext;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

@WebServlet("*.do")
public class DispatcherServlet extends HttpServlet {

    private BeanFactory beanFactory;

    @Override
    public void init() throws ServletException {
        super.init();
        beanFactory = new ClassPathXmlApplicationContext();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //http://localhost:8080/WebTestApp/hello.do
        //servlet path : /hello.do
        // /hello.do -> hello
        // hello -> HelloController
        String servletPath = req.getServletPath();
        servletPath = servletPath.substring(1);
        int lastDotIndex = servletPath.lastIndexOf(".do");
        servletPath = servletPath.substring(0, lastDotIndex);
        Object controllerBeanObj = beanFactory.getBean(servletPath);
        String operate = req.getParameter("operate");
        if (operate == null || operate.equals("")) {
            operate = "index";
        }
        try {
            Method[] methods = controllerBeanObj.getClass().getDeclaredMethods();
            for (Method method : methods) {
                if (operate.equals(method.getName())) {
                    Parameter[] parameters = method.getParameters();
                    Object[] parameterValues = new Object[parameters.length];
                    for (int i=0; i<parameters.length; i++) {
                        Parameter parameter = parameters[i];
                        String parameterName = parameter.getName();
                        if ("request".equals(parameterName)) {
                            parameterValues[i] = req;
                        } else if ("response".equals(parameterName)) {
                            parameterValues[i] = resp;
                        } else if ("session".equals(parameterName)) {
                            parameterValues[i] = req.getSession();
                        } else {
                            String parameterValue = req.getParameter(parameterName);
                            Object parameterObj = parameterValue;
                            String typeName = parameter.getType().getName();
                            if (parameterObj != null) {
                                if ("java.lang.Integer".equals(typeName)) {
                                    parameterObj = Integer.parseInt(parameterValue);
                                }
                            }
                            parameterValues[i] = parameterObj;
                        }
                    }
                    method.setAccessible(true);
                    Object returnObj = method.invoke(controllerBeanObj, parameterValues);
                    String methodReturnStr = (String) returnObj;
                    if (methodReturnStr.startsWith("redirect:")) {
                        String redirectStr = methodReturnStr.substring("redirect:".length());
                        resp.sendRedirect(redirectStr);
                    } else {
                        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/WEB-INF/views/" + methodReturnStr + ".jsp");
                        requestDispatcher.forward(req, resp);
                    }
                }
            }
        } catch (InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }


    }


}

'JAVA' 카테고리의 다른 글

파일업로드 구현  (1) 2023.01.30
Dao JDBC #3  (0) 2023.01.18
DAO JDBC #2  (0) 2023.01.18
DAO jdbc  (0) 2023.01.18
Servletでいまの時間を表示する  (0) 2023.01.01
Posted by 다만사
2023. 1. 18. 23:49

executeUpdate 編

 

なんか変化をしたいとき、使うメソッドだ。

今回はDAOと、jspを作ってやってた。

いままでのEmployeeDAOだ。

次はjspです。入力と処理を担当するjspだ。

<%--
  Created by IntelliJ IDEA.
  User: daman
  Date: 2023-01-18
  Time: 오후 11:30
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.sora.webapptest.dao.EmployeeDAO" %>
<%@ page import="com.sora.webapptest.dto.Employee" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    request.setCharacterEncoding("utf-8");
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    Employee employee = new Employee();
    employee.setLast_name(name);
    employee.setEmail(email);

    EmployeeDAO dao = new EmployeeDAO();
    int result = dao.insertEmp(employee);
    if (result == 1) {
        response.sendRedirect("add_employee.jsp");
    } else {
        out.println("오류 발생");
    }
%>
</body>
</html>
<%--
  Created by IntelliJ IDEA.
  User: daman
  Date: 2023-01-18
  Time: 오후 11:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h2>사원 추가</h2>
<form method="post" action="add_employee_ok.jsp">
    이름: <input type="text" name="name"> <br/>
    E-mail: <input type="email" name="email"> <br/>
    <input type="submit" value="추가"/>
</form>

</body>
</html>
package com.sora.webapptest.dao;

import com.sora.webapptest.basedao.BaseDAO;
import com.sora.webapptest.dto.Employee;

import java.util.List;

public class EmployeeDAO extends BaseDAO<Employee> {

    public List<Employee> getEmpList() {
        String sql = "select employee_id, first_name, last_name, email from employees";
        return executeQuery(sql, (Object[]) null);
    }

    public Employee getEmpById(int id) {
        String sql = "select * from employees where employee_id = ?";
        return load(sql, id);
    }

    public int insertEmp(Employee employee) {
        String sql = "insert into employees(employee_id, last_name, email, hire_date, job_id) values (" +
                "employees_seq.nextval, ?, ?, sysdate, 'IT_PROG')";
        return executeUpdate(sql, employee.getLast_name(), employee.getEmail());
    }
}
protected int executeUpdate(String sql, Object... params) {
    try {
        conn = getConn();
        pstmt = conn.prepareStatement(sql);
        setParams(pstmt, params);

        return pstmt.executeUpdate();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        close(rs, pstmt, conn);
    }
}

'JAVA' 카테고리의 다른 글

파일업로드 구현  (1) 2023.01.30
DispatcherServlet  (0) 2023.01.23
DAO JDBC #2  (0) 2023.01.18
DAO jdbc  (0) 2023.01.18
Servletでいまの時間を表示する  (0) 2023.01.01
Posted by 다만사
2023. 1. 18. 22:39

DBのクローズするのは忘れて、追加して、T load メソッドを追加した。

修正したクラスは前回に修正して送った。

protected T load(String sql, Object... params) {
    try {
        conn = getConn();
        pstmt = conn.prepareStatement(sql);
        setParams(pstmt, params);
        rs = pstmt.executeQuery();

        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();

        if (rs.next()) {
            T entity = (T)entityClass.newInstance();

            for (int i=0; i<columnCount; i++) {
                String columnName = rsmd.getColumnName(i+1);
                Object columnValue = rs.getObject(i+1);
                setValue(entity, columnName, columnValue);
            }

            return entity;
        }
    } catch (SQLException | InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    } finally {
        close(rs, pstmt, conn);
    }

    return null;
}

 

テストは DTOを作って、今度はサブレットでした。

つぎはDTOだ。

サブレットもある。

package com.sora.webapptest;

import com.sora.webapptest.dao.EmployeeDAO;
import com.sora.webapptest.dto.Employee;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "EmpServlet", value = "/EmpServlet")
public class EmpServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EmployeeDAO dao = new EmployeeDAO();
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        String empId = request.getParameter("id");
//        List<Employee> employeeList = dao.getEmpList();
        Employee employee = dao.getEmpById(Integer.parseInt(empId));
        out.println("<html><head><title>emp list</title></head><body>");
        out.println("<table border=\"1\">");
//        for (Employee employee : employeeList) {
        out.print("<tr>");
        out.print("<td>" + employee.getEmployee_id()
                        + "</td><td>" + employee.getFirst_name()
                        + "</td><td>" + employee.getLast_name()
                        + "</td><td>" + employee.getEmail()
                        + "</td><td>" + employee.getPhone_number()
                        + "</td><td>" + employee.getHire_date()
                        + "</td><td>" + employee.getJob_id()
                        + "</td><td>" + employee.getSalary()
                        + "</td><td>" + employee.getCommission_pct()
                        + "</td><td>" + employee.getManager_id()
                        + "</td><td>" + employee.getDepartment_id() + "</td>" );
        out.println("</tr>");
//        }
        out.println("</table>");
        out.println("</body></html>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
package com.sora.webapptest.dto;

import java.math.BigDecimal;
import java.util.Date;

public class Employee {
    private BigDecimal employee_id;
    private String first_name;
    private String last_name;

    private String email;

    private String phone_number;

    private Date hire_date;

    private String job_id;

    private BigDecimal salary;

    private BigDecimal commission_pct;

    private BigDecimal manager_id;

    private BigDecimal department_id;

    public BigDecimal getEmployee_id() {
        return employee_id;
    }

    public void setEmployee_id(BigDecimal employee_id) {
        this.employee_id = employee_id;
    }

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone_number() {
        return phone_number;
    }

    public void setPhone_number(String phone_number) {
        this.phone_number = phone_number;
    }

    public Date getHire_date() {
        return hire_date;
    }

    public void setHire_date(Date hire_date) {
        this.hire_date = hire_date;
    }

    public String getJob_id() {
        return job_id;
    }

    public void setJob_id(String job_id) {
        this.job_id = job_id;
    }

    public BigDecimal getSalary() {
        return salary;
    }

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }

    public BigDecimal getCommission_pct() {
        return commission_pct;
    }

    public void setCommission_pct(BigDecimal commission_pct) {
        this.commission_pct = commission_pct;
    }

    public BigDecimal getManager_id() {
        return manager_id;
    }

    public void setManager_id(BigDecimal manager_id) {
        this.manager_id = manager_id;
    }

    public BigDecimal getDepartment_id() {
        return department_id;
    }

    public void setDepartment_id(BigDecimal department_id) {
        this.department_id = department_id;
    }
}

'JAVA' 카테고리의 다른 글

DispatcherServlet  (0) 2023.01.23
Dao JDBC #3  (0) 2023.01.18
DAO jdbc  (0) 2023.01.18
Servletでいまの時間を表示する  (0) 2023.01.01
IntellijでTomcat8.5を連携するときに不具合発生  (0) 2023.01.01
Posted by 다만사
2023. 1. 18. 01:01

 

역시 개발은 12시 이후에 해야 되나보다.... 그래서 60세이후론 힘듬...ㅋㅋ

CSDN을 참고로 DAO 패턴을 작성했다. 역시 좋은 자료가 많음...

 

먼저 BaseDAO이다.

아직 완성된 것은 아니지만, 목록은 나온다. 원작에서는 ioc 까지 구현했지만, 자바 기본에선 일단 이정도면 되겠다.

완벽히 이해하려면 자바 리플렉션과 제네릭스를 이해해야하지만,,

 

다음은 이 BaseDAO를 상속받은 EmpDAO이다.

 

그리고 테스트를 진행한 서블릿이다.

 

개발툴은 자바 11(1.8)과 톰캣 8.5 그리고 인텔리제이 ultimate 이다.

 

package com.sora.webapptest;

import com.sora.webapptest.dao.EmployeeDAO;
import com.sora.webapptest.dto.Employee;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "EmpServlet", value = "/EmpServlet")
public class EmpServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EmployeeDAO dao = new EmployeeDAO();
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        List<Employee> employeeList = dao.getEmpList();
        out.println("<html><head><title>emp list</title></head><body>");
        out.println("<ul>");
        for (Employee employee : employeeList) {
            out.println("<li>" + employee.getEmployee_id() + " " + employee.getFirst_name() + "</li>");
        }
        out.println("</ul>");
        out.println("</body></html>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
package com.sora.webapptest.dao;

import com.sora.webapptest.basedao.BaseDAO;
import com.sora.webapptest.dto.Employee;

import java.util.List;

public class EmployeeDAO extends BaseDAO<Employee> {

    public List<Employee> getEmpList() {
        String sql = "select employee_id, first_name, last_name from employees";
        return executeQuery(sql, (Object[]) null);
    }
}

 

package com.sora.webapptest.basedao;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public abstract class BaseDAO<T> {
    public final String DRIVER = "oracle.jdbc.OracleDriver";
    public final String URL = "jdbc:oracle:thin:@localhost:1521:java";
    public final String USER = "hr";
    public final String PWD = "hr";

    protected Connection conn;
    protected PreparedStatement pstmt;
    protected ResultSet rs;

    private Class entityClass;

    public BaseDAO() {

        Type genericType = getClass().getGenericSuperclass();
        Type[] actualTypeArguments = ((ParameterizedType) genericType).getActualTypeArguments();
        Type actualType = actualTypeArguments[0];
        try {
            entityClass = Class.forName(actualType.getTypeName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected Connection getConn() {
        try {
            //1.
            Class.forName(DRIVER);

            return DriverManager.getConnection(URL, USER, PWD);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void close(ResultSet rs, PreparedStatement pstmt, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void setParams(PreparedStatement pstmt, Object... params) throws SQLException {
        if (params != null && params.length > 0) {
            for (int i=0; i<params.length; i++) {
                pstmt.setObject(i+1, params[i]);
            }
        }
    }

    private void setValue(Object obj, String property, Object propertyValue) {
        Class clazz = obj.getClass();
        try {
            Field field = clazz.getDeclaredField(property.toLowerCase());
            field.setAccessible(true);
            field.set(obj, propertyValue);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    protected List<T> executeQuery(String sql, Object... params) {
        List<T> list = new ArrayList<>();
        try {
            conn = getConn();
            pstmt = conn.prepareStatement(sql);
            setParams(pstmt, params);
            rs = pstmt.executeQuery();

            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();

            while (rs.next()) {
                T entity = (T)entityClass.newInstance();
                for(int i=0; i<columnCount; i++) {
                    String columnName = rsmd.getColumnName(i+1);
                    Object columnValue = rs.getObject(i+1);
                    setValue(entity, columnName, columnValue);

                }
                list.add(entity);
            }
        } catch (SQLException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        } finally {
            close(rs, pstmt, conn);
        }

        return list;
    }





}

 

'JAVA' 카테고리의 다른 글

Dao JDBC #3  (0) 2023.01.18
DAO JDBC #2  (0) 2023.01.18
Servletでいまの時間を表示する  (0) 2023.01.01
IntellijでTomcat8.5を連携するときに不具合発生  (0) 2023.01.01
tomcat 8.0.x 설치  (0) 2022.12.31
Posted by 다만사
2023. 1. 1. 20:29

ついに環境の問題が解決できました!

基本的に提供されたservletソースに少し修正しました。

package com.sora.webapptest;

import java.io.*;
import java.time.LocalTime;
import java.util.Date;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {
    private String message;

    public void init() {
        message = "Hello World!";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        LocalTime time = LocalTime.now();
        // Hello
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>" + time + "</h1>");
        out.println("</body></html>");
    }

    public void destroy() {
    }
}

修正した部分は

LocalTime time = LocalTime.now();
out.println("<h1>" + time + "</h1>");

2箇所です。

 

結果は結構いいですね。

'JAVA' 카테고리의 다른 글

DAO JDBC #2  (0) 2023.01.18
DAO jdbc  (0) 2023.01.18
IntellijでTomcat8.5を連携するときに不具合発生  (0) 2023.01.01
tomcat 8.0.x 설치  (0) 2022.12.31
openjdk 1.8.X 설치  (0) 2022.12.31
Posted by 다만사
2023. 1. 1. 18:47

こんなことができる理由がわらなないですね。

[JAVA 웹 개발환경] IntelliJ + Tomcat 연동 방법 (tistory.com)

このブログみてそのままやってるんだけど、

pom.xml です。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sora</groupId>
    <artifactId>WebAppTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>WebAppTest</name>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
        <junit.version>5.8.2</junit.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.3.2</version>
            </plugin>
        </plugins>
    </build>
</project>

エラーがでてるけど、よくわからないですね。

それで、Apache Tomcat 8.0 톰캣 설치방법 및 서버연결 (tistory.com) をみて、C:\java-se-8u42-ri\jre\lib\extにtomcatから、el-api.jar, jsp-api.jar, servlet-api.jarをコピして入れたけど、できないですね。

今原因を探してますね。

 

===============================================================================

 

原因はintellij Interprise Java 設定がtomcatの9バージョン以降を支援しるみたいです。だから、mavenで

エラーが出て、servletがコンパイルできない状態になったみたいです。(確実ではないです。)

そして、tomcatのライブラリを直接に入れてやってみたら、解決ができました。

'JAVA' 카테고리의 다른 글

DAO JDBC #2  (0) 2023.01.18
DAO jdbc  (0) 2023.01.18
Servletでいまの時間を表示する  (0) 2023.01.01
tomcat 8.0.x 설치  (0) 2022.12.31
openjdk 1.8.X 설치  (0) 2022.12.31
Posted by 다만사
2022. 12. 31. 17:23

톰캣 8.0을 설치하려고 했지만, 여러가지로 개선된 8.5를 설치했다.

이유: Apache Tomcat 7,8,9 어떻게 다를까? 톰캣 버전별 특징 (tistory.com) 

 

Apache Tomcat 7,8,9 어떻게 다를까? 톰캣 버전별 특징

Apache Tomcat은 자바의 서블릿과 JSP 기술의 오픈소스 소프트웨어입니다. 다음은 아파치 홈페이지에서 제공하고 있는 버전별 사양들입니다. 서블릿 스펙JSP 사양EL SpecWebSocket 사양재 스픽 사양Apache T

isabeller.tistory.com

다운로드 

Apache Tomcat® - Apache Tomcat 8 Software Downloads

 

Apache Tomcat® - Apache Tomcat 8 Software Downloads

Welcome to the Apache Tomcat® 8.x software download page. This page provides download links for obtaining the latest versions of Tomcat 8.x software, as well as links to the archives of older releases. Unsure which version you need? Specification versions

tomcat.apache.org

윈도우 서비스 인스톨러 판을 다운받아 설치했다. 

다른 블로그에서도 이렇게 나오는데, 아마도 윈도우에서 서버를 돌릴 때 편해서 인것 같다.

 

설치중간에 Full로 설치하고, 포트는 오라클 11G XE 때문에 8090으로 변경했다.

 

그리고 윈도우 + R ==> services.msc 서비스 들어가서 Apache Tomcat 8을 정지하고 시작 설정을 수동으로 했다.

이렇게 해야 이클립스나 인텔리제이에서 돌릴 수 있기 때문이다.

'JAVA' 카테고리의 다른 글

DAO JDBC #2  (0) 2023.01.18
DAO jdbc  (0) 2023.01.18
Servletでいまの時間を表示する  (0) 2023.01.01
IntellijでTomcat8.5を連携するときに不具合発生  (0) 2023.01.01
openjdk 1.8.X 설치  (0) 2022.12.31
Posted by 다만사
2022. 12. 31. 13:18

자바 공부를 하기 위해 OpenJDK 1.8을 설치해보자

 

다운로드 경로는 https://openjdk.org 이다.

 

현재 최신 버전은 19이지만, 웹호스팅 업체에서는 아직 1.8로 되어 있어서,

 

개인 홈페이지(블로그) 개설을 위해 1.8을 설치해 본다.

 

zip파일로 되어 있는 파일을 C드라이브에 압축 해제한다.

 

C드라이브에 복사한 화면

 

이후 환경변수에 등록한다.

1. 자바홈 설정

 

자바 홈 설정 화면

2. 패스 설정

패스 설정 화면

다른 jdk가 설정되어 있다면 삭제하든지 밑으로 내린다...

 

설치 확인 화면

이상 설치 완료!

'JAVA' 카테고리의 다른 글

DAO JDBC #2  (0) 2023.01.18
DAO jdbc  (0) 2023.01.18
Servletでいまの時間を表示する  (0) 2023.01.01
IntellijでTomcat8.5を連携するときに不具合発生  (0) 2023.01.01
tomcat 8.0.x 설치  (0) 2022.12.31
Posted by 다만사