Spring MVC - 값 전달

Programming/Java 2016.02.11 12:25 Posted by 파란크리스마스

출처 : 스프링3(Spring3)MVC 연동 (3) - 서버값 웹페이지로 전송하기 :: 야근싫어하는 개발자

파라미터 전달 (클라이언트 -> 서버)

java 소스

	@RequestMapping(value = "/sum_result1.iot", method = RequestMethod.GET)
	public String sum_result1(
			@RequestParam("param1") int param1,
			@RequestParam("param2") int param2,
			ModelMap modelMap
			)

Get 파라미터 전달

http://localhost:7070/IotWebServer/sum_result1.iot?param1=2&param2=3

서버값 클라이언트에 전달 (서버 -> 클라이언트)

java 소스 - TestController.java

package com.iot.ui.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class TestController {

	@RequestMapping(value = "/sum_result1.iot", method = RequestMethod.GET)
	public String sum_result1(
			@RequestParam("param1") int param1,
			@RequestParam("param2") int param2,
			ModelMap modelMap
			)
	{
		// 결과값
		int sum_value = param1 + param2;
		
		// Model에 값 설정
		modelMap.addAttribute("param1", param1);
		modelMap.addAttribute("param2", param2);
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_result1";
	}
}

jsp 소스 - sum_result1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
 
스프링 테스트<br/><br/>
 
${param1} 더하기 ${param2} (은/는) ${sum_value} 입니다.
 
</body>
</html>

결과

@ResponseBody 어노테이션

출처 : @ResponseBody 이해하기

@ResponseBody 로 어노테이션이 되어 있다면 메소드에서 리턴되는 값은 View 를 통해서 출력되지 않고 HTTP Response Body 에 직접 쓰여지게 됩니다.

java 소스

	@ResponseBody
	@RequestMapping(value="/sum_result_body.iot", method = RequestMethod.GET)
	public String sum_result_body(
			@RequestParam("param1") int param1, 
			@RequestParam("param2") int param2
			) throws Exception 
	{
		return param1 + " + " + param2 + " = " + (param1 + param2);
	}

결과

@RequestParam 어노테이션

출처 : [Spring 3 - @MVC] @Controller #2 - 파라미터와 리턴 타입의 종류

옵션

  • value : 파라미터명
  • required : 필수 여부
  • defaultValue : required가 false인 경우 값이 없는 경우 기본값

java 소스

	@RequestMapping(value = "/sum_result2.iot", method = RequestMethod.GET)
	public String sum_result2(
			@RequestParam("param1") int param1,
			@RequestParam(value="param2", required=false, defaultValue="0") int param2,
			ModelMap modelMap
			)
	{
		// 결과값
		int sum_value = param1 + param2;
		
		// Model에 값 설정
		modelMap.addAttribute("param1", param1);
		modelMap.addAttribute("param2", param2);
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_result1";
	}

결과

domain 객체 클라이언트에 전달 (서버 -> 클라이언트)

출처 : 뜬금없는 도메인 오브젝트의 발전사

java 소스 도메인 객체 - SumValueDomain.java

package com.iot.domain;

public class SumValueDomain {
	
	private int value1;
	private int value2;
}

get, set 메소드 생성

메소드 추가

	public int getSumValue() {
		return this.value1 + this.value2;
	}

java 소스 도메인 객체 최종소스 - SumValueDomain.java

package com.iot.domain;

public class SumValueDomain {
	
	private int value1;
	private int value2;
	
	public int getValue1() {
		return value1;
	}
	
	public void setValue1(int value1) {
		this.value1 = value1;
	}
	
	public int getValue2() {
		return value2;
	}
	
	public void setValue2(int value2) {
		this.value2 = value2;
	}
	
	public int getSumValue() {
		return this.value1 + this.value2;
	}
}

java 소스

	@RequestMapping(value = "/sum_result3.iot", method = RequestMethod.GET)
	public String sum_result3(
			@RequestParam("param1") int param1,
			@RequestParam(value="param2", required=false, defaultValue="0") int param2,
			ModelMap modelMap
			) 
	{
		// 도메일 객체 생성
		SumValueDomain sum_value = new SumValueDomain();
		
		// 값 설정
		sum_value.setValue1(param1);
		sum_value.setValue2(param2);
		
		// Model에 도메일 객체 전달
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_result3";
	}

jsp 소스 - sum_result3.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>

스프링 테스트<br/><br/>

${sum_value.value1} 더하기 ${sum_value.value2} (은/는) ${sum_value.getSumValue()} 입니다.

</body>
</html>

결과

domain 객체 서버에 전달 (클라이언트 -> 서버)

domain 객체를 spring 프레임워크에서 제공되는 form 테그 라이브러리를 사용해서 jsp에 전달했다가 다시 form 테그를 이용해서 서버의 controller에 전달하는 과정

