您的位置:首页 > 编程语言 > Java开发

一个简单的Java Web项目搭建流程

2017-04-11 09:51 846 查看

 

今天试图在服务器上搭建一个web服务器,顺便回顾了java web项目的入门,使用Servlet处理HTTP请求,并记录日志等操作。当很久没有做过web项目时,有些东西还是很容易忘记的。
 


Maven配置

使用maven进行整个项目的构建,使用intellij idea IDE,填写完groupId和artifactId之后,声明packaging元素为war包,在build中注意需要设置war-plugin的webResources:
 
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<webResources>
<resource>
<directory>web</directory>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>

 
 

 
其中的dependency项中除了要包含的依赖jar包外,有些编译期依赖的jar包也需要填写(scope=provided),比如javaee-api。
 


Servlet编写和配置

Java Web项目中使用Servlet来处理具体的http请求,请求url的处理是配置在webResources目录下的web.xml文件中的:
 
<servlet>
<servlet-name>monitor</servlet-name>
<servlet-class>具体的ServletClass</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>monitor</servlet-name>
<url-pattern>/monitor</url-pattern>
</servlet-mapping>

 
 
其中servlet-mapping中的/monitor就是对应的处理URL,也即http://主机名称:web服务器端口/web项目的Context/url-pattern。
 
在Servlet中通常继承javax.servlet.http.HttpServlet类,重写其中的doGet和doPost方法(分别处理GET和POST请求)。事实上,Servlet中包含HTTP的所有请求方式的相关方法(PUT, DELETE等)一般情况下,我们对于数据量稍微比较大的数据都使用POST方式提交HTTP请求(GET方式一般用于查询资源,会限制提交数据长度,GET请求的参数数据会显示在浏览器的地址栏URL中)。
 
通过HttpServletRequest.getParameter(parameterName)来获取请求中提交的参数数据,这里指的仅仅是Request范围的参数名。
 


Servlet的数据返回

如何返回Servlet中的数据,这需要我们使用参数中的HttpServletResponse的相关方法了,其中getWriter()方法提供了一个输出流,可以将html中的数据写入到这个输出流中,这样在浏览器就能以页面到形式查看到这个html页面。
 
Servlet可以以Java程序的方式对请求进行处理并返回,可以说,Servlet是Java代码中包含html页面,如果生成的html页面比较大,其中的getWriter().print()的代码会非常恐怖而且难以理解。JSP正是基于这个原因出现的,JSP使用的方式是html页面加入java代码(scriptlet),在html页面较大而java逻辑较少的情况下比较适用。
 
在Servlet中也可以根据处理逻辑来forword到对应的jsp页面,使用如下的方法:
getServletConfig().getServletContext().getRequestDispatcher(jsp的相对路径).forward(request,response);

 
 
我们知道HTTP返回的代码代表这不同的含义,比如
1xx-信息提示;
2xx-成功;
3xx-重定向;
4xx-客户端错误;
5xx-服务器错误;

 
 
我们可以手动在HttpServletResponse.setStatus()方法中指定返回的HTTP Code,给客户端对应的提示。
 
在Web项目处理逻辑中,经常需要处理本地资源,比如读取本地(Web项目中)的配置文件。这就需要使用ServletContext中的getResource系列方法, getResource和getResourceAsStream方法以“/”开头的字符串为参数,它指定上下文根路径的资源相对路径。文档的层级可能存在于服务器的文件系统,war文件,远程服务器或者在一些其它位置中,注意在使用完成后,需要将流关闭。
 


日志(log4j)配置

在进行任何项目开发都需要记录必要的日志,尤其是对应web项目的开发,你需要能够查询到对应的处理错误,这里使用了log4j来进行日志的处理。
 
日志的配置需要进行初始化,这个初始化的时机需要在web项目启动时做。这里就需要为log4j单独创建一个Servlet,用于初始化。在web.xml中建立对应的Servlet,并不需要声明servlet-mapping,因为它并不负责真正处理HTTP请求。
<servlet>
<servlet-name>log4j-init</servlet-name>
<servlet-class>com.xxx.monitor.servlet.Log4jInitServlet</servlet-class>
<init-param>
<param-name>log4j</param-name>
<param-value>WEB-INF/log4j.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

 
 
将其load-on-startup声明的顺序改成1,这样就能保证在其他Servlet初始化之前,Log4j已经初始化完毕。其中的init-param参数指定了log4j配置文件对应WebResources的位置,这在ServletConfig中可以通过getInitParameter来进行获取。
 
在Log4jInitServlet中,由于不需要处理HTTP的各种类型请求,只需要重写初始化方法init:
@Override
public void init(ServletConfig servletConfig) throws ServletException {
String prefix = servletConfig.getServletContext().getRealPath("/");
String filePath = String.format("%s/%s", prefix, servletConfig.getInitParameter("log4j"));
FileInputStream inputStream = null;
Properties properties = new Properties();
try {
inputStream = new FileInputStream(new File(filePath));
properties.load(inputStream);
String logFilePath = String.format("%s%s", prefix, properties.getProperty("log4j.appender.R.File"));
properties.setProperty("log4j.appender.R.File", logFilePath);

PropertyConfigurator.configure(properties);
} catch (IOException e) {
throw new ServletException("log4j module initialized failed!");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}

 
 
这里log4j.properties中的log4j.appender.R.File参数只是指定输出log文件的相对地址,这就需要我们使用servletConfig.getServletContext().getRealPath("/")将其拼接成运行时的绝对地址。
 


HTTP请求测试

在编写代码完后,我们都需要对其正确性进行测试。Java中提供了对于HTTP请求发送的相关API,在这个基础上,我们进行测试代码的编写:
 
URL postUrl = null;
try {
postUrl = new URL(url);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
HttpURLConnection connection = null;
DataOutputStream dataOutputStream = null;
BufferedReader reader = null;
try {
connection = (HttpURLConnection) postUrl.openConnection();
//Read from the connection
connection.setDoInput(true);
//http body is in the content
connection.setDoOutput(true);
//we use post method
connection.setRequestMethod("POST");
//post can't use caches
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);

connection.connect();
dataOutputStream = new DataOutputStream(connection.getOutputStream());
String content = "userName=clamaa&password=bbb&json=jsonstring";
dataOutputStream.writeBytes(content);
dataOutputStream.flush();
dataOutputStream.close();

reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));

System.out.println("====================");
System.out.println("read line started...");
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
result.append(line).append(System.getProperty("line.separator"));
}
System.out.println("====================");
return result.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}

 
 至此,一个基本的Java项目就已经编写完毕,由于整个项目使用maven来构建的,只要在项目目录下,执行maven clean install命令,将生成的target/下的war包部署到tomcat的webapp目录下即可。 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: