基于Java的web应用,打包为War,包含jsp文件,servlet、java类、web.xml配置文件、依赖jar包、静态web资源等。同其他任何Maven项目一样,Maven对Web项目的布局结构有一个通用约定。显式指定打包方式为war。
<project>
…
<groupId>com.company.mvnbook</groupId>
<artifactId>sample-war</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
…
</project>
其他不相关配置忽略了。
service的POM
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.j.mvnbook.account</groupId>
<artifactId>account-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>account-service</artifactId>
<name>Account Service</name>
<properties>
<greenmail.version>1.3.1b</greenmail.version>
</properties>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>account-email</artifactId>
<version>${project-version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>account-persist</artifactId>
<version>${project-version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>account-captcha</artifactId>
<version>${project-version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>com.icegreen</groupId>
<artifactId>greenmail</artifactId>
<version>${greenmail.version}</version>
</dependency>
</dependencies>
<build>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
</build>
</project>
service的主代码
AccoutService.java
package com.j.mvnbook.account.service;
public interface AccountService
{
String generateCaptchaKey() throws AccountServiceException;
byte[] generateCaptchaImage(String captchaKey) throws AccountServiceException;
void signUp(SignUpRequest signUpRequest) throws AccountServiceException;
void activate(String activationNumber) throws AccountServiceException;
void login(String id,String password) throws AccountServiceException;
}
AccoutServiceImpl.java
public class AccountServiceImpl implements AccountService
{
private AccountPersistService accountPersistService;
private AccountEmailService accountEmailService;
private AccountCaptchaService accountCaptchaService;
public AccountPersistService getAccountPersistService()
{
return accountPersistService;
}
public void setAccountPersistService(AccountPersistService accountPersistService)
{
this.accounPersistService=accountPersistService;
}
public AccountEmailService getAccountEmailService()
{
return accountEmailService;
}
public void setAccountEmailService(AccountEmailService accountEmailService)
{
this.accounEmailService=accountEmailService;
}
public AccountCaptchaService getAccountCaptchaService()
{
return accountCaptchaService;
}
public void setAccountCaptchaService(AccountCaptchaService accountCaptchaService)
{
this.accounCaptchaService=accountCaptchaService;
}
public byte[] generateCaptchaImage(String captchaKey) throws AccountServiceException
{
try{
return accountCaptchaService.generateCaptchaImage(captchaKey);
}catch(AccountCaptchaException e)
{
throw new AccountServiceException("Unable to generate Captcha Image.",e);
}
}
public String generateCaptchaKey() throws AccountServiceException
{
try{
return accountCaptchaService.generateCaptchaKey();
}catch(AccountCaptchaException e)
{
throw new AccountServiceException("Unable to generate Captcha key.",e)
}
}
private Map<String,String> activationMap=new HashMap<String,String>();
public void signUp(SignUpRequest signUpRequest) throws AccountServiceException
{
try{
if(!signUpRequest.getPassword().equals(signUpRequest.getConfirmpassword()))
{
throw new AccountServiceException("2 passwords do not match.");
}
if(!accountCaptchaService.validateCaptcha(signUpRequest.getCaptchaKey().signUpRequest.getCaptchaValue()))
{
throw new AccountServiceException("Incorrect Captcha.");
}
Account account=new Account();
account.setId(signUpRequest.getId());
account.setEmail(signUpRequest.getEmail());
account.setName(signUpRequest.getName());
account.setPassword(signUpRequest.getPassword());
account.setActivated(false);
accountPersistService.createAccount(account);
String activationId=RandomGenerator.getRandomString();
activationMap.put(activationId.account.getId());
String link=signUpRequest.getActivateServiceUrl(0.endsWith("/"?signUpRequest.getActivateServiceUrl())
+activationId:signUpRequest.getActivateServiceUrl()+"?key="+activationId;
accounEmailService.sendMail(account.getEmail(),"Please Activate Your Account",link);
}catch(AccountCaptchaException e){
throw new AccountServiceException("Unable to vaildate captcha.",e);
}catch(AccountCaptchaException e){
throw new AccountServiceException("Unable to vaildate captcha.",e);
}catch(AccountPersistException e){
throw new AccountServiceException("Unable to create account.",e);
}catch(AccountEmailException e){
throw new AccountServiceException("Unable to send activation mail.",e);
}
}
public void activate(String activationId) throws AccountServiceException{
String accountId=activationMap.get(activationId);
if(accountId==null)
{
throw new AccountServiceException("Invalid account activation ID");
}
try{
Account account =accountPersistService.readAccount(accountId);
account.setActivated(true);
accountPersistService.updateAccount(account);
}catch(AccountPersistException e){
throw new AccountServiceException("Unable to activate account.");
}
}
public void login(String id,String password) throws AccountServiceException{
try{
Account account=accountPersistService.readAccount(id);
if(account==null){
throw new AccountServiceException("Account does not exist.");
}
if(!account.isActivated){
throw new AccountServiceException("Account is disabled.");
}
if(!account.getPassword().equals(password)){
throw new AccountServiceException("Incorrect password");
}
}catch(AccountPersistException e){
throw new AccountServiceException("Unable to login.",e);
}
}
}
web的POM
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<modelVsersion>4.0.0</modelVsersion>
<parent>
<groupId>com.j.mvnbook.account</groupId>
<artifactId>account-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>accout-web</artifactId>
<packaging>war</packaging>
<name>Account web</name>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>account-service</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
</dependencies>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>1.0</version>
<configuration>
<container>
<containerId>tomcat7x</containerId>
<home>D:\cmd\apache-tomcat-7.0.27</home>
</container>
<configuration>
<type>standalone</type>
<home>${project.build.directory}/tomcat7x</home>
</configuration>
</configuration>
</plugin>
web的主代码
web.xml
<!DOCTYPE web-app PUBLIC
"~//Sun Microsystems,Inc.//DTD Web Application 2.3 //EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Sample Maven Project:Account Service</display-name>
<listener>
<listener-class>org.Springframework.web.context.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/account-persist.xml
classpath:/account-captcha.xml
classpath:/account-email.xml
classpath:/account-service.xml
</param-value>
</context-param>
<servlet>
<servlet-name>CaptchaImageServlet</servlet-name>
<servlet-class>com.j.mvnbook.account.web.CaptchaImageServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>SignUpServlet</servlet-name>
<servlet-class>com.j.mvnbook.account.web.SignUpServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ActivateServlet</servlet-name>
<servlet-class>com.j.mvnbook.account.web.ActivateServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.j.mvnbook.account.web.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CaptchaImageServlet</servlet-name>
<url-pattern>/captcha_image</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SignUpServlet</servlet-name>
<url-pattern>signup</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ActivateServlet</servlet-name>
<url-pattern>/activate</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Signup.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ page import="com.j.mvnbook.account.service.*,
org.springframework.context.ApplicationContext,
org.springframework.web.context.support.WebApplicationContextUtils"%>
<html>
<head>
<style type="text/css">
...
</style>
</head>
<body>
<%
ApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(getServletContext());
AccountService accountservice=(AccountService)context.getBean("accountService");
String captchaKey =accountservice.generateCaptchaKey();%>
<div class="text/fileld">
<h2>注册新用户</h2>
<form name="signup" action="signup" method="post">
<label>账户ID:</label><input type="test" name="id"></input></br>
<label>EMail:</label><input type="text" name="email"></input></br>
<label>显示名称:</label><input type="text" name="name"></input></br>
<label>密码:</label><input type="password" name="password"></input></br>
<label>确认密码:</label><input type="password" name="confirm_password"></input></br>
<label>验证码:</label><input type="text" name="email"></input></br>
<input type="hidden" name="captcha_key" value="<%=captchaKey%>"/>
<img src="<%=request.getContextPath()%>/captcha_image?key=<%=captchaKey%>"/>
</br>
<button>确认并提交</button>
</form>
</div>
</body>
</html>
captchaImageServlet.java
package com.j.mvnbook.account.web;
import java.io.IOException;
public class CaptchaImageServlet extends HttpServlet{
private ApplicationContext context;
private static final long serialVersionUID=5274323889605521606L;
@Override
public void init() throws ServletException
{
super.init();
context.=WebApplicationContextUtils.getWebApplicationContext(getServletContext());
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException
{
String key=requeset.getParameter("key");
if(key==null||key.langth()==0)
{
response.sendError(400,"No Captcha Key found");
}
else
{
AccountService service=(AccountService)context.getBean("accountService");
try{
response.setContentType("image/jpeg");
OutputStream out=response.getOutputStream();
out.write(service.generateCaptchaImage(key));
out.close();
}catch(AccountServiceException e)
{
response.sendError(404,e.getMessage());
}
}
}
}
SignUpServlet.java
package com.j.mvnbook.account.web;
import java.io.IOException;
import ...
public class SignUpServlet extends HttpServlet
{
private static final long serialVersionUID=4784742296013868199L;
private ApplicationContext context;
@Overrid
public void init() throws ServletException
{
super.init();
context=WebApplicationContextUtils.getWebApplicationContext(getServletContext());
}
@Overrid
protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
{
String id=req.getParameter("id");
String email=req.getParameter("email");
String name=req.getParameter("name");
String password=req.getParameter("password");
String confirmPassword=req.getParameter("confirm_Password");
String captchaValue=req.getParameter("captcha_Value");
if(id==null || id.length()==0 || email==null || email.length()==0 ||...||captchaValue.length()==0)
{
resp.send(400,"Parameter incomplete");
return;
}
AccountService service=(AccountService)context.getBean("accountService");
SignRequest request=new SignRequest();
request.setId(id);
request.setEmail(email);
request.setName(name);
request.setPassword(password);
request.setConfirmPassword(confirmPassword);
request.setCaptchaKey(captchaKey);
request.setCaptchaValue(CaptchaValue);
reuqest.setActivateServiceUrl(getServletContext().getRealPath("/")+"activate");
try{
service.signUp(request);
resp.getWriter().print("Account is Created,Please check your mail box for activation link.");
}catch(AccountServiceException e){
resp.sendError(400,e.getMessage());
return;
}
}
}
部署到本地Web容器
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>1.0</version>
<configuration>
<container>
<containerId>tomcat7x</containerId>
<home>D:\cmd\apache-tomcat-7.0.27</home>
</container>
<configuration>
<type>standalone</type>
<home>${project.build.directory}/tomcat7x</home>
</configuration>
</configuration>
</plugin>
部署到远程Web容器
<!--部署到远程web服务器-->
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>1.0</version>
<configuration>
<!--远程部署,type值为remote-->
<container>
<containerId>tomcat7x</containerId>
<type>remote</type>
</container>
<configuration>
<!--依赖于一个已经运行的容器-->
<type>runtime</type>
<!--声明热部署相关配置-->
<properties>
<cargo.remote.username>admin</cargo.remote.username>
<cargo.remote.password>admin123</cargo.remote.password>
<cargo.remote.manager.url>http:localhost:8080/manager</cargo.remote.manager.url>
</properties>
</configuration>
</configuration>
以上/可以实现一个简单的登录注册页面。