java 소스 - Form jsp 호출

	@RequestMapping(value = "/sum_form.iot", method = RequestMethod.GET)
	public String sum_form(ModelMap modelMap) {
		// 도메일 객체 생성
		SumValueDomain sum_value = new SumValueDomain();
		
		// Model에 도메일 객체 전달
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_form";
	}

jsp 소스 - sum_form.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<head>
</head>
<body>

<form:form modelAttribute="sum_value" action="sum_result4.iot" method="POST">
	<p>
		값1<br/>
		<form:input path="value1"/>
	</p>
	<p>
		값2<br/>
		<form:input path="value2"/>
	</p>
	<p>
		<input type="submit" value="Submit">
	</p>
</form:form>

</body>
</html>

결과 - Form jsp

java 소스 - Form 에서 submit 호출 받는 메소드

	@RequestMapping(value = "/sum_result4.iot", method = RequestMethod.POST)
	public String sum_result4(SumValueDomain domain, ModelMap modelMap) 
	{
		int sum_value = domain.getValue1() + domain.getValue2();
		
		modelMap.addAttribute("param1", domain.getValue1());
		modelMap.addAttribute("param2", domain.getValue2());
		modelMap.addAttribute("sum_value", sum_value);
		
		// 전달 할 jap 페이지
		return "sum_result1";
	}

결과

Spring - 환경 설정

Programming/Java 2016.02.06 02:54 Posted by 파란크리스마스

출처 : Web.xml의 개요, 기능, 활용
web.xml Listener, Filter의 활용
톰캣 web.xml 설명
[Spring] web.xml 기본 설정

파일 위치

%PROJECT_HOME%\WEB-INF\web.xml

기본 web.xml 파일

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="bluexmas" version="3.0">

	<display-name>IotWebServer</display-name>
	
	<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>com.bluexmas.ui</param-value>
	</context-param>	
	
	<session-config>
		<session-timeout>720</session-timeout>
	</session-config>

	<jsp-config>
		<jsp-property-group>
			<url-pattern>*.jsp</url-pattern>
			<page-encoding>UTF-8</page-encoding>
		</jsp-property-group>
		<jsp-property-group>
			<url-pattern>/servlet/*</url-pattern>
			<page-encoding>UTF-8</page-encoding>
		</jsp-property-group>
	</jsp-config>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
</web-app>

서블릿 추가

서블릿 파일

package com.iot.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 출처 : http://dkatlf900.tistory.com/68
// tomcat 7.0부터 지원되는 xml 매핑을 자동 매핑
//@WebServlet("/test")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException 
	{
		// request 안의 모든 parameter 확인하기
		// 출처 : http://tmdjcollabo.tistory.com/entry/java-request-%EC%95%88%EC%9D%98-%EB%AA%A8%EB%93%A0-parameter-%ED%99%95%EC%9D%B8%ED%95%98%EA%B8%B0
		Enumeration<String> params = request.getParameterNames();
		System.out.println("----------------------------");
		while (params.hasMoreElements()){
			String name = (String) params.nextElement();
			System.out.println(name + " : " + request.getParameter(name));
		}
		System.out.println("----------------------------");
		
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("Iot 서버 입니다.");
	}
}

web-xml 추가

	<servlet>
		<servlet-name>test</servlet-name>
		<servlet-class>com.iot.servlet.TestServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>test</servlet-name>
		<url-pattern>/test</url-pattern>
	</servlet-mapping>

Spring MVC DispatherServlet 설정

출처 : @MVC와 DispatcherServlet에 대해서

디렉토리 구조

web-xml 추가

	<servlet>
		<servlet-name>iot</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>iot</servlet-name>
		<url-pattern>*.iot</url-pattern>
	</servlet-mapping>

iot-servlet.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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                           http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                           http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-2.5.xsd
                           http://www.springframework.org/schema/jee       http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
                           http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                           http://www.springframework.org/schema/security  http://www.springframework.org/schema/security/spring-security-2.0.xsd">

	<bean id="testController" class="com.iot.ui.controller.TestController"/>
	
	<!-- ========================= JSP View Resolver ========================= -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>		
</beans>

TestController.java

package com.iot.ui.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class TestController {

	@RequestMapping(value = "/test.iot", method = RequestMethod.GET)
	public String test(ModelMap modelMap) {
		return "testjsp";
	}
}

testjsp.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>

스프링 테스트

</body>
</html>


Java objects to XML using JAXB (Servlet)

Programming/Java 2014.12.04 10:41 Posted by 파란크리스마스

출처 : JAXB(위키백과)
@XMLAccessorType, @XMLRootElement
JAXB 2.0 Annotation 정리
How to customise an XML export using JAXB
Creating a Generic List Wrapper in JAXB

JAXB(Java Architecture for XML Binding)는 자바 클래스를 XML로 표현하는 자바 API이다. JAXB는 주로 2가지 기능이 있다. 자바 객체를 XML로 직렬화하는 것이고 반대로 XML에서 자바 객체로 역직렬화하는 것이다. 즉, JAXB는 메모리의 데이터를 XML 형식으로 변환하여 저장할 수 있고, 이 과정을 위해 프로그램의 각 클래스에서 XML을 읽고 저장하는 일을 구현해야 한다.

JAXB 2.0 Annotation 정리

@XmlRootElement 속성

  • name : xml root element 명 지정
  • namespace: namespace 지정

@XmlAccessorType의 설정

@XmlAccessorType(XmlAccessType.PROPERTY)

  • 모든 getter/setter 쌍을 JAXB 직렬화/역직렬화 대상으로 함
  • JAXB 직력화/역직력화에서 제외하고자 할 경우 getter 혹은 setter에 @XmlTransient를 사용
  • @XmlTransient는 getter/setter 상단에 설정
    • 멤버변수 상단에 설정시 적용 않됨
  • getter/setter가 존재하지 않는 public 멤버 변수를 JAXB 직력화/역직력화에서 추가하고자 할 경우 JAXB 어노테이션 사용
    • @XmlElement
    • @XmlAttribute

Employee

package com.test;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "Emp")
@XmlType(propOrder = {"name", "age", "role", "gender"})
public class Employee {

	private int id;

	private String gender;

	private int age;
	private String name;
	private String role;

	private String password;

	@XmlTransient
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@XmlAttribute
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

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

	@XmlElement(name = "gen")
	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	@Override
	public String toString() {
		return "ID = " + id + " NAME=" + name + " AGE=" + age + " GENDER="
				+ gender + " ROLE=" + role + " PASSWORD=" + password;
	}

}

JAXBExample

package com.test;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JAXBExample {

	private static final String FILE_NAME = "jaxb-emp.xml";

	public static void main(String[] args) {
		Employee emp = new Employee();
		emp.setId(1);
		emp.setAge(25);
		emp.setName("Pankaj");
		emp.setGender("Male");
		emp.setRole("Developer");
		emp.setPassword("sensitive");

		jaxbObjectToXML(emp);

		Employee empFromFile = jaxbXMLToObject();
		System.out.println(empFromFile.toString());
	}

	private static Employee jaxbXMLToObject() {
		try {
			JAXBContext context = JAXBContext.newInstance(Employee.class);
			Unmarshaller un = context.createUnmarshaller();
			Employee emp = (Employee) un.unmarshal(new File(FILE_NAME));
			return emp;
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static void jaxbObjectToXML(Employee emp) {

		try {
			JAXBContext context = JAXBContext.newInstance(Employee.class);
			Marshaller m = context.createMarshaller();
			// for pretty-print XML in JAXB
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

			// Write to System.out for debugging
			// m.marshal(emp, System.out);

			// Write to File
			m.marshal(emp, new File(FILE_NAME));
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

}

결과 파일 : jaxb-emp.xml

JAXBExample에서 Employee 클래스에 데이터를 담고, 그것을 xml로 출력한 결과입니다.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Emp id="1">
    <name>Pankaj</name>
    <age>25</age>
    <role>Developer</role>
    <gen>Male</gen>
</Emp>

Wrapper

package com.test;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAnyElement;

public class Wrapper<T> {
	private List<T> items;

	public Wrapper() {
		items = new ArrayList<T>();
	}

	public Wrapper(List<T> items) {
		this.items = items;
	}

	@XmlAnyElement(lax = true)
	public List<T> getItems() {
		return items;
	}
}

XMLServlet

package com.test;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

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 javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;

@WebServlet(urlPatterns = "/xml")
public class XMLServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/xml;charset=UTF-8");
		OutputStream out = resp.getOutputStream();

		try {
			JAXBContext jc = JAXBContext.newInstance(Wrapper.class, Employee.class);
			
			// Marshal
			Marshaller marshaller;
			
			marshaller = jc.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshal(marshaller, getEmpDatas(), "emps", out);

		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		out.close();
	}

	/** * Unmarshal XML to Wrapper and return List value. */
	private static <T> List<T> unmarshal(Unmarshaller unmarshaller, Class<T> clazz, String xmlLocation) throws JAXBException {
		StreamSource xml = new StreamSource(xmlLocation);
		Wrapper<T> wrapper = (Wrapper<T>) unmarshaller.unmarshal(xml, Wrapper.class).getValue();
		return wrapper.getItems();
	}

	/**
	 * * Wrap List in Wrapper, then leverage JAXBElement to supply root element *
	 * information.
	 */
	private static void marshal(Marshaller marshaller, List<?> list, String name, OutputStream os) throws JAXBException {
		QName qName = new QName(name);
		Wrapper wrapper = new Wrapper(list);
		JAXBElement<Wrapper> jaxbElement = new JAXBElement<Wrapper>(qName, Wrapper.class, wrapper);
		marshaller.marshal(jaxbElement, os);
	}

	private List<Employee> getEmpDatas() {

		List<Employee> datas = new ArrayList<Employee>();

		Employee emp = new Employee();
		emp.setId(1);
		emp.setAge(25);
		emp.setName("Pankaj");
		emp.setGender("Male");
		emp.setRole("Developer");
		emp.setPassword("sensitive");

		datas.add(emp);

		emp = new Employee();
		emp.setId(11);
		emp.setAge(125);
		emp.setName("1Pankaj");
		emp.setGender("1Male");
		emp.setRole("1Developer");
		emp.setPassword("1sensitive");

		datas.add(emp);

		return datas;
	}
}

실행결과

소스파일

ObjToXML.zip

Spring Security

Programming/Java 2014.10.03 08:03 Posted by 파란크리스마스

출처 : Spring Security login/logout 관련 글
Spring Security Logout Example
Spring Security 3 - 맛보기와 기본 설정의 이해


web.xml

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/baroCOST-datasource.xml
			/WEB-INF/baroCOST-security.xml
		</param-value>
	</context-param>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>	

baroCOST-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.2.xsd">

	<security:http auto-config="true">
		<security:intercept-url pattern="/favicon.ico" access="ROLE_ANONYMOUS" />
		<security:intercept-url pattern="/**" access="ROLE_USER" />
	</security:http>

	<security:authentication-manager>
		<security:authentication-provider>
			<security:user-service>
				<security:user name="guest" password="guest" authorities="ROLE_USER" />
			</security:user-service>
		</security:authentication-provider>
	</security:authentication-manager>
</beans>

Spring Security 에서 기본 제공해주는 로그인 페이지(spring_security_login)

<html><head><title>Login Page</title></head><body onload='document.f.j_username.focus();'>
<h3>Login with Username and Password</h3>
<form name='f' action='/baroCOST/j_spring_security_check' method='POST'>
 <table>
    <tr><td>User:</td><td><input type='text' name='j_username' value=''></td></tr>
    <tr><td>Password:</td><td><input type='password' name='j_password'/></td></tr>
    <tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
  </table>
</form></body></html>

DB 사용

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.2.xsd">

	<security:http auto-config="true">
		<security:intercept-url pattern="/favicon.ico" access="ROLE_ANONYMOUS" />
		<security:intercept-url pattern="/**" access="ROLE_USER" />
		<security:intercept-url pattern="/" access="ROLE_USER" />
	</security:http>

	<security:authentication-manager>
		<security:authentication-provider>
			<!-- 
            <security:user-service>
                <security:user name="guest" password="guest" authorities="ROLE_USER" />
            </security:user-service>
            -->		
			<security:jdbc-user-service data-source-ref="dataSource"
				users-by-username-query="select user_id username, password, 1 as enabled from user_info where user_id = ?"
				authorities-by-username-query="select user_id username, 'ROLE_USER' authority from user_info where user_id = ?"
			/>
		</security:authentication-provider>
	</security:authentication-manager>
</beans>

로그인 페이지 변경

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.2.xsd">
           
	<security:http pattern="/common/css/**" security="none" />
	<security:http pattern="/common/image/**" security="none" />
	<security:http pattern="/common/js/**" security="none" />           

	<security:http auto-config="true">
		<security:intercept-url pattern="/favicon.ico" access="ROLE_ANONYMOUS" />
		<security:intercept-url pattern="/login.cmx" access="ROLE_ANONYMOUS" />
		<security:intercept-url pattern="/**" access="ROLE_USER" />
		<security:intercept-url pattern="/" access="ROLE_USER" />
		
		<security:form-login login-page="/login.cmx" default-target-url="/index.html"
			authentication-failure-url="/loginfailed" />
		<security:logout logout-success-url="/logout" />		
	</security:http>

	<security:authentication-manager>
		<security:authentication-provider>
			<!-- 
            <security:user-service>
                <security:user name="guest" password="guest" authorities="ROLE_USER" />
            </security:user-service>
            -->		
			<security:jdbc-user-service data-source-ref="dataSource"
				users-by-username-query="select user_id username, password, 1 as enabled from user_info where user_id = ?"
				authorities-by-username-query="select user_id username, 'ROLE_USER' authority from user_info where user_id = ?"
			/>
		</security:authentication-provider>
	</security:authentication-manager>
</beans>


Camel Header 설정

Programming/Java 2014.09.25 10:19 Posted by 파란크리스마스

참고 : http://camel.apache.org/jms.html

RouteBuilder

	from("jms:queue:test1?maxConcurrentConsumers=1&maxMessagesPerTask=1&autoStartup=true&preserveMessageQos=true")
	.bean(com.bluexmas.Test1Queue.class, "doTest")
	.to("jms:queue:test2");
	
	from("jms:queue:test2?maxConcurrentConsumers=1&maxMessagesPerTask=1&autoStartup=true&preserveMessageQos=true")
	.bean(com.bluexmas.Test2Queue.class, "doTest")
	.to("stream:out");

Header1Object

package com.bluexmas;

import java.io.Serializable;

public class Header1Object implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	int age;
	String name;
	
	public Header1Object(int age, String name) {
		super();
		this.age = age;
		this.name = name;
	}

	@Override
	public String toString() {
		return "Header1Object [age=" + age + ", name=" + name + "]";
	}
}

Test1Queue

package com.bluexmas;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.camel.Exchange;
import org.apache.camel.Message;

import com.uni.fep.bean.service.MQSenderService;
import com.uni.fep.bean.util.BeanUtils;
import com.uni.fep.bean.util.EnvironmentInit;

public class Test1Queue {
	
	public void doTest(Exchange exchange) {
		System.out.println("-- Test1Queue.doTest ----------------------------");
		
		Message in = exchange.getIn();
		
		System.out.println("body = " + in.getBody());
		System.out.println("header1 = " + in.getHeader("header1"));
		System.out.println("header2 = " + in.getHeader("header2"));
		
		in.setHeader("header1", "value1-1");
		in.setHeader("header2", "value2");
		
		List<String> listValue = new ArrayList<String>();
		listValue.add("list1");
		listValue.add("list2");
		in.setHeader("header3", listValue);
		System.out.println("header3 = " + in.getHeader("header3"));
		
		in.setHeader("header4", new Header1Object(10, "bluexmas"));
		System.out.println("header4 = " + in.getHeader("header4"));
	}
	
	public static void main(String[] args) throws Exception {
		EnvironmentInit.init();
		
		MQSenderService service = (MQSenderService)BeanUtils.getBean("MQSenderService");
		
		String message = "Hello Camel";
		
		Map<String, Object>map=new HashMap<String,Object>();
		map.put("header1", "value1");
		
		service.doSend("test1", map, message);
		
		Thread.sleep(5000);
		
		System.exit(0);
	}

}

Test2Queue

package com.bluexmas;

import org.apache.camel.Exchange;
import org.apache.camel.Message;

public class Test2Queue {

	public void doTest(Exchange exchange) {
		System.out.println("-- Test2Queue.doTest ----------------------------");
		
		Message in = exchange.getIn();
		
		System.out.println("body = " + in.getBody());
		System.out.println("header1 = " + in.getHeader("header1"));
		System.out.println("header2 = " + in.getHeader("header2"));
		System.out.println("header3 = " + in.getHeader("header3"));
		System.out.println("header4 = " + in.getHeader("header4"));
	}
	
}

출력결과

-- Test1Queue.doTest ----------------------------
body = Hello Camel
header1 = value1
header2 = null
header3 = [list1, list2]
header4 = Header1Object [age=10, name=bluexmas]
-- Test2Queue.doTest ----------------------------
body = Hello Camel
header1 = value1-1
header2 = value2
header3 = null
header4 = null
Hello Camel

설명

Camel에서 기본적으로 Header의 내용은 Queue 넘어 갈때 초기화 되는데, 
초기화 하지 않고, 그대로 데이터를 가지고 다니려면 preserveMessageQos=true 해주면 된다.

출력결과를 보시면 알 수 있듯이 기본 자료형외에 객체는 전달 할 수가 없는 것으로 판단된다.

header1 : 초기에 전달된 Header의 값으로 그 값을 변경했을때 변경된 값이 전달되는 것을 확인
header2 : 초기에 전달되지 않았으나 추가로 Header에 추가된 값으로 Queue 이동 후 값이 존재하는 것을 확인
Header3 : ArreyList에 기본형 데이터(String) 추가해서 Header에 추가해서 전달했으나 List 전달되지 않는 것으로 확인
Header4 : 사용자가 임으로 만들 객체를 Header에 추가 했으나 Queue 이동 후 값이 전달되지 않는 것으로 확인

Spring Security 적용하기

Programming/Java 2014.01.28 15:33 Posted by 파란크리스마스

출처 : Spring Security 3 - 맛보기와 기본 설정의 이해
스프링 시큐리티 적용하기 (properties 인증 방법)
Spring Security를 이용한 인증 처리
AJAX Login with Spring Security

WEB-INF\web.xml

	<!-- 스프링 시큐리티 적용하기 -->
	<context-param&g
		<param-name>contextConfigLocation</param-name>
		<param-value>WEB-INF/spring-security.xml</param-value>
 	</context-param>	
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<listener>
  		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 	</listener>

WEB-INF\spring-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.2.xsd">

	<security:http pattern="/common/css/**" security="none" />
	<security:http pattern="/common/img/**" security="none" />
	<security:http pattern="/common/js/**" security="none" />

	<security:http auto-config="true">
		<security:intercept-url pattern="/admin/**"	access="ROLE_ADMIN" />
		<security:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />		

		<!-- 
		<security:form-login login-page="/login.do"
			login-processing-url="/j_spring_security_check.do"
			default-target-url="/loginSuccess.do" authentication-failure-url="/loginFailed.do" />

		<security:logout logout-url="/j_spring_security_logout.do"
			logout-success-url="/logout.do" invalidate-session="true" />
 		-->			
	</security:http>


	<security:authentication-manager>
		<security:authentication-provider>
            <security:user-service>
                <security:user name="admin" password="admin!@" authorities="ROLE_ADMIN" />
            </security:user-service>		
			<!-- 
			<security:user-service properties="/WEB-INF/users-config.xml" />
			 -->
		</security:authentication-provider>
	</security:authentication-manager>

</beans>

WEB-INF\users-config.xml (옵션)

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
        <comment>users</comment>
        <entry key="admin">1111,ROLE_ADMIN,ROLE_USER</entry>
        <entry key="user">2222,ROLE_USER</entry>
</properties>

 

Quartz - 배치 실행

Programming/Java 2014.01.28 14:45 Posted by 파란크리스마스

출처 : Chapter 19. Quartz 혹은 Timer 를 사용한 스케쥴링     

DongHoReportBatch.java

package com.blueX.batch;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class DongHoReportBatch extends QuartzJobBean {

	@Override
	protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		Date dt = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd, hh:mm:ss a"); 
		System.out.println(sdf.format(dt).toString()); 
	}
	
	public static void main(String[] args) throws Exception {
		String[] configLocation = new String[] { "file:WebContent/WEB-INF/blueX-servlet.xml" };
		ApplicationContext context = new ClassPathXmlApplicationContext(configLocation);
	}

}

blueX-servlet.xml

	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean" autowire="no">
		<property name="triggers">
       		<list>
	         	<ref bean="dongHoReportTrigger" />
			</list>
     	</property>
     	<property name="quartzProperties">
		    <props>
		    	<prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>
		        <prop key="org.quartz.threadPool.threadCount">5</prop>
		        <prop key="org.quartz.threadPool.threadPriority">4</prop>
		        <prop key="org.quartz.jobStore.class">org.quartz.simpl.RAMJobStore</prop>
		        <prop key="org.quartz.jobStore.misfireThreshold">60000</prop>
			</props>
		</property>
	</bean>
	
	<bean id="dongHoReportTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
		<property name="jobDetail" ref="dongHoReportJob" />
		<property name="startDelay" value="60000"/> <!-- 서버 시작후 1분후 첫 실행 -->
		<property name="repeatInterval" value="300000"/> <!-- 첫 실행 후 5분 마다 실행 -->
	</bean> 
	
	<bean id="dongHoReportJob" class="org.springframework.scheduling.quartz.JobDetailBean">
		<property name="jobClass" value="com.blueX.batch.DongHoReportBatch" />
	</bean>

Java - File Hash 값 추출

Programming/Java 2013.12.11 09:56 Posted by 파란크리스마스

DigestUtils

package bluexmas.utils;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DigestUtils {

	public static String extractStringHashSHA256(String str){
		String SHA = ""; 
		try{
			MessageDigest sh = MessageDigest.getInstance("SHA-256"); 
			sh.update(str.getBytes()); 
			byte byteData[] = sh.digest();
			StringBuffer sb = new StringBuffer(); 
			for(int i = 0 ; i < byteData.length ; i++){
				sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));
			}
			SHA = sb.toString();
			
		}catch(NoSuchAlgorithmException e){
			e.printStackTrace(); 
			SHA = null; 
		}
		return SHA;
	}
	
	public static String extractFileHashSHA256(String filename) throws Exception {
		
		String SHA = ""; 
		int buff = 16384;
		try {
			RandomAccessFile file = new RandomAccessFile(filename, "r");

			MessageDigest hashSum = MessageDigest.getInstance("SHA-256");

			byte[] buffer = new byte[buff];
			byte[] partialHash = null;

			long read = 0;

			// calculate the hash of the hole file for the test
			long offset = file.length();
			int unitsize;
			while (read < offset) {
				unitsize = (int) (((offset - read) >= buff) ? buff : (offset - read));
				file.read(buffer, 0, unitsize);

				hashSum.update(buffer, 0, unitsize);

				read += unitsize;
			}

			file.close();
			partialHash = new byte[hashSum.getDigestLength()];
			partialHash = hashSum.digest();
			
			StringBuffer sb = new StringBuffer(); 
			for(int i = 0 ; i < partialHash.length ; i++){
				sb.append(Integer.toString((partialHash[i]&0xff) + 0x100, 16).substring(1));
			}
			SHA = sb.toString();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		return SHA;
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(extractStringHashSHA256("1"));
		System.out.println(extractFileHashSHA256("a.pdf"));
	}	
}


Spring tiles

Programming/Java 2013.10.15 13:12 Posted by 파란크리스마스

aaplus-pc-tiles.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context.xsd">
	

	<bean id="templateResolver"
		class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
		<property name="prefix" value="/WEB-INF/view/" />
		<property name="suffix" value=".html" />
		<property name="templateMode" value="HTML5" />
		<property name="cacheable" value="true" />
	</bean>
	<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
		<property name="templateResolver" ref="templateResolver" />
	</bean>
	<bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
		<property name="templateEngine" ref="templateEngine" />
		<property name="order" value="1" />
		<property name="viewNames" value="thymeleaf/*" />
	</bean>

	<!-- Resolves view names to Tiles definitions -->
	<beans profile="tiles3">
		<bean id="tilesViewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver">
			<property name="order" value="0"/>
		</bean>
	
		<!-- Configures Tiles 3-->
		<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
			<property name="definitions">
				<list>
					<value>/WEB-INF/view/jsp/03-tiles/tiles.xml</value>
					<value>/WEB-INF/view/jsp/admin/tiles.xml</value>
				</list>
			</property>
		</bean>
	</beans>
	
	<beans profile="tiles2">
		<bean id="tilesViewResolver" class="org.springframework.web.servlet.view.tiles2.TilesViewResolver">
			<property name="order" value="0"/>
		</bean>
	
		<!-- Configures Tiles 2 -->
		<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
			<property name="definitions">
				<list>
					<value>/WEB-INF/view/jsp/03-tiles/tiles.xml</value>
					<value>/WEB-INF/view/jsp/admin/tiles.xml</value>
				</list>
			</property>
		</bean>
	</beans>

</beans>

/WEB-INF/view/jsp/03-tiles/tiles.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC 
	"-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN" 
	"http://tiles.apache.org/dtds/tiles-config_3_0.dtd">	

<tiles-definitions>

	<definition name="03-tiles/*" template="/WEB-INF/view/jsp/03-tiles/layout.jsp">
		<put-attribute name="main" value="/WEB-INF/view/jsp/03-tiles/{1}.jsp" />
	</definition>
	
</tiles-definitions>

/WEB-INF/view/jsp/03-tiles/layout.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles" %>

<html>
<head>
	<meta charset="utf-8"/>
	<spring:url value="/common/style" var="styleUrl" />
	<link href="${styleUrl}/app.css" rel="stylesheet"/>
	<title><c:out value="${title}"/></title>
</head>

<body>
	<div class="container" style="padding-top: 50px;">
		<jsp:include page="/WEB-INF/view/jsp/menu.jsp"/>	
		<tiles:insertAttribute name="main" />
		<jsp:include page="/WEB-INF/view/jsp/footer.jsp"/>	
	</div>
</body>
</html>

Oracle Procedure - JDBC 배열(ARRAY 타입) 호출

Programming/Java 2013.04.11 15:24 Posted by 파란크리스마스

출처 : Passing Arrays between Java and Oracle Procedures
how to call procedure with out parameter as table type from a java class
Oracle procedure 'out' 'table of varchar2' type parameter
Oracle stored procedure using array as parameter for table insert
Jdbc array binding: character set encoding
Oracle Database 11g Release 2 JDBC Drivers

주의사항

1. Spring을 사용하는 경우 OracleConnection을 가지고 오기 위해서 <property name="accessToUnderlyingConnectionAllowed" value="true"/>

2. 인코딩 문제로 varchar2의 경우 orai18n.jar를 추가 해야 됨

oracle 배열 타입 생성

CREATE OR REPLACE TYPE ARRAY_V AS TABLE OF VARCHAR2(512);

oracle procedure

CREATE OR REPLACE PACKAGE XXX.PKG_TEST AS

  PROCEDURE SP_TERMINAL_SELECT
  ( 
    IN_TERMINAL_MAC  IN  ARRAY_V,
    OUT_TERMINAL_IP  OUT ARRAY_V   
  );

END PKG_TEST;
/

CREATE OR REPLACE PACKAGE BODY XXX.PKG_TEST IS

  PROCEDURE SP_TERMINAL_SELECT
  ( 
    IN_TERMINAL_MAC  IN  ARRAY_V,
    OUT_TERMINAL_IP  OUT ARRAY_V   
  ) IS
  BEGIN
    -- need to initialize the collection or it will fail if it is used
    OUT_TERMINAL_IP := ARRAY_V();
  
    FOR i IN 1 .. IN_TERMINAL_MAC.COUNT LOOP
    
        OUT_TERMINAL_IP.extend(1);
        
        SELECT TERMINAL_IP INTO OUT_TERMINAL_IP(i) 
          FROM TERMINAL
         WHERE TERMINAL_MAC = IN_TERMINAL_MAC(i); 
        
    END LOOP;
  
  END SP_TERMINAL_SELECT;

END PKG_TEST;
/

java 소스

package test;

import java.sql.Connection;
import java.sql.SQLException;

import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OracleTypes;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;

import org.apache.commons.dbcp.DelegatingConnection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import test.util.ConnectionManager;

public class SelectTerminal {
	
	public static ApplicationContext context;
	
	public static void main(String[] args) throws Exception {
		
		System.out.println("test");
        String[] configLocation = new String[] { "file:WebContent/WEB-INF/test-servlet.xml" };
        context = new ClassPathXmlApplicationContext(configLocation);
		
		Connection conn = null;
		try {
			conn = ConnectionManager.getConnection();

			//
			Connection oraConn = ((DelegatingConnection)conn).getDelegate();
			if ((oraConn instanceof DelegatingConnection) && !(oraConn instanceof oracle.jdbc.OracleConnection)) {
				oraConn = ((DelegatingConnection)oraConn).getDelegate();
			}
			
			// Create descriptors for each Oracle collection type required
			// CREATE OR REPLACE ARRAY_V AS TABLE OF VARCHAR2(512); 
			ArrayDescriptor oracleVarchar2Collection = ArrayDescriptor.createDescriptor("ARRAY_V", oraConn);

	        // JAVA arrays to hold the data.
	        String[] terminal_mac_array    = { "08:xx:xx:xx:xx:xx", "00:xx:xx:xx:xx:xx" };
	        ARRAY ora_terminal_mac    = new ARRAY(oracleVarchar2Collection, oraConn, terminal_mac_array);
	
	        show_array_info(ora_terminal_mac);
	        
	        // Bind the input arrays.
			OracleCallableStatement stmt = 
	        	(OracleCallableStatement) oraConn.prepareCall("{ call PKG_TEST.SP_TERMINAL_SELECT(?,?) }");	        

	        stmt.setArray(1, ora_terminal_mac);
	        stmt.registerOutParameter(2, OracleTypes.ARRAY, "ARRAY_V");
	        stmt.execute();

	        //
	        ARRAY ora_terminal_ip = stmt.getARRAY(2);
	        if (ora_terminal_ip!=null) {
	        	String[] terminal_ip_array = (String[])ora_terminal_ip.getArray();
	        	for (int i=0; i<terminal_ip_array.length; i++) {
	        		System.out.println(i + " / terminal_ip = " + terminal_ip_array[i]);
	        	}
	        }	        

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn!=null) try { conn.close(); } catch (SQLException e) { }
		}        
	}
	
	private static void show_array_info(oracle.sql.ARRAY p_in) throws SQLException {

		System.out.println("Array is of type      " + p_in.getSQLTypeName());
		System.out.println("Array is of type code " + p_in.getBaseType());
		System.out.println("Array is of length    " + p_in.length());

		String[] values = (String[]) p_in.getArray();

		for (int i = 0; i < p_in.length(); i++)
			System.out.println("p_in[" + i + "] = " + values[i]);
	}

}

결과

Array is of type      XXX.ARRAY_V
Array is of type code 12
Array is of length    2
p_in[0] = 08:xx:xx:xx:xx:xx
p_in[1] = 00:xx:xx:xx:xx:xx
0 / terminal_ip = 192.168.0.2
1 / terminal_ip = 192.168.0.3

Java - Get방식 Http 호출

Programming/Java 2013.04.01 21:17 Posted by 파란크리스마스
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class HttpGetCall {

	public static void main(String[] args) throws Exception {
		URL url = new URL("http://naver.com");
		InputStream is = url.openStream();

		BufferedReader inFile = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while( (line = inFile.readLine()) != null ) {
            System.out.println(line);
        }
		is.close();
	}
}
TAG GET, HTTP, Java, URL

NT Service로 기동할때 톰캣메모리설정

Programming/Java 2013.03.05 14:52 Posted by 파란크리스마스

출처 : NT Service로 기동할때 톰캣메모리설정

HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\Tomcat7\Parameters

"JVM Option Number 4"="-Xms512m"
"JVM Option Number 5"="-Xmx1024m" 



 

티스토리 툴